├── .editorconfig ├── .gitignore ├── LICENSE.txt ├── README.md ├── README.pdf ├── live.js └── package.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = crlf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Custom files 2 | *.yaml 3 | *.html 4 | .npmrc 5 | practice/ 6 | *.txt 7 | *.code-workspace 8 | ## -------------------- 9 | 10 | # Created by https://www.gitignore.io/api/java,gradle,windows,intellij+all,visualstudiocode 11 | # Edit at https://www.gitignore.io/?templates=java,gradle,windows,intellij+all,visualstudiocode 12 | 13 | ### Intellij+all ### 14 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 15 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 16 | 17 | # User-specific stuff 18 | .idea/**/workspace.xml 19 | .idea/**/tasks.xml 20 | .idea/**/usage.statistics.xml 21 | .idea/**/dictionaries 22 | .idea/**/shelf 23 | 24 | # Generated files 25 | .idea/**/contentModel.xml 26 | 27 | # Sensitive or high-churn files 28 | .idea/**/dataSources/ 29 | .idea/**/dataSources.ids 30 | .idea/**/dataSources.local.xml 31 | .idea/**/sqlDataSources.xml 32 | .idea/**/dynamic.xml 33 | .idea/**/uiDesigner.xml 34 | .idea/**/dbnavigator.xml 35 | 36 | # Gradle 37 | .idea/**/gradle.xml 38 | .idea/**/libraries 39 | 40 | # Gradle and Maven with auto-import 41 | # When using Gradle or Maven with auto-import, you should exclude module files, 42 | # since they will be recreated, and may cause churn. Uncomment if using 43 | # auto-import. 44 | # .idea/modules.xml 45 | # .idea/*.iml 46 | # .idea/modules 47 | # *.iml 48 | # *.ipr 49 | 50 | # CMake 51 | cmake-build-*/ 52 | 53 | # Mongo Explorer plugin 54 | .idea/**/mongoSettings.xml 55 | 56 | # File-based project format 57 | *.iws 58 | 59 | # IntelliJ 60 | out/ 61 | 62 | # mpeltonen/sbt-idea plugin 63 | .idea_modules/ 64 | 65 | # JIRA plugin 66 | atlassian-ide-plugin.xml 67 | 68 | # Cursive Clojure plugin 69 | .idea/replstate.xml 70 | 71 | # Crashlytics plugin (for Android Studio and IntelliJ) 72 | com_crashlytics_export_strings.xml 73 | crashlytics.properties 74 | crashlytics-build.properties 75 | fabric.properties 76 | 77 | # Editor-based Rest Client 78 | .idea/httpRequests 79 | 80 | # Android studio 3.1+ serialized cache file 81 | .idea/caches/build_file_checksums.ser 82 | 83 | ### Intellij+all Patch ### 84 | # Ignores the whole .idea folder and all .iml files 85 | # See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 86 | 87 | .idea/ 88 | 89 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 90 | 91 | *.iml 92 | modules.xml 93 | .idea/misc.xml 94 | *.ipr 95 | 96 | # Sonarlint plugin 97 | .idea/sonarlint 98 | 99 | ### Java ### 100 | # Compiled class file 101 | *.class 102 | 103 | # Log file 104 | *.log 105 | 106 | # BlueJ files 107 | *.ctxt 108 | 109 | # Mobile Tools for Java (J2ME) 110 | .mtj.tmp/ 111 | 112 | # Package Files # 113 | *.jar 114 | *.war 115 | *.nar 116 | *.ear 117 | *.zip 118 | *.tar.gz 119 | *.rar 120 | 121 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 122 | hs_err_pid* 123 | 124 | ### VisualStudioCode ### 125 | .vscode/* 126 | !.vscode/settings.json 127 | !.vscode/tasks.json 128 | !.vscode/launch.json 129 | !.vscode/extensions.json 130 | 131 | ### VisualStudioCode Patch ### 132 | # Ignore all local history of files 133 | .history 134 | 135 | ### Windows ### 136 | # Windows thumbnail cache files 137 | Thumbs.db 138 | Thumbs.db:encryptable 139 | ehthumbs.db 140 | ehthumbs_vista.db 141 | 142 | # Dump file 143 | *.stackdump 144 | 145 | # Folder config file 146 | [Dd]esktop.ini 147 | 148 | # Recycle Bin used on file shares 149 | $RECYCLE.BIN/ 150 | 151 | # Windows Installer files 152 | *.cab 153 | *.msi 154 | *.msix 155 | *.msm 156 | *.msp 157 | 158 | # Windows shortcuts 159 | *.lnk 160 | 161 | ### Gradle ### 162 | .gradle 163 | build/ 164 | 165 | # Ignore Gradle GUI config 166 | gradle-app.setting 167 | 168 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 169 | !gradle-wrapper.jar 170 | 171 | # Cache of project 172 | .gradletasknamecache 173 | 174 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 175 | # gradle/wrapper/gradle-wrapper.properties 176 | 177 | ### Gradle Patch ### 178 | **/build/ 179 | 180 | # End of https://www.gitignore.io/api/java,gradle,windows,intellij+all,visualstudiocode -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Attribution-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-ShareAlike 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-ShareAlike 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. Share means to provide material to the public by any means or 126 | process that requires permission under the Licensed Rights, such 127 | as reproduction, public display, public performance, distribution, 128 | dissemination, communication, or importation, and to make material 129 | available to the public including in ways that members of the 130 | public may access the material from a place and at a time 131 | individually chosen by them. 132 | 133 | l. Sui Generis Database Rights means rights other than copyright 134 | resulting from Directive 96/9/EC of the European Parliament and of 135 | the Council of 11 March 1996 on the legal protection of databases, 136 | as amended and/or succeeded, as well as other essentially 137 | equivalent rights anywhere in the world. 138 | 139 | m. You means the individual or entity exercising the Licensed Rights 140 | under this Public License. Your has a corresponding meaning. 141 | 142 | 143 | Section 2 -- Scope. 144 | 145 | a. License grant. 146 | 147 | 1. Subject to the terms and conditions of this Public License, 148 | the Licensor hereby grants You a worldwide, royalty-free, 149 | non-sublicensable, non-exclusive, irrevocable license to 150 | exercise the Licensed Rights in the Licensed Material to: 151 | 152 | a. reproduce and Share the Licensed Material, in whole or 153 | in part; and 154 | 155 | b. produce, reproduce, and Share Adapted Material. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. Additional offer from the Licensor -- Adapted Material. 186 | Every recipient of Adapted Material from You 187 | automatically receives an offer from the Licensor to 188 | exercise the Licensed Rights in the Adapted Material 189 | under the conditions of the Adapter's License You apply. 190 | 191 | c. No downstream restrictions. You may not offer or impose 192 | any additional or different terms or conditions on, or 193 | apply any Effective Technological Measures to, the 194 | Licensed Material if doing so restricts exercise of the 195 | Licensed Rights by any recipient of the Licensed 196 | Material. 197 | 198 | 6. No endorsement. Nothing in this Public License constitutes or 199 | may be construed as permission to assert or imply that You 200 | are, or that Your use of the Licensed Material is, connected 201 | with, or sponsored, endorsed, or granted official status by, 202 | the Licensor or others designated to receive attribution as 203 | provided in Section 3(a)(1)(A)(i). 204 | 205 | b. Other rights. 206 | 207 | 1. Moral rights, such as the right of integrity, are not 208 | licensed under this Public License, nor are publicity, 209 | privacy, and/or other similar personality rights; however, to 210 | the extent possible, the Licensor waives and/or agrees not to 211 | assert any such rights held by the Licensor to the limited 212 | extent necessary to allow You to exercise the Licensed 213 | Rights, but not otherwise. 214 | 215 | 2. Patent and trademark rights are not licensed under this 216 | Public License. 217 | 218 | 3. To the extent possible, the Licensor waives any right to 219 | collect royalties from You for the exercise of the Licensed 220 | Rights, whether directly or through a collecting society 221 | under any voluntary or waivable statutory or compulsory 222 | licensing scheme. In all other cases the Licensor expressly 223 | reserves any right to collect such royalties. 224 | 225 | 226 | Section 3 -- License Conditions. 227 | 228 | Your exercise of the Licensed Rights is expressly made subject to the 229 | following conditions. 230 | 231 | a. Attribution. 232 | 233 | 1. If You Share the Licensed Material (including in modified 234 | form), You must: 235 | 236 | a. retain the following if it is supplied by the Licensor 237 | with the Licensed Material: 238 | 239 | i. identification of the creator(s) of the Licensed 240 | Material and any others designated to receive 241 | attribution, in any reasonable manner requested by 242 | the Licensor (including by pseudonym if 243 | designated); 244 | 245 | ii. a copyright notice; 246 | 247 | iii. a notice that refers to this Public License; 248 | 249 | iv. a notice that refers to the disclaimer of 250 | warranties; 251 | 252 | v. a URI or hyperlink to the Licensed Material to the 253 | extent reasonably practicable; 254 | 255 | b. indicate if You modified the Licensed Material and 256 | retain an indication of any previous modifications; and 257 | 258 | c. indicate the Licensed Material is licensed under this 259 | Public License, and include the text of, or the URI or 260 | hyperlink to, this Public License. 261 | 262 | 2. You may satisfy the conditions in Section 3(a)(1) in any 263 | reasonable manner based on the medium, means, and context in 264 | which You Share the Licensed Material. For example, it may be 265 | reasonable to satisfy the conditions by providing a URI or 266 | hyperlink to a resource that includes the required 267 | information. 268 | 269 | 3. If requested by the Licensor, You must remove any of the 270 | information required by Section 3(a)(1)(A) to the extent 271 | reasonably practicable. 272 | 273 | b. ShareAlike. 274 | 275 | In addition to the conditions in Section 3(a), if You Share 276 | Adapted Material You produce, the following conditions also apply. 277 | 278 | 1. The Adapter's License You apply must be a Creative Commons 279 | license with the same License Elements, this version or 280 | later, or a BY-SA Compatible License. 281 | 282 | 2. You must include the text of, or the URI or hyperlink to, the 283 | Adapter's License You apply. You may satisfy this condition 284 | in any reasonable manner based on the medium, means, and 285 | context in which You Share Adapted Material. 286 | 287 | 3. You may not offer or impose any additional or different terms 288 | or conditions on, or apply any Effective Technological 289 | Measures to, Adapted Material that restrict exercise of the 290 | rights granted under the Adapter's License You apply. 291 | 292 | 293 | Section 4 -- Sui Generis Database Rights. 294 | 295 | Where the Licensed Rights include Sui Generis Database Rights that 296 | apply to Your use of the Licensed Material: 297 | 298 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 299 | to extract, reuse, reproduce, and Share all or a substantial 300 | portion of the contents of the database; 301 | 302 | b. if You include all or a substantial portion of the database 303 | contents in a database in which You have Sui Generis Database 304 | Rights, then the database in which You have Sui Generis Database 305 | Rights (but not its individual contents) is Adapted Material, 306 | 307 | including for purposes of Section 3(b); and 308 | c. You must comply with the conditions in Section 3(a) if You Share 309 | all or a substantial portion of the contents of the database. 310 | 311 | For the avoidance of doubt, this Section 4 supplements and does not 312 | replace Your obligations under this Public License where the Licensed 313 | Rights include other Copyright and Similar Rights. 314 | 315 | 316 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 317 | 318 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 319 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 320 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 321 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 322 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 323 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 324 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 325 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 326 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 327 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 328 | 329 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 330 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 331 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 332 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 333 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 334 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 335 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 336 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 337 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 338 | 339 | c. The disclaimer of warranties and limitation of liability provided 340 | above shall be interpreted in a manner that, to the extent 341 | possible, most closely approximates an absolute disclaimer and 342 | waiver of all liability. 343 | 344 | 345 | Section 6 -- Term and Termination. 346 | 347 | a. This Public License applies for the term of the Copyright and 348 | Similar Rights licensed here. However, if You fail to comply with 349 | this Public License, then Your rights under this Public License 350 | terminate automatically. 351 | 352 | b. Where Your right to use the Licensed Material has terminated under 353 | Section 6(a), it reinstates: 354 | 355 | 1. automatically as of the date the violation is cured, provided 356 | it is cured within 30 days of Your discovery of the 357 | violation; or 358 | 359 | 2. upon express reinstatement by the Licensor. 360 | 361 | For the avoidance of doubt, this Section 6(b) does not affect any 362 | right the Licensor may have to seek remedies for Your violations 363 | of this Public License. 364 | 365 | c. For the avoidance of doubt, the Licensor may also offer the 366 | Licensed Material under separate terms or conditions or stop 367 | distributing the Licensed Material at any time; however, doing so 368 | will not terminate this Public License. 369 | 370 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 371 | License. 372 | 373 | 374 | Section 7 -- Other Terms and Conditions. 375 | 376 | a. The Licensor shall not be bound by any additional or different 377 | terms or conditions communicated by You unless expressly agreed. 378 | 379 | b. Any arrangements, understandings, or agreements regarding the 380 | Licensed Material not stated herein are separate from and 381 | independent of the terms and conditions of this Public License. 382 | 383 | 384 | Section 8 -- Interpretation. 385 | 386 | a. For the avoidance of doubt, this Public License does not, and 387 | shall not be interpreted to, reduce, limit, restrict, or impose 388 | conditions on any use of the Licensed Material that could lawfully 389 | be made without permission under this Public License. 390 | 391 | b. To the extent possible, if any provision of this Public License is 392 | deemed unenforceable, it shall be automatically reformed to the 393 | minimum extent necessary to make it enforceable. If the provision 394 | cannot be reformed, it shall be severed from this Public License 395 | without affecting the enforceability of the remaining terms and 396 | conditions. 397 | 398 | c. No term or condition of this Public License will be waived and no 399 | failure to comply consented to unless expressly agreed to by the 400 | Licensor. 401 | 402 | d. Nothing in this Public License constitutes or may be interpreted 403 | as a limitation upon, or waiver of, any privileges and immunities 404 | that apply to the Licensor or You, including from the legal 405 | processes of any jurisdiction or authority. 406 | 407 | 408 | ======================================================================= 409 | 410 | Creative Commons is not a party to its public licenses. 411 | Notwithstanding, Creative Commons may elect to apply one of its public 412 | licenses to material it publishes and in those instances will be 413 | considered the “Licensor.” The text of the Creative Commons public 414 | licenses is dedicated to the public domain under the CC0 Public Domain 415 | Dedication. Except for the limited purpose of indicating that material 416 | is shared under a Creative Commons public license or as otherwise 417 | permitted by the Creative Commons policies published at 418 | creativecommons.org/policies, Creative Commons does not authorize the 419 | use of the trademark "Creative Commons" or any other trademark or logo 420 | of Creative Commons without its prior written consent including, 421 | without limitation, in connection with any unauthorized modifications 422 | to any of its public licenses or any other arrangements, 423 | understandings, or agreements concerning use of licensed material. For 424 | the avoidance of doubt, this paragraph does not form part of the public 425 | licenses. 426 | 427 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Angular 2 | 3 | > :warning: **DOCUMENTO EN DESARROLLO** :warning: 4 | 5 | ## Introducción 6 | 7 | **Angular** es un framework de desarrollo front-end, mantenido por Google, que permite crear aplicaciones web dinámicas y escalables utilizando TypeScript. Está diseñado para construir aplicaciones de una sola página (SPA) y sigue una arquitectura basada en componentes. 8 | 9 | Angular tiene sus raíces en **AngularJS**, lanzado en 2009 por Misko Hevery y Adam Abrons. En 2016, Google lanzó una versión completamente reescrita, **Angular 2**, basada en TypeScript. Desde entonces, Angular ha evolucionado como un framework moderno, mientras que AngularJS se mantiene como un proyecto separado con soporte limitado. 10 | 11 | Las **aplicaciones de una sola página** (_SPA_, por sus siglas en inglés) representan un enfoque moderno en el desarrollo web. A diferencia de las aplicaciones web tradicionales, donde cada interacción del usuario requiere cargar una nueva página desde el servidor, las SPAs cargan una única página HTML inicial. A partir de ahí, la aplicación actualiza dinámicamente el contenido en la misma página, utilizando JavaScript para interactuar con el servidor y manipular el DOM. Esto proporciona una experiencia de usuario más fluida y rápida, similar a la de una aplicación de escritorio o móvil. Angular está especialmente diseñado para facilitar la creación de SPAs, ofreciendo herramientas integradas para el enrutamiento, la gestión de estados y la actualización dinámica de la interfaz. 12 | 13 | Las principales **características** de Angular incluyen la vinculación bidireccional de datos, que permite la sincronización automática entre la vista y el modelo de datos; inyección de dependencias, que promueve la modularidad y la reutilización de código; y un conjunto de herramientas y bibliotecas que simplifican tareas comunes como la manipulación del DOM, la gestión de eventos y la realización de peticiones HTTP. 14 | 15 | Angular aprovecha la tecnología de los componentes web o [_"Web Components"_](https://developer.mozilla.org/es/docs/Web/API/Web_components) y el [_"Shadow DOM"_](https://developer.mozilla.org/es/docs/Web/API/Web_components/Using_shadow_DOM) para apoyar el desarrollo impulsado por componentes. La **arquitectura** de Angular puede resumirse en: 16 | 17 | - **Módulos**: Angular organiza la aplicación en módulos, que son conjuntos lógicos de componentes, servicios, directivas y otros artefactos relacionados. Los módulos ayudan a estructurar y organizar la aplicación, facilitando la carga y gestión de diferentes partes de la misma. 18 | 19 | - **Componentes**: son los bloques de construcción fundamentales de una aplicación Angular. Cada componente está asociado a una vista y un controlador (o en términos de Angular, un ViewModel). La vista define la interfaz de usuario, mientras que el controlador maneja la lógica y los datos relacionados con esa vista. 20 | 21 | - **Templates**: son archivos que definen la estructura y el diseño de las vistas en Angular. Utilizan una sintaxis especial, que combina HTML con extensiones específicas de Angular para la vinculación de datos y la manipulación de la interfaz de usuario. 22 | 23 | - **Directivas**: son atributos especiales en el HTML que permiten extender o modificar el comportamiento de los elementos DOM. Angular incluye directivas integradas, como `*ngIf` para controlar la visibilidad de elementos, o `*ngFor` para realizar bucles sobre conjuntos de datos. 24 | 25 | - **Servicios**: los servicios en Angular son objetos singleton que realizan funciones específicas y que pueden ser compartidos entre componentes. Se utilizan para encapsular la lógica de negocio, la manipulación de datos, o para realizar operaciones asíncronas, como llamadas HTTP. 26 | 27 | - **Inyección de dependencias**: Angular utiliza un sistema de inyección de dependencias para proporcionar a los componentes y servicios las dependencias que necesitan. Esto facilita la modularidad y la reutilización de código al tiempo que mejora la testabilidad. 28 | 29 | - **Vinculación de datos (_Data Binding_)**: Angular ofrece una potente vinculación de datos bidireccional, lo que significa que los cambios en el modelo de datos se reflejan automáticamente en la vista y viceversa. Esto simplifica la actualización de la interfaz de usuario en respuesta a eventos o cambios en los datos de la aplicación. 30 | 31 | - **Enrutamiento**: Angular proporciona un módulo de enrutamiento que permite la navegación entre las distintas vistas de la aplicación sin necesidad de recargar la página. Esto es esencial para construir aplicaciones de una sola página (SPA). 32 | 33 | Angular es ideal para proyectos grandes y complejos gracias a su arquitectura modular, su potente sistema de herramientas y su integración con TypeScript, que mejora la calidad y mantenibilidad del código. En resumen, Angular es una herramienta poderosa y versátil para desarrollar aplicaciones web modernas. 34 | 35 | :warning: **Sección introductoria generada por ChatGPT y mejorada por DeepSeek** :warning: 36 | 37 | ## Primeros pasos 38 | 39 | ### Instalación 40 | 41 | Angular requiere **Node.js**, que se instala descargándolo de su [página oficial](https://nodejs.org/). 42 | 43 | Cuando se instala **Node.js** también se instala **NPM** (_Node Package Manager_) que nos permite, entre otras cosas, gestionar las dependencias de un proyecto. 44 | 45 | Para desarrollar en Angular se puede utilizar como lenguaje de programación tanto **Javascript** como **TypeScript**, pero dado que **Angular está implementado con TypeScript**, se recomienda usar este lenguaje. 46 | 47 | Para instalar **Typescript** se utiliza la herramienta **NPM** ya que también está publicado como paquete. 48 | 49 | > :point_right: Para funcionar correctamente, cada **versión de Angular** requiere **una determinada versión de Node.js, TypeScript y RxJS**. Estas versiones pueden consultarse en esta [tabla de la documentación oficial](https://angular.dev/reference/versions). 50 | 51 | ```sh 52 | // Comprobar la versión de Node.js 53 | $ node -v 54 | 55 | // Comprobar la versión de NPM 56 | $ npm -v 57 | 58 | // Instalar TypeScript 59 | $ npm install -g typescript 60 | 61 | // Comprobar la versión de TypeScript 62 | $ tsc --version 63 | ``` 64 | 65 | ### DevTools 66 | 67 | Las **_Angular DevTools_** son una extensión para navegadores web (como [Chrome](https://chrome.google.com/webstore/detail/angular-developer-tools/ienfalfjdbdpebioblfackkekamfmbnh) o [Firefox](https://addons.mozilla.org/firefox/addon/angular-devtools/)) diseñada específicamente para ayudar a los desarrolladores a depurar, analizar y optimizar aplicaciones Angular. Esta herramienta es desarrollada y mantenida por el equipo de Angular en Google, y se integra directamente en las **"Herramientas para desarrolladores"** del navegador (_DevTools_). 68 | 69 | Se accede a estas herramientas (_DevTools_) de Chrome o Firefox en cualquier página web presionando `F12` o `Ctrl+Shift+I` (en Windows o Linux) y `Fn+F12` o `Cmd+Option+I` (en Mac). Una vez que las _DevTools_ del navegador estén abiertas, la extensión se encuentra en la pestaña "Angular". 70 | 71 | Las principales características de la extensión incluyen: 72 | 73 | - Árbol de componentes: 74 | 75 | - Permite visualizar la jerarquía de componentes de una aplicación Angular en tiempo real. 76 | 77 | - Muestra las propiedades (@Input) y estados de cada componente. 78 | 79 | - Facilita la identificación de relaciones entre componentes. 80 | 81 | - Profiler de rendimiento: 82 | 83 | - Ofrece una herramienta para analizar el rendimiento de la aplicación. 84 | 85 | - Muestra el tiempo de detección de cambios (change detection) y cómo afecta al rendimiento. 86 | 87 | - Ayuda a identificar cuellos de botella y componentes que pueden estar causando problemas de rendimiento. 88 | 89 | - Depuración de Inyección de Dependencias: 90 | 91 | - Permite inspeccionar los servicios inyectados en cada componente. 92 | 93 | - Muestra la jerarquía de inyección de dependencias y los proveedores asociados. 94 | 95 | - Estado de la aplicación: 96 | 97 | - Facilita la visualización del estado de la aplicación, especialmente cuando se utiliza librerías como NgRx o Akita. 98 | 99 | - Permite rastrear cambios en el estado y cómo afectan a los componentes. 100 | 101 | Más información en la [página de la extensión](https://angular.dev/tools/devtools). 102 | 103 | ### Angular CLI 104 | 105 | [**'Angular CLI'**](https://angular.dev/tools/cli) es la herramienta de línea de comandos estándar para crear, depurar construir y publicar aplicaciones Angular. 106 | 107 | Esta herramienta está publicada en **NPM** como el paquete `@angular/cli` e incluye el binario `ng`: 108 | 109 | ```sh 110 | // Instalación de 'Angular CLI' de forma global 111 | $ npm install -g @angular/cli 112 | 113 | // Comprobar la versión de 'Angular CLI' 114 | $ ng version 115 | 116 | // Ver la ayuda general 117 | $ ng help 118 | 119 | // Ver la ayuda de un comando en concreto como 'ng serve' 120 | $ ng serve --help 121 | ``` 122 | 123 | En la [documentación oficial](https://angular.dev/cli) para consultarse la lista completa de comandos y párametros que ofrece esta herramienta de Angular. 124 | 125 | #### Puesta en marcha del proyecto 126 | 127 | Las aplicaciones Angular se desarrollan en el contexto de una espacio de trabajo o [**_'workspace'_**](https://angular.dev/tools/cli/setup-local). Un espacio de trabajo puede contener múltiples aplicaciones y bibliotecas. 128 | 129 | Para crear un nuevo espacio de trabajo y una aplicación inicial dentro de este nuevo espacio de trabajo, se utiliza el comando `'ng new'`: 130 | 131 | ```sh 132 | // Crear una nueva aplicación en un workspace 133 | ng new my-app // Cambiando 'my-app' por el nombre de la nueva aplicación 134 | ``` 135 | 136 | Este comando nos solicitará **información** para configurar la aplicación inicial, pudiendo utilizar la configuración que viene por defecto. 137 | 138 | A continuación se instalan todas las bibliotecas y dependencias necesarias. Finalmente obtiene una aplicación inicial completamente funcional y las configuraciones necesarias para su depuración, pruebas y ejecución. 139 | 140 | Por defecto la aplicación se crea con el prefijo `app` que se usará en todos los componentes pero puede personalizarse usando el modificador `--prefix`. 141 | 142 | #### Desarrollo del proyecto 143 | 144 | **'Angular CLI'** incluye un [servidor de desarrollo](https://angular.dev/tools/cli/serve) lo que permite servir la aplicación fácilmente a nivel local. 145 | 146 | El comando `'ng serve'` inicia el servidor de desarrollo, observa los cambios en el código fuente, reconstruye automáticamente la aplicación cuando detecta algún cambio en el código y recarga la página en el navegador ("_hot-reloading_"): 147 | 148 | ```sh 149 | // Navegar dentro del espacio de trabajo 150 | cd my-app 151 | 152 | // Arranca el servidor y abre el navegador en 'http://localhost:4200' 153 | ng serve --open 154 | ``` 155 | 156 | #### Compilación del proyecto 157 | 158 | Para [compilar el proyecto](https://angular.dev/tools/cli/build) se utiliza el comando `'ng build'`. 159 | 160 | Se compilará el código TypeScript en código JavaScript, se optimizará el código, se empaquetará y se comprimirán (_'minify'_) los ficheros según sea necesario. 161 | 162 | Este comando ejecuta el constructor o _'builder'_ definido en el fichero `angular.json`. 163 | 164 | Por defecto, cuando se inicializa la aplicación con `'ng new'` se utiliza el constructor `@angular-devkit/build-angular:application`. 165 | 166 | Existen **4 constructores disponibles**, según el tipo de aplicación que se necesite construir. 167 | 168 | #### Despliegue del proyecto 169 | 170 | Una vez la aplicación está lista para su [despliegue](https://angular.dev/tools/cli/deployment), se puede realizar de varias formas, tanto manual como automática. 171 | 172 | Para realizar el despliegue de **forma automática**, se dispone del comando `'ng deploy'`. 173 | 174 | Existen desarrolladores _'third-party'_ que implementan capacidades de despliegue en diferentes plataformas. Se pueden añadir cualquiera de ellos al proyecto con `'ng add'`. 175 | 176 | - **Firebase hosting** 177 | 178 | - **Vercel** 179 | 180 | - **Netlify** 181 | 182 | - **Github Pages** 183 | 184 | - **Amazon Cloud S3** 185 | 186 | Cuando se agrega un paquete con capacidad de despliegue, automáticamente se actualizará la configuración del espacio de trabajo (archivo `angular.json`) con una sección de despliegue para el proyecto seleccionado. Luego, se puede usar el comando `'ng deploy'` para desplegar ese proyecto. 187 | 188 | Por ejemplo, podemos añadir un paquete de terceros para realizar el despliegue en **Firebase**: 189 | 190 | ```sh 191 | # Añade el 'package' en 'angular.json' 192 | $ ng add @angular/fire 193 | 194 | # Ejecuta el despliegue 195 | $ ng deploy 196 | ``` 197 | 198 | Y esto añadirá la sección `deploy` en el fichero `angular.json`: 199 | 200 | ```json 201 | { 202 | "projects": { 203 | "my-app": { 204 | "architect": { 205 | "deploy": { 206 | "builder": "@angular/fire:deploy", 207 | "options": { 208 | "target": "hosting:my-app" 209 | } 210 | } 211 | } 212 | } 213 | } 214 | } 215 | ``` 216 | 217 | #### Schematics 218 | 219 | Los [**_schematics_**](https://angular.dev/tools/cli/schematics) en Angular son una herramienta poderosa que permite automatizar tareas repetitivas en el desarrollo de aplicaciones, como la creación de componentes, servicios, módulos y otros elementos de la arquitectura de Angular. Básicamente, son plantillas o generadores de código que siguen un conjunto de reglas predefinidas para crear o modificar archivos en un proyecto Angular. 220 | 221 | Los _schematics_ forman parte del ecosistema de Angular. Se pueden modificar estos _schematics_ o definir otros nuevos para, por ejemplo, actualizar el código y corregir cambios importantes en una dependencia, o añadir una nueva opción de configuración o un nuevo framework a un proyecto existente. 222 | 223 | Los _schematics_ incluidos en la colección `@schematics/angular` se ejecutan de forma predeterminada mediante los comandos `ng generate` y `ng add`. Se puede usar la forma abreviada o la forma larga. La forma larga es útil en _schematics_ personalizados o colecciones de _schematics_: 224 | 225 | ```sh 226 | # FORMA ABREVIADA (usa el schematic 'component' de '@schematics/angular') 227 | $ ng generate component 228 | 229 | # FORMA LARGA 230 | $ ng generate @schematics/angular:component 231 | ``` 232 | 233 | Algunos de los _schematics_ que pueden usarse: 234 | 235 | - [`app-shell`](https://angular.dev/cli/generate/app-shell) 236 | - [`application`](https://angular.dev/cli/generate/application) 237 | - [`class`](https://angular.dev/cli/generate/class) 238 | - [`component`](https://angular.dev/cli/generate/component) 239 | - [`config`](https://angular.dev/cli/generate/config) 240 | - [`directive`](https://angular.dev/cli/generate/directive) 241 | - [`enum`](https://angular.dev/cli/generate/enum) 242 | - [`environments`](https://angular.dev/cli/generate/environments) 243 | - [`guard`](https://angular.dev/cli/generate/guard) 244 | - [`interceptor`](https://angular.dev/cli/generate/interceptor) 245 | - [`interface`](https://angular.dev/cli/generate/interface) 246 | - [`library`](https://angular.dev/cli/generate/library) 247 | - [`module`](https://angular.dev/cli/generate/module) 248 | - [`pipe`](https://angular.dev/cli/generate/pipe) 249 | - [`resolver`](https://angular.dev/cli/generate/resolver) 250 | - [`service`](https://angular.dev/cli/generate/service) 251 | - [`service-worker`](https://angular.dev/cli/generate/service-worker) 252 | - [`web-worker`](https://angular.dev/cli/generate/web-worker) 253 | 254 | #### Builders 255 | 256 | TODO 257 | 258 | ### Estructura de una aplicación Angular 259 | 260 | Cuando se ejecuta el comando `'ng new'` se instalan las bibliotecas y dependencias necesarias en el nuevo espacio de trabajo, además del **esqueleto funcional** de una aplicación dentro de la carpeta `src/`. 261 | 262 | Esta aplicación se considera la **aplicación principal** o **aplicación raíz**. El [directorio raíz](https://angular.dev/reference/configs/file-structure) del espacio de trabajo contiene todos los ficheros de configuración, etc.. necesarios para construir y servir la aplicación Angular. 263 | 264 | La aplicación inicial creada es la **aplicación por defecto** para todos los comandos lanzados a través de `ng`. 265 | 266 | Para un espacio de trabajo que contiene una única aplicación, la subcarpeta `src/` del espacio de trabajo contendrá los ficheros de código (lógica de la aplicación, datos y _assets_) de la aplicación raíz. 267 | 268 | Para espacios de trabajo de tipo _'multi-project'_, cada proyecto estará en su propia carpeta dentro de la carpeta `projects/`. 269 | 270 | #### Ficheros de configuración 271 | 272 | Todos los proyectos dentro del mismo espacio de trabajo o _'workspace'_ comparten los ficheros de configuración que están en la raíz del espacio de trabajo. Estos ficheros de configuración tienen **ámbito del espacio de trabajo** y por tanto su configuración afecta a todos los proyectos. 273 | 274 | Los archivos de configuración que están en la raíz del espacio de trabajo son los ficheros de configuración de la aplicación raíz. Para un espacio de trabajo de múltiples proyectos, los archivos de configuración específicos de cada proyecto estarán en la carpeta raíz de cada proyecto, dentro de `projects/project-name`. 275 | 276 | El fichero `'package.json'` es el [fichero estándar](https://docs.npmjs.com/cli/v10/configuring-npm/package-json) de **_NPM_** donde se almacenan las dependencias de terceros que se utilizará para todos los proyectos del espacio de trabajo. Contiene las bibliotecas que necesita la aplicación para ejecutarse tanto en desarrollo como producción: 277 | 278 | ```json 279 | { 280 | "dependencies": { 281 | "@angular/core": "^7.2.0" 282 | }, 283 | "devDependencies": { 284 | "@angular/cli": "7.2.0" 285 | } 286 | } 287 | ``` 288 | 289 | Además de las dependencias, el fichero `'package.json'` sirve para indicar información sobre el proyecto como el nombre, versión, nombre del autor, url del repositorio, etc.. y también como contenedor de scripts para automatizar tareas de operaciones rutinarias: 290 | 291 | ```json 292 | { 293 | "name": "my-app", 294 | "version": "0.0.0", 295 | "scripts": { 296 | "ng": "ng", 297 | "start": "ng serve", 298 | "build": "ng build", 299 | "test": "ng test", 300 | "lint": "ng lint", 301 | "e2e": "ng e2e" 302 | }, 303 | "devDependencies": { 304 | // ... 305 | } 306 | } 307 | ``` 308 | 309 | El fichero `'tsconfig.json'` contiene los parámetros de configuración por defecto de [TypeScript](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). 310 | 311 | El fichero `angular.json` contiene los [valores predeterminados](https://angular.dev/reference/configs/workspace-config#general-json-structure) de configuración para todos los proyectos en el área de trabajo, incluidas las opciones de configuración para compilar, servir y probar la aplicación. 312 | 313 | **Los cambios en los ficheros de configuración no se recargan automáticamente**. Hay que parar la servidor y volver a lanzarlo para que se carguen. 314 | 315 | #### Carpetas y ficheros de la aplicación 316 | 317 | La [estructura](https://angular.dev/reference/configs/file-structure#application-project-files) de la aplicación se distribuye en carpetas. 318 | 319 | A nivel raíz de la estructura de la aplicación tenemos las siguientes carpetas y ficheros: 320 | 321 | - **`src/`**: los archivos fuente para el proyecto de la aplicación a nivel raíz. 322 | 323 | - **`public/`**: contiene imágenes y otros archivos servidos de forma estática y que se copiarán tal cual cuando se cree la aplicación. 324 | 325 | - **`node_modules/`**: los paquetes **NPM** instalados para todo el espacio de trabajo 326 | 327 | - **`package.json`**: configura las [dependencias NPM](https://angular.dev/reference/configs/npm-packages) 328 | 329 | - **`angular.json`**: [configuración CLI](https://angular.dev/reference/configs/workspace-config) para todo el espacio de trabajo 330 | 331 | - **`tsconfig.json`**: la configuración base de TypeScript para los proyectos en el espacio de trabajo. 332 | 333 | Y otros ficheros como `package-lock.json`, `.gitignore`, `.editorconfig` o `README.md`. 334 | 335 | Dentro de la carpeta `/src` tenemos: 336 | 337 | - **`src/app`**: contiene los componentes Angular que componen la aplicación. 338 | 339 | - **`index.html`**: la página HTML principal que se sirve cuando alguien visita el sitio. Los archivos JavaScript y CSS se agregan automáticamente al crear la aplicación, por lo que normalmente no se necesita agregar ninguna etiqueta `