├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── LICENSE ├── Readme.md ├── assets ├── require │ └── require.js ├── script.js └── thebe │ ├── LICENSE │ ├── index.js │ ├── index.js.LICENSE.txt │ ├── index.js.map │ ├── main.css │ ├── mathjax.js │ └── thebe.css ├── docker-compose.yml ├── requirements.txt └── script.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **What is actually happening** 24 | The output you are getting. 25 | If applicable, add screenshots to help explain your problem. 26 | 27 | **Desktop (please complete the following information):** 28 | - Text gen version [e.g. tag: v1.7] 29 | - OS: [e.g. iOS] 30 | - Browser [e.g. chrome, safari] 31 | 32 | **Additional context** 33 | Add any other context about the problem here. 34 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Code Runner 2 | 3 | - allows you to run code in the chat interface 4 | - needs a jupyter server to connect to 5 | - runs the code in a jupyter kernel 6 | - allows the use of ipywidgets 7 | 8 | 9 | ![Screenshot_CodeRunner](https://github.com/xr4dsh/CodeRunner/assets/146959987/a79be0d9-30d3-4886-b281-48c8f4805a8b) 10 | 11 | # Setup 12 | To install it in text-generation-webui, go to the extensions folder and clone this repo. 13 | All requirements should already be installed. 14 | Afterwards install a jupyterlab server. I recommend docker because it does not screw with your personal files. 15 | 16 | ```bash 17 | # install extension 18 | $ cd extensions/ 19 | $ git clone https://github.com/xr4dsh/CodeRunner.git 20 | # setup jupyter server 21 | $ cd CodeRunner/ 22 | $ docker compose up 23 | ``` 24 | 25 | # Usage 26 | Enable the extension in the `Session tab`. 27 | In the `Chat tab` scroll to the bottom and type in the jupyter `server address` and the `token`. 28 | Click on `Connect` above. 29 | Afterwards you can test if it works in the Status section below by clicking on `run`. 30 | If it works you can ask the model to generate code and the code should be evaluated inline with the response. 31 | 32 | To get better results use a Character that has some examples how to use code cells: 33 | ~~~ 34 | The AI always create a python program that computes the output instead of answering it directly. 35 | 36 | Question: 37 | What is 10 + 5? 38 | Answer: 39 | ```python 40 | print(10 + 5) 41 | ``` 42 | Result: 15 43 | If you add 10 and 5 the result is 15 44 | 45 | Question: 46 | What is 30*10? 47 | Answer: 48 | ```python 49 | print(30 * 10) 50 | ``` 51 | Result: 300 52 | If you multiply 30 and 10 the result is 300 53 | ~~~ 54 | 55 | # How it works 56 | It works by using thebe to interact with a jupyter server that executes the python code and sends back the result. 57 | If the model generates a code block it is changed to a thebe code cell, this is detected by the browser that sends it to jupyter to execute. The response is displayed in the Browser and also send back to the model, this output is injected into the context and the model continues with the response. 58 | 59 | # Limitations 60 | - There is a 30 second timeout for execution of code cells, the cell might compute the result later, but the answer can not be injected into the context anymore. 61 | - Each time the frontend changes everything is recomputed, because the thebe cell ids are lost. 62 | 63 | # Build 64 | Currently thebe is already compiled in the assets folder if you want to build it yourself you can clone thebe from github. 65 | I made some changes to thebe so you need this PR: https://github.com/executablebooks/thebe/pull/725 66 | After it compiled you need to take the `index.js` file and if you dont want to load `require.js` from cloudflare eachtime you use it, you have to replace `https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js` by `file/extensions/CodeRunner/assets/require/require.js`. Then copy `index.js` and `mathjax.js` into `assets/thebe/`. 67 | -------------------------------------------------------------------------------- /assets/require/require.js: -------------------------------------------------------------------------------- 1 | /** vim: et:ts=4:sw=4:sts=4 2 | * @license RequireJS 2.3.6 Copyright jQuery Foundation and other contributors. 3 | * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE 4 | */ 5 | //Not using strict: uneven strict support in browsers, #392, and causes 6 | //problems with requirejs.exec()/transpiler plugins that may not be strict. 7 | /*jslint regexp: true, nomen: true, sloppy: true */ 8 | /*global window, navigator, document, importScripts, setTimeout, opera */ 9 | 10 | var requirejs, require, define; 11 | (function (global, setTimeout) { 12 | var req, s, head, baseElement, dataMain, src, 13 | interactiveScript, currentlyAddingScript, mainScript, subPath, 14 | version = '2.3.6', 15 | commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg, 16 | cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, 17 | jsSuffixRegExp = /\.js$/, 18 | currDirRegExp = /^\.\//, 19 | op = Object.prototype, 20 | ostring = op.toString, 21 | hasOwn = op.hasOwnProperty, 22 | isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), 23 | isWebWorker = !isBrowser && typeof importScripts !== 'undefined', 24 | //PS3 indicates loaded and complete, but need to wait for complete 25 | //specifically. Sequence is 'loading', 'loaded', execution, 26 | // then 'complete'. The UA check is unfortunate, but not sure how 27 | //to feature test w/o causing perf issues. 28 | readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? 29 | /^complete$/ : /^(complete|loaded)$/, 30 | defContextName = '_', 31 | //Oh the tragedy, detecting opera. See the usage of isOpera for reason. 32 | isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', 33 | contexts = {}, 34 | cfg = {}, 35 | globalDefQueue = [], 36 | useInteractive = false; 37 | 38 | //Could match something like ')//comment', do not lose the prefix to comment. 39 | function commentReplace(match, singlePrefix) { 40 | return singlePrefix || ''; 41 | } 42 | 43 | function isFunction(it) { 44 | return ostring.call(it) === '[object Function]'; 45 | } 46 | 47 | function isArray(it) { 48 | return ostring.call(it) === '[object Array]'; 49 | } 50 | 51 | /** 52 | * Helper function for iterating over an array. If the func returns 53 | * a true value, it will break out of the loop. 54 | */ 55 | function each(ary, func) { 56 | if (ary) { 57 | var i; 58 | for (i = 0; i < ary.length; i += 1) { 59 | if (ary[i] && func(ary[i], i, ary)) { 60 | break; 61 | } 62 | } 63 | } 64 | } 65 | 66 | /** 67 | * Helper function for iterating over an array backwards. If the func 68 | * returns a true value, it will break out of the loop. 69 | */ 70 | function eachReverse(ary, func) { 71 | if (ary) { 72 | var i; 73 | for (i = ary.length - 1; i > -1; i -= 1) { 74 | if (ary[i] && func(ary[i], i, ary)) { 75 | break; 76 | } 77 | } 78 | } 79 | } 80 | 81 | function hasProp(obj, prop) { 82 | return hasOwn.call(obj, prop); 83 | } 84 | 85 | function getOwn(obj, prop) { 86 | return hasProp(obj, prop) && obj[prop]; 87 | } 88 | 89 | /** 90 | * Cycles over properties in an object and calls a function for each 91 | * property value. If the function returns a truthy value, then the 92 | * iteration is stopped. 93 | */ 94 | function eachProp(obj, func) { 95 | var prop; 96 | for (prop in obj) { 97 | if (hasProp(obj, prop)) { 98 | if (func(obj[prop], prop)) { 99 | break; 100 | } 101 | } 102 | } 103 | } 104 | 105 | /** 106 | * Simple function to mix in properties from source into target, 107 | * but only if target does not already have a property of the same name. 108 | */ 109 | function mixin(target, source, force, deepStringMixin) { 110 | if (source) { 111 | eachProp(source, function (value, prop) { 112 | if (force || !hasProp(target, prop)) { 113 | if (deepStringMixin && typeof value === 'object' && value && 114 | !isArray(value) && !isFunction(value) && 115 | !(value instanceof RegExp)) { 116 | 117 | if (!target[prop]) { 118 | target[prop] = {}; 119 | } 120 | mixin(target[prop], value, force, deepStringMixin); 121 | } else { 122 | target[prop] = value; 123 | } 124 | } 125 | }); 126 | } 127 | return target; 128 | } 129 | 130 | //Similar to Function.prototype.bind, but the 'this' object is specified 131 | //first, since it is easier to read/figure out what 'this' will be. 132 | function bind(obj, fn) { 133 | return function () { 134 | return fn.apply(obj, arguments); 135 | }; 136 | } 137 | 138 | function scripts() { 139 | return document.getElementsByTagName('script'); 140 | } 141 | 142 | function defaultOnError(err) { 143 | throw err; 144 | } 145 | 146 | //Allow getting a global that is expressed in 147 | //dot notation, like 'a.b.c'. 148 | function getGlobal(value) { 149 | if (!value) { 150 | return value; 151 | } 152 | var g = global; 153 | each(value.split('.'), function (part) { 154 | g = g[part]; 155 | }); 156 | return g; 157 | } 158 | 159 | /** 160 | * Constructs an error with a pointer to an URL with more information. 161 | * @param {String} id the error ID that maps to an ID on a web page. 162 | * @param {String} message human readable error. 163 | * @param {Error} [err] the original error, if there is one. 164 | * 165 | * @returns {Error} 166 | */ 167 | function makeError(id, msg, err, requireModules) { 168 | var e = new Error(msg + '\nhttps://requirejs.org/docs/errors.html#' + id); 169 | e.requireType = id; 170 | e.requireModules = requireModules; 171 | if (err) { 172 | e.originalError = err; 173 | } 174 | return e; 175 | } 176 | 177 | if (typeof define !== 'undefined') { 178 | //If a define is already in play via another AMD loader, 179 | //do not overwrite. 180 | return; 181 | } 182 | 183 | if (typeof requirejs !== 'undefined') { 184 | if (isFunction(requirejs)) { 185 | //Do not overwrite an existing requirejs instance. 186 | return; 187 | } 188 | cfg = requirejs; 189 | requirejs = undefined; 190 | } 191 | 192 | //Allow for a require config object 193 | if (typeof require !== 'undefined' && !isFunction(require)) { 194 | //assume it is a config object. 195 | cfg = require; 196 | require = undefined; 197 | } 198 | 199 | function newContext(contextName) { 200 | var inCheckLoaded, Module, context, handlers, 201 | checkLoadedTimeoutId, 202 | config = { 203 | //Defaults. Do not set a default for map 204 | //config to speed up normalize(), which 205 | //will run faster if there is no default. 206 | waitSeconds: 7, 207 | baseUrl: './', 208 | paths: {}, 209 | bundles: {}, 210 | pkgs: {}, 211 | shim: {}, 212 | config: {} 213 | }, 214 | registry = {}, 215 | //registry of just enabled modules, to speed 216 | //cycle breaking code when lots of modules 217 | //are registered, but not activated. 218 | enabledRegistry = {}, 219 | undefEvents = {}, 220 | defQueue = [], 221 | defined = {}, 222 | urlFetched = {}, 223 | bundlesMap = {}, 224 | requireCounter = 1, 225 | unnormalizedCounter = 1; 226 | 227 | /** 228 | * Trims the . and .. from an array of path segments. 229 | * It will keep a leading path segment if a .. will become 230 | * the first path segment, to help with module name lookups, 231 | * which act like paths, but can be remapped. But the end result, 232 | * all paths that use this function should look normalized. 233 | * NOTE: this method MODIFIES the input array. 234 | * @param {Array} ary the array of path segments. 235 | */ 236 | function trimDots(ary) { 237 | var i, part; 238 | for (i = 0; i < ary.length; i++) { 239 | part = ary[i]; 240 | if (part === '.') { 241 | ary.splice(i, 1); 242 | i -= 1; 243 | } else if (part === '..') { 244 | // If at the start, or previous value is still .., 245 | // keep them so that when converted to a path it may 246 | // still work when converted to a path, even though 247 | // as an ID it is less than ideal. In larger point 248 | // releases, may be better to just kick out an error. 249 | if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { 250 | continue; 251 | } else if (i > 0) { 252 | ary.splice(i - 1, 2); 253 | i -= 2; 254 | } 255 | } 256 | } 257 | } 258 | 259 | /** 260 | * Given a relative module name, like ./something, normalize it to 261 | * a real name that can be mapped to a path. 262 | * @param {String} name the relative name 263 | * @param {String} baseName a real name that the name arg is relative 264 | * to. 265 | * @param {Boolean} applyMap apply the map config to the value. Should 266 | * only be done if this normalization is for a dependency ID. 267 | * @returns {String} normalized name 268 | */ 269 | function normalize(name, baseName, applyMap) { 270 | var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, 271 | foundMap, foundI, foundStarMap, starI, normalizedBaseParts, 272 | baseParts = (baseName && baseName.split('/')), 273 | map = config.map, 274 | starMap = map && map['*']; 275 | 276 | //Adjust any relative paths. 277 | if (name) { 278 | name = name.split('/'); 279 | lastIndex = name.length - 1; 280 | 281 | // If wanting node ID compatibility, strip .js from end 282 | // of IDs. Have to do this here, and not in nameToUrl 283 | // because node allows either .js or non .js to map 284 | // to same file. 285 | if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { 286 | name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); 287 | } 288 | 289 | // Starts with a '.' so need the baseName 290 | if (name[0].charAt(0) === '.' && baseParts) { 291 | //Convert baseName to array, and lop off the last part, 292 | //so that . matches that 'directory' and not name of the baseName's 293 | //module. For instance, baseName of 'one/two/three', maps to 294 | //'one/two/three.js', but we want the directory, 'one/two' for 295 | //this normalization. 296 | normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); 297 | name = normalizedBaseParts.concat(name); 298 | } 299 | 300 | trimDots(name); 301 | name = name.join('/'); 302 | } 303 | 304 | //Apply map config if available. 305 | if (applyMap && map && (baseParts || starMap)) { 306 | nameParts = name.split('/'); 307 | 308 | outerLoop: for (i = nameParts.length; i > 0; i -= 1) { 309 | nameSegment = nameParts.slice(0, i).join('/'); 310 | 311 | if (baseParts) { 312 | //Find the longest baseName segment match in the config. 313 | //So, do joins on the biggest to smallest lengths of baseParts. 314 | for (j = baseParts.length; j > 0; j -= 1) { 315 | mapValue = getOwn(map, baseParts.slice(0, j).join('/')); 316 | 317 | //baseName segment has config, find if it has one for 318 | //this name. 319 | if (mapValue) { 320 | mapValue = getOwn(mapValue, nameSegment); 321 | if (mapValue) { 322 | //Match, update name to the new value. 323 | foundMap = mapValue; 324 | foundI = i; 325 | break outerLoop; 326 | } 327 | } 328 | } 329 | } 330 | 331 | //Check for a star map match, but just hold on to it, 332 | //if there is a shorter segment match later in a matching 333 | //config, then favor over this star map. 334 | if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { 335 | foundStarMap = getOwn(starMap, nameSegment); 336 | starI = i; 337 | } 338 | } 339 | 340 | if (!foundMap && foundStarMap) { 341 | foundMap = foundStarMap; 342 | foundI = starI; 343 | } 344 | 345 | if (foundMap) { 346 | nameParts.splice(0, foundI, foundMap); 347 | name = nameParts.join('/'); 348 | } 349 | } 350 | 351 | // If the name points to a package's name, use 352 | // the package main instead. 353 | pkgMain = getOwn(config.pkgs, name); 354 | 355 | return pkgMain ? pkgMain : name; 356 | } 357 | 358 | function removeScript(name) { 359 | if (isBrowser) { 360 | each(scripts(), function (scriptNode) { 361 | if (scriptNode.getAttribute('data-requiremodule') === name && 362 | scriptNode.getAttribute('data-requirecontext') === context.contextName) { 363 | scriptNode.parentNode.removeChild(scriptNode); 364 | return true; 365 | } 366 | }); 367 | } 368 | } 369 | 370 | function hasPathFallback(id) { 371 | var pathConfig = getOwn(config.paths, id); 372 | if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { 373 | //Pop off the first array value, since it failed, and 374 | //retry 375 | pathConfig.shift(); 376 | context.require.undef(id); 377 | 378 | //Custom require that does not do map translation, since 379 | //ID is "absolute", already mapped/resolved. 380 | context.makeRequire(null, { 381 | skipMap: true 382 | })([id]); 383 | 384 | return true; 385 | } 386 | } 387 | 388 | //Turns a plugin!resource to [plugin, resource] 389 | //with the plugin being undefined if the name 390 | //did not have a plugin prefix. 391 | function splitPrefix(name) { 392 | var prefix, 393 | index = name ? name.indexOf('!') : -1; 394 | if (index > -1) { 395 | prefix = name.substring(0, index); 396 | name = name.substring(index + 1, name.length); 397 | } 398 | return [prefix, name]; 399 | } 400 | 401 | /** 402 | * Creates a module mapping that includes plugin prefix, module 403 | * name, and path. If parentModuleMap is provided it will 404 | * also normalize the name via require.normalize() 405 | * 406 | * @param {String} name the module name 407 | * @param {String} [parentModuleMap] parent module map 408 | * for the module name, used to resolve relative names. 409 | * @param {Boolean} isNormalized: is the ID already normalized. 410 | * This is true if this call is done for a define() module ID. 411 | * @param {Boolean} applyMap: apply the map config to the ID. 412 | * Should only be true if this map is for a dependency. 413 | * 414 | * @returns {Object} 415 | */ 416 | function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { 417 | var url, pluginModule, suffix, nameParts, 418 | prefix = null, 419 | parentName = parentModuleMap ? parentModuleMap.name : null, 420 | originalName = name, 421 | isDefine = true, 422 | normalizedName = ''; 423 | 424 | //If no name, then it means it is a require call, generate an 425 | //internal name. 426 | if (!name) { 427 | isDefine = false; 428 | name = '_@r' + (requireCounter += 1); 429 | } 430 | 431 | nameParts = splitPrefix(name); 432 | prefix = nameParts[0]; 433 | name = nameParts[1]; 434 | 435 | if (prefix) { 436 | prefix = normalize(prefix, parentName, applyMap); 437 | pluginModule = getOwn(defined, prefix); 438 | } 439 | 440 | //Account for relative paths if there is a base name. 441 | if (name) { 442 | if (prefix) { 443 | if (isNormalized) { 444 | normalizedName = name; 445 | } else if (pluginModule && pluginModule.normalize) { 446 | //Plugin is loaded, use its normalize method. 447 | normalizedName = pluginModule.normalize(name, function (name) { 448 | return normalize(name, parentName, applyMap); 449 | }); 450 | } else { 451 | // If nested plugin references, then do not try to 452 | // normalize, as it will not normalize correctly. This 453 | // places a restriction on resourceIds, and the longer 454 | // term solution is not to normalize until plugins are 455 | // loaded and all normalizations to allow for async 456 | // loading of a loader plugin. But for now, fixes the 457 | // common uses. Details in #1131 458 | normalizedName = name.indexOf('!') === -1 ? 459 | normalize(name, parentName, applyMap) : 460 | name; 461 | } 462 | } else { 463 | //A regular module. 464 | normalizedName = normalize(name, parentName, applyMap); 465 | 466 | //Normalized name may be a plugin ID due to map config 467 | //application in normalize. The map config values must 468 | //already be normalized, so do not need to redo that part. 469 | nameParts = splitPrefix(normalizedName); 470 | prefix = nameParts[0]; 471 | normalizedName = nameParts[1]; 472 | isNormalized = true; 473 | 474 | url = context.nameToUrl(normalizedName); 475 | } 476 | } 477 | 478 | //If the id is a plugin id that cannot be determined if it needs 479 | //normalization, stamp it with a unique ID so two matching relative 480 | //ids that may conflict can be separate. 481 | suffix = prefix && !pluginModule && !isNormalized ? 482 | '_unnormalized' + (unnormalizedCounter += 1) : 483 | ''; 484 | 485 | return { 486 | prefix: prefix, 487 | name: normalizedName, 488 | parentMap: parentModuleMap, 489 | unnormalized: !!suffix, 490 | url: url, 491 | originalName: originalName, 492 | isDefine: isDefine, 493 | id: (prefix ? 494 | prefix + '!' + normalizedName : 495 | normalizedName) + suffix 496 | }; 497 | } 498 | 499 | function getModule(depMap) { 500 | var id = depMap.id, 501 | mod = getOwn(registry, id); 502 | 503 | if (!mod) { 504 | mod = registry[id] = new context.Module(depMap); 505 | } 506 | 507 | return mod; 508 | } 509 | 510 | function on(depMap, name, fn) { 511 | var id = depMap.id, 512 | mod = getOwn(registry, id); 513 | 514 | if (hasProp(defined, id) && 515 | (!mod || mod.defineEmitComplete)) { 516 | if (name === 'defined') { 517 | fn(defined[id]); 518 | } 519 | } else { 520 | mod = getModule(depMap); 521 | if (mod.error && name === 'error') { 522 | fn(mod.error); 523 | } else { 524 | mod.on(name, fn); 525 | } 526 | } 527 | } 528 | 529 | function onError(err, errback) { 530 | var ids = err.requireModules, 531 | notified = false; 532 | 533 | if (errback) { 534 | errback(err); 535 | } else { 536 | each(ids, function (id) { 537 | var mod = getOwn(registry, id); 538 | if (mod) { 539 | //Set error on module, so it skips timeout checks. 540 | mod.error = err; 541 | if (mod.events.error) { 542 | notified = true; 543 | mod.emit('error', err); 544 | } 545 | } 546 | }); 547 | 548 | if (!notified) { 549 | req.onError(err); 550 | } 551 | } 552 | } 553 | 554 | /** 555 | * Internal method to transfer globalQueue items to this context's 556 | * defQueue. 557 | */ 558 | function takeGlobalQueue() { 559 | //Push all the globalDefQueue items into the context's defQueue 560 | if (globalDefQueue.length) { 561 | each(globalDefQueue, function(queueItem) { 562 | var id = queueItem[0]; 563 | if (typeof id === 'string') { 564 | context.defQueueMap[id] = true; 565 | } 566 | defQueue.push(queueItem); 567 | }); 568 | globalDefQueue = []; 569 | } 570 | } 571 | 572 | handlers = { 573 | 'require': function (mod) { 574 | if (mod.require) { 575 | return mod.require; 576 | } else { 577 | return (mod.require = context.makeRequire(mod.map)); 578 | } 579 | }, 580 | 'exports': function (mod) { 581 | mod.usingExports = true; 582 | if (mod.map.isDefine) { 583 | if (mod.exports) { 584 | return (defined[mod.map.id] = mod.exports); 585 | } else { 586 | return (mod.exports = defined[mod.map.id] = {}); 587 | } 588 | } 589 | }, 590 | 'module': function (mod) { 591 | if (mod.module) { 592 | return mod.module; 593 | } else { 594 | return (mod.module = { 595 | id: mod.map.id, 596 | uri: mod.map.url, 597 | config: function () { 598 | return getOwn(config.config, mod.map.id) || {}; 599 | }, 600 | exports: mod.exports || (mod.exports = {}) 601 | }); 602 | } 603 | } 604 | }; 605 | 606 | function cleanRegistry(id) { 607 | //Clean up machinery used for waiting modules. 608 | delete registry[id]; 609 | delete enabledRegistry[id]; 610 | } 611 | 612 | function breakCycle(mod, traced, processed) { 613 | var id = mod.map.id; 614 | 615 | if (mod.error) { 616 | mod.emit('error', mod.error); 617 | } else { 618 | traced[id] = true; 619 | each(mod.depMaps, function (depMap, i) { 620 | var depId = depMap.id, 621 | dep = getOwn(registry, depId); 622 | 623 | //Only force things that have not completed 624 | //being defined, so still in the registry, 625 | //and only if it has not been matched up 626 | //in the module already. 627 | if (dep && !mod.depMatched[i] && !processed[depId]) { 628 | if (getOwn(traced, depId)) { 629 | mod.defineDep(i, defined[depId]); 630 | mod.check(); //pass false? 631 | } else { 632 | breakCycle(dep, traced, processed); 633 | } 634 | } 635 | }); 636 | processed[id] = true; 637 | } 638 | } 639 | 640 | function checkLoaded() { 641 | var err, usingPathFallback, 642 | waitInterval = config.waitSeconds * 1000, 643 | //It is possible to disable the wait interval by using waitSeconds of 0. 644 | expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), 645 | noLoads = [], 646 | reqCalls = [], 647 | stillLoading = false, 648 | needCycleCheck = true; 649 | 650 | //Do not bother if this call was a result of a cycle break. 651 | if (inCheckLoaded) { 652 | return; 653 | } 654 | 655 | inCheckLoaded = true; 656 | 657 | //Figure out the state of all the modules. 658 | eachProp(enabledRegistry, function (mod) { 659 | var map = mod.map, 660 | modId = map.id; 661 | 662 | //Skip things that are not enabled or in error state. 663 | if (!mod.enabled) { 664 | return; 665 | } 666 | 667 | if (!map.isDefine) { 668 | reqCalls.push(mod); 669 | } 670 | 671 | if (!mod.error) { 672 | //If the module should be executed, and it has not 673 | //been inited and time is up, remember it. 674 | if (!mod.inited && expired) { 675 | if (hasPathFallback(modId)) { 676 | usingPathFallback = true; 677 | stillLoading = true; 678 | } else { 679 | noLoads.push(modId); 680 | removeScript(modId); 681 | } 682 | } else if (!mod.inited && mod.fetched && map.isDefine) { 683 | stillLoading = true; 684 | if (!map.prefix) { 685 | //No reason to keep looking for unfinished 686 | //loading. If the only stillLoading is a 687 | //plugin resource though, keep going, 688 | //because it may be that a plugin resource 689 | //is waiting on a non-plugin cycle. 690 | return (needCycleCheck = false); 691 | } 692 | } 693 | } 694 | }); 695 | 696 | if (expired && noLoads.length) { 697 | //If wait time expired, throw error of unloaded modules. 698 | err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); 699 | err.contextName = context.contextName; 700 | return onError(err); 701 | } 702 | 703 | //Not expired, check for a cycle. 704 | if (needCycleCheck) { 705 | each(reqCalls, function (mod) { 706 | breakCycle(mod, {}, {}); 707 | }); 708 | } 709 | 710 | //If still waiting on loads, and the waiting load is something 711 | //other than a plugin resource, or there are still outstanding 712 | //scripts, then just try back later. 713 | if ((!expired || usingPathFallback) && stillLoading) { 714 | //Something is still waiting to load. Wait for it, but only 715 | //if a timeout is not already in effect. 716 | if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { 717 | checkLoadedTimeoutId = setTimeout(function () { 718 | checkLoadedTimeoutId = 0; 719 | checkLoaded(); 720 | }, 50); 721 | } 722 | } 723 | 724 | inCheckLoaded = false; 725 | } 726 | 727 | Module = function (map) { 728 | this.events = getOwn(undefEvents, map.id) || {}; 729 | this.map = map; 730 | this.shim = getOwn(config.shim, map.id); 731 | this.depExports = []; 732 | this.depMaps = []; 733 | this.depMatched = []; 734 | this.pluginMaps = {}; 735 | this.depCount = 0; 736 | 737 | /* this.exports this.factory 738 | this.depMaps = [], 739 | this.enabled, this.fetched 740 | */ 741 | }; 742 | 743 | Module.prototype = { 744 | init: function (depMaps, factory, errback, options) { 745 | options = options || {}; 746 | 747 | //Do not do more inits if already done. Can happen if there 748 | //are multiple define calls for the same module. That is not 749 | //a normal, common case, but it is also not unexpected. 750 | if (this.inited) { 751 | return; 752 | } 753 | 754 | this.factory = factory; 755 | 756 | if (errback) { 757 | //Register for errors on this module. 758 | this.on('error', errback); 759 | } else if (this.events.error) { 760 | //If no errback already, but there are error listeners 761 | //on this module, set up an errback to pass to the deps. 762 | errback = bind(this, function (err) { 763 | this.emit('error', err); 764 | }); 765 | } 766 | 767 | //Do a copy of the dependency array, so that 768 | //source inputs are not modified. For example 769 | //"shim" deps are passed in here directly, and 770 | //doing a direct modification of the depMaps array 771 | //would affect that config. 772 | this.depMaps = depMaps && depMaps.slice(0); 773 | 774 | this.errback = errback; 775 | 776 | //Indicate this module has be initialized 777 | this.inited = true; 778 | 779 | this.ignore = options.ignore; 780 | 781 | //Could have option to init this module in enabled mode, 782 | //or could have been previously marked as enabled. However, 783 | //the dependencies are not known until init is called. So 784 | //if enabled previously, now trigger dependencies as enabled. 785 | if (options.enabled || this.enabled) { 786 | //Enable this module and dependencies. 787 | //Will call this.check() 788 | this.enable(); 789 | } else { 790 | this.check(); 791 | } 792 | }, 793 | 794 | defineDep: function (i, depExports) { 795 | //Because of cycles, defined callback for a given 796 | //export can be called more than once. 797 | if (!this.depMatched[i]) { 798 | this.depMatched[i] = true; 799 | this.depCount -= 1; 800 | this.depExports[i] = depExports; 801 | } 802 | }, 803 | 804 | fetch: function () { 805 | if (this.fetched) { 806 | return; 807 | } 808 | this.fetched = true; 809 | 810 | context.startTime = (new Date()).getTime(); 811 | 812 | var map = this.map; 813 | 814 | //If the manager is for a plugin managed resource, 815 | //ask the plugin to load it now. 816 | if (this.shim) { 817 | context.makeRequire(this.map, { 818 | enableBuildCallback: true 819 | })(this.shim.deps || [], bind(this, function () { 820 | return map.prefix ? this.callPlugin() : this.load(); 821 | })); 822 | } else { 823 | //Regular dependency. 824 | return map.prefix ? this.callPlugin() : this.load(); 825 | } 826 | }, 827 | 828 | load: function () { 829 | var url = this.map.url; 830 | 831 | //Regular dependency. 832 | if (!urlFetched[url]) { 833 | urlFetched[url] = true; 834 | context.load(this.map.id, url); 835 | } 836 | }, 837 | 838 | /** 839 | * Checks if the module is ready to define itself, and if so, 840 | * define it. 841 | */ 842 | check: function () { 843 | if (!this.enabled || this.enabling) { 844 | return; 845 | } 846 | 847 | var err, cjsModule, 848 | id = this.map.id, 849 | depExports = this.depExports, 850 | exports = this.exports, 851 | factory = this.factory; 852 | 853 | if (!this.inited) { 854 | // Only fetch if not already in the defQueue. 855 | if (!hasProp(context.defQueueMap, id)) { 856 | this.fetch(); 857 | } 858 | } else if (this.error) { 859 | this.emit('error', this.error); 860 | } else if (!this.defining) { 861 | //The factory could trigger another require call 862 | //that would result in checking this module to 863 | //define itself again. If already in the process 864 | //of doing that, skip this work. 865 | this.defining = true; 866 | 867 | if (this.depCount < 1 && !this.defined) { 868 | if (isFunction(factory)) { 869 | //If there is an error listener, favor passing 870 | //to that instead of throwing an error. However, 871 | //only do it for define()'d modules. require 872 | //errbacks should not be called for failures in 873 | //their callbacks (#699). However if a global 874 | //onError is set, use that. 875 | if ((this.events.error && this.map.isDefine) || 876 | req.onError !== defaultOnError) { 877 | try { 878 | exports = context.execCb(id, factory, depExports, exports); 879 | } catch (e) { 880 | err = e; 881 | } 882 | } else { 883 | exports = context.execCb(id, factory, depExports, exports); 884 | } 885 | 886 | // Favor return value over exports. If node/cjs in play, 887 | // then will not have a return value anyway. Favor 888 | // module.exports assignment over exports object. 889 | if (this.map.isDefine && exports === undefined) { 890 | cjsModule = this.module; 891 | if (cjsModule) { 892 | exports = cjsModule.exports; 893 | } else if (this.usingExports) { 894 | //exports already set the defined value. 895 | exports = this.exports; 896 | } 897 | } 898 | 899 | if (err) { 900 | err.requireMap = this.map; 901 | err.requireModules = this.map.isDefine ? [this.map.id] : null; 902 | err.requireType = this.map.isDefine ? 'define' : 'require'; 903 | return onError((this.error = err)); 904 | } 905 | 906 | } else { 907 | //Just a literal value 908 | exports = factory; 909 | } 910 | 911 | this.exports = exports; 912 | 913 | if (this.map.isDefine && !this.ignore) { 914 | defined[id] = exports; 915 | 916 | if (req.onResourceLoad) { 917 | var resLoadMaps = []; 918 | each(this.depMaps, function (depMap) { 919 | resLoadMaps.push(depMap.normalizedMap || depMap); 920 | }); 921 | req.onResourceLoad(context, this.map, resLoadMaps); 922 | } 923 | } 924 | 925 | //Clean up 926 | cleanRegistry(id); 927 | 928 | this.defined = true; 929 | } 930 | 931 | //Finished the define stage. Allow calling check again 932 | //to allow define notifications below in the case of a 933 | //cycle. 934 | this.defining = false; 935 | 936 | if (this.defined && !this.defineEmitted) { 937 | this.defineEmitted = true; 938 | this.emit('defined', this.exports); 939 | this.defineEmitComplete = true; 940 | } 941 | 942 | } 943 | }, 944 | 945 | callPlugin: function () { 946 | var map = this.map, 947 | id = map.id, 948 | //Map already normalized the prefix. 949 | pluginMap = makeModuleMap(map.prefix); 950 | 951 | //Mark this as a dependency for this plugin, so it 952 | //can be traced for cycles. 953 | this.depMaps.push(pluginMap); 954 | 955 | on(pluginMap, 'defined', bind(this, function (plugin) { 956 | var load, normalizedMap, normalizedMod, 957 | bundleId = getOwn(bundlesMap, this.map.id), 958 | name = this.map.name, 959 | parentName = this.map.parentMap ? this.map.parentMap.name : null, 960 | localRequire = context.makeRequire(map.parentMap, { 961 | enableBuildCallback: true 962 | }); 963 | 964 | //If current map is not normalized, wait for that 965 | //normalized name to load instead of continuing. 966 | if (this.map.unnormalized) { 967 | //Normalize the ID if the plugin allows it. 968 | if (plugin.normalize) { 969 | name = plugin.normalize(name, function (name) { 970 | return normalize(name, parentName, true); 971 | }) || ''; 972 | } 973 | 974 | //prefix and name should already be normalized, no need 975 | //for applying map config again either. 976 | normalizedMap = makeModuleMap(map.prefix + '!' + name, 977 | this.map.parentMap, 978 | true); 979 | on(normalizedMap, 980 | 'defined', bind(this, function (value) { 981 | this.map.normalizedMap = normalizedMap; 982 | this.init([], function () { return value; }, null, { 983 | enabled: true, 984 | ignore: true 985 | }); 986 | })); 987 | 988 | normalizedMod = getOwn(registry, normalizedMap.id); 989 | if (normalizedMod) { 990 | //Mark this as a dependency for this plugin, so it 991 | //can be traced for cycles. 992 | this.depMaps.push(normalizedMap); 993 | 994 | if (this.events.error) { 995 | normalizedMod.on('error', bind(this, function (err) { 996 | this.emit('error', err); 997 | })); 998 | } 999 | normalizedMod.enable(); 1000 | } 1001 | 1002 | return; 1003 | } 1004 | 1005 | //If a paths config, then just load that file instead to 1006 | //resolve the plugin, as it is built into that paths layer. 1007 | if (bundleId) { 1008 | this.map.url = context.nameToUrl(bundleId); 1009 | this.load(); 1010 | return; 1011 | } 1012 | 1013 | load = bind(this, function (value) { 1014 | this.init([], function () { return value; }, null, { 1015 | enabled: true 1016 | }); 1017 | }); 1018 | 1019 | load.error = bind(this, function (err) { 1020 | this.inited = true; 1021 | this.error = err; 1022 | err.requireModules = [id]; 1023 | 1024 | //Remove temp unnormalized modules for this module, 1025 | //since they will never be resolved otherwise now. 1026 | eachProp(registry, function (mod) { 1027 | if (mod.map.id.indexOf(id + '_unnormalized') === 0) { 1028 | cleanRegistry(mod.map.id); 1029 | } 1030 | }); 1031 | 1032 | onError(err); 1033 | }); 1034 | 1035 | //Allow plugins to load other code without having to know the 1036 | //context or how to 'complete' the load. 1037 | load.fromText = bind(this, function (text, textAlt) { 1038 | /*jslint evil: true */ 1039 | var moduleName = map.name, 1040 | moduleMap = makeModuleMap(moduleName), 1041 | hasInteractive = useInteractive; 1042 | 1043 | //As of 2.1.0, support just passing the text, to reinforce 1044 | //fromText only being called once per resource. Still 1045 | //support old style of passing moduleName but discard 1046 | //that moduleName in favor of the internal ref. 1047 | if (textAlt) { 1048 | text = textAlt; 1049 | } 1050 | 1051 | //Turn off interactive script matching for IE for any define 1052 | //calls in the text, then turn it back on at the end. 1053 | if (hasInteractive) { 1054 | useInteractive = false; 1055 | } 1056 | 1057 | //Prime the system by creating a module instance for 1058 | //it. 1059 | getModule(moduleMap); 1060 | 1061 | //Transfer any config to this other module. 1062 | if (hasProp(config.config, id)) { 1063 | config.config[moduleName] = config.config[id]; 1064 | } 1065 | 1066 | try { 1067 | req.exec(text); 1068 | } catch (e) { 1069 | return onError(makeError('fromtexteval', 1070 | 'fromText eval for ' + id + 1071 | ' failed: ' + e, 1072 | e, 1073 | [id])); 1074 | } 1075 | 1076 | if (hasInteractive) { 1077 | useInteractive = true; 1078 | } 1079 | 1080 | //Mark this as a dependency for the plugin 1081 | //resource 1082 | this.depMaps.push(moduleMap); 1083 | 1084 | //Support anonymous modules. 1085 | context.completeLoad(moduleName); 1086 | 1087 | //Bind the value of that module to the value for this 1088 | //resource ID. 1089 | localRequire([moduleName], load); 1090 | }); 1091 | 1092 | //Use parentName here since the plugin's name is not reliable, 1093 | //could be some weird string with no path that actually wants to 1094 | //reference the parentName's path. 1095 | plugin.load(map.name, localRequire, load, config); 1096 | })); 1097 | 1098 | context.enable(pluginMap, this); 1099 | this.pluginMaps[pluginMap.id] = pluginMap; 1100 | }, 1101 | 1102 | enable: function () { 1103 | enabledRegistry[this.map.id] = this; 1104 | this.enabled = true; 1105 | 1106 | //Set flag mentioning that the module is enabling, 1107 | //so that immediate calls to the defined callbacks 1108 | //for dependencies do not trigger inadvertent load 1109 | //with the depCount still being zero. 1110 | this.enabling = true; 1111 | 1112 | //Enable each dependency 1113 | each(this.depMaps, bind(this, function (depMap, i) { 1114 | var id, mod, handler; 1115 | 1116 | if (typeof depMap === 'string') { 1117 | //Dependency needs to be converted to a depMap 1118 | //and wired up to this module. 1119 | depMap = makeModuleMap(depMap, 1120 | (this.map.isDefine ? this.map : this.map.parentMap), 1121 | false, 1122 | !this.skipMap); 1123 | this.depMaps[i] = depMap; 1124 | 1125 | handler = getOwn(handlers, depMap.id); 1126 | 1127 | if (handler) { 1128 | this.depExports[i] = handler(this); 1129 | return; 1130 | } 1131 | 1132 | this.depCount += 1; 1133 | 1134 | on(depMap, 'defined', bind(this, function (depExports) { 1135 | if (this.undefed) { 1136 | return; 1137 | } 1138 | this.defineDep(i, depExports); 1139 | this.check(); 1140 | })); 1141 | 1142 | if (this.errback) { 1143 | on(depMap, 'error', bind(this, this.errback)); 1144 | } else if (this.events.error) { 1145 | // No direct errback on this module, but something 1146 | // else is listening for errors, so be sure to 1147 | // propagate the error correctly. 1148 | on(depMap, 'error', bind(this, function(err) { 1149 | this.emit('error', err); 1150 | })); 1151 | } 1152 | } 1153 | 1154 | id = depMap.id; 1155 | mod = registry[id]; 1156 | 1157 | //Skip special modules like 'require', 'exports', 'module' 1158 | //Also, don't call enable if it is already enabled, 1159 | //important in circular dependency cases. 1160 | if (!hasProp(handlers, id) && mod && !mod.enabled) { 1161 | context.enable(depMap, this); 1162 | } 1163 | })); 1164 | 1165 | //Enable each plugin that is used in 1166 | //a dependency 1167 | eachProp(this.pluginMaps, bind(this, function (pluginMap) { 1168 | var mod = getOwn(registry, pluginMap.id); 1169 | if (mod && !mod.enabled) { 1170 | context.enable(pluginMap, this); 1171 | } 1172 | })); 1173 | 1174 | this.enabling = false; 1175 | 1176 | this.check(); 1177 | }, 1178 | 1179 | on: function (name, cb) { 1180 | var cbs = this.events[name]; 1181 | if (!cbs) { 1182 | cbs = this.events[name] = []; 1183 | } 1184 | cbs.push(cb); 1185 | }, 1186 | 1187 | emit: function (name, evt) { 1188 | each(this.events[name], function (cb) { 1189 | cb(evt); 1190 | }); 1191 | if (name === 'error') { 1192 | //Now that the error handler was triggered, remove 1193 | //the listeners, since this broken Module instance 1194 | //can stay around for a while in the registry. 1195 | delete this.events[name]; 1196 | } 1197 | } 1198 | }; 1199 | 1200 | function callGetModule(args) { 1201 | //Skip modules already defined. 1202 | if (!hasProp(defined, args[0])) { 1203 | getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); 1204 | } 1205 | } 1206 | 1207 | function removeListener(node, func, name, ieName) { 1208 | //Favor detachEvent because of IE9 1209 | //issue, see attachEvent/addEventListener comment elsewhere 1210 | //in this file. 1211 | if (node.detachEvent && !isOpera) { 1212 | //Probably IE. If not it will throw an error, which will be 1213 | //useful to know. 1214 | if (ieName) { 1215 | node.detachEvent(ieName, func); 1216 | } 1217 | } else { 1218 | node.removeEventListener(name, func, false); 1219 | } 1220 | } 1221 | 1222 | /** 1223 | * Given an event from a script node, get the requirejs info from it, 1224 | * and then removes the event listeners on the node. 1225 | * @param {Event} evt 1226 | * @returns {Object} 1227 | */ 1228 | function getScriptData(evt) { 1229 | //Using currentTarget instead of target for Firefox 2.0's sake. Not 1230 | //all old browsers will be supported, but this one was easy enough 1231 | //to support and still makes sense. 1232 | var node = evt.currentTarget || evt.srcElement; 1233 | 1234 | //Remove the listeners once here. 1235 | removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); 1236 | removeListener(node, context.onScriptError, 'error'); 1237 | 1238 | return { 1239 | node: node, 1240 | id: node && node.getAttribute('data-requiremodule') 1241 | }; 1242 | } 1243 | 1244 | function intakeDefines() { 1245 | var args; 1246 | 1247 | //Any defined modules in the global queue, intake them now. 1248 | takeGlobalQueue(); 1249 | 1250 | //Make sure any remaining defQueue items get properly processed. 1251 | while (defQueue.length) { 1252 | args = defQueue.shift(); 1253 | if (args[0] === null) { 1254 | return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + 1255 | args[args.length - 1])); 1256 | } else { 1257 | //args are id, deps, factory. Should be normalized by the 1258 | //define() function. 1259 | callGetModule(args); 1260 | } 1261 | } 1262 | context.defQueueMap = {}; 1263 | } 1264 | 1265 | context = { 1266 | config: config, 1267 | contextName: contextName, 1268 | registry: registry, 1269 | defined: defined, 1270 | urlFetched: urlFetched, 1271 | defQueue: defQueue, 1272 | defQueueMap: {}, 1273 | Module: Module, 1274 | makeModuleMap: makeModuleMap, 1275 | nextTick: req.nextTick, 1276 | onError: onError, 1277 | 1278 | /** 1279 | * Set a configuration for the context. 1280 | * @param {Object} cfg config object to integrate. 1281 | */ 1282 | configure: function (cfg) { 1283 | //Make sure the baseUrl ends in a slash. 1284 | if (cfg.baseUrl) { 1285 | if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { 1286 | cfg.baseUrl += '/'; 1287 | } 1288 | } 1289 | 1290 | // Convert old style urlArgs string to a function. 1291 | if (typeof cfg.urlArgs === 'string') { 1292 | var urlArgs = cfg.urlArgs; 1293 | cfg.urlArgs = function(id, url) { 1294 | return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; 1295 | }; 1296 | } 1297 | 1298 | //Save off the paths since they require special processing, 1299 | //they are additive. 1300 | var shim = config.shim, 1301 | objs = { 1302 | paths: true, 1303 | bundles: true, 1304 | config: true, 1305 | map: true 1306 | }; 1307 | 1308 | eachProp(cfg, function (value, prop) { 1309 | if (objs[prop]) { 1310 | if (!config[prop]) { 1311 | config[prop] = {}; 1312 | } 1313 | mixin(config[prop], value, true, true); 1314 | } else { 1315 | config[prop] = value; 1316 | } 1317 | }); 1318 | 1319 | //Reverse map the bundles 1320 | if (cfg.bundles) { 1321 | eachProp(cfg.bundles, function (value, prop) { 1322 | each(value, function (v) { 1323 | if (v !== prop) { 1324 | bundlesMap[v] = prop; 1325 | } 1326 | }); 1327 | }); 1328 | } 1329 | 1330 | //Merge shim 1331 | if (cfg.shim) { 1332 | eachProp(cfg.shim, function (value, id) { 1333 | //Normalize the structure 1334 | if (isArray(value)) { 1335 | value = { 1336 | deps: value 1337 | }; 1338 | } 1339 | if ((value.exports || value.init) && !value.exportsFn) { 1340 | value.exportsFn = context.makeShimExports(value); 1341 | } 1342 | shim[id] = value; 1343 | }); 1344 | config.shim = shim; 1345 | } 1346 | 1347 | //Adjust packages if necessary. 1348 | if (cfg.packages) { 1349 | each(cfg.packages, function (pkgObj) { 1350 | var location, name; 1351 | 1352 | pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; 1353 | 1354 | name = pkgObj.name; 1355 | location = pkgObj.location; 1356 | if (location) { 1357 | config.paths[name] = pkgObj.location; 1358 | } 1359 | 1360 | //Save pointer to main module ID for pkg name. 1361 | //Remove leading dot in main, so main paths are normalized, 1362 | //and remove any trailing .js, since different package 1363 | //envs have different conventions: some use a module name, 1364 | //some use a file name. 1365 | config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') 1366 | .replace(currDirRegExp, '') 1367 | .replace(jsSuffixRegExp, ''); 1368 | }); 1369 | } 1370 | 1371 | //If there are any "waiting to execute" modules in the registry, 1372 | //update the maps for them, since their info, like URLs to load, 1373 | //may have changed. 1374 | eachProp(registry, function (mod, id) { 1375 | //If module already has init called, since it is too 1376 | //late to modify them, and ignore unnormalized ones 1377 | //since they are transient. 1378 | if (!mod.inited && !mod.map.unnormalized) { 1379 | mod.map = makeModuleMap(id, null, true); 1380 | } 1381 | }); 1382 | 1383 | //If a deps array or a config callback is specified, then call 1384 | //require with those args. This is useful when require is defined as a 1385 | //config object before require.js is loaded. 1386 | if (cfg.deps || cfg.callback) { 1387 | context.require(cfg.deps || [], cfg.callback); 1388 | } 1389 | }, 1390 | 1391 | makeShimExports: function (value) { 1392 | function fn() { 1393 | var ret; 1394 | if (value.init) { 1395 | ret = value.init.apply(global, arguments); 1396 | } 1397 | return ret || (value.exports && getGlobal(value.exports)); 1398 | } 1399 | return fn; 1400 | }, 1401 | 1402 | makeRequire: function (relMap, options) { 1403 | options = options || {}; 1404 | 1405 | function localRequire(deps, callback, errback) { 1406 | var id, map, requireMod; 1407 | 1408 | if (options.enableBuildCallback && callback && isFunction(callback)) { 1409 | callback.__requireJsBuild = true; 1410 | } 1411 | 1412 | if (typeof deps === 'string') { 1413 | if (isFunction(callback)) { 1414 | //Invalid call 1415 | return onError(makeError('requireargs', 'Invalid require call'), errback); 1416 | } 1417 | 1418 | //If require|exports|module are requested, get the 1419 | //value for them from the special handlers. Caveat: 1420 | //this only works while module is being defined. 1421 | if (relMap && hasProp(handlers, deps)) { 1422 | return handlers[deps](registry[relMap.id]); 1423 | } 1424 | 1425 | //Synchronous access to one module. If require.get is 1426 | //available (as in the Node adapter), prefer that. 1427 | if (req.get) { 1428 | return req.get(context, deps, relMap, localRequire); 1429 | } 1430 | 1431 | //Normalize module name, if it contains . or .. 1432 | map = makeModuleMap(deps, relMap, false, true); 1433 | id = map.id; 1434 | 1435 | if (!hasProp(defined, id)) { 1436 | return onError(makeError('notloaded', 'Module name "' + 1437 | id + 1438 | '" has not been loaded yet for context: ' + 1439 | contextName + 1440 | (relMap ? '' : '. Use require([])'))); 1441 | } 1442 | return defined[id]; 1443 | } 1444 | 1445 | //Grab defines waiting in the global queue. 1446 | intakeDefines(); 1447 | 1448 | //Mark all the dependencies as needing to be loaded. 1449 | context.nextTick(function () { 1450 | //Some defines could have been added since the 1451 | //require call, collect them. 1452 | intakeDefines(); 1453 | 1454 | requireMod = getModule(makeModuleMap(null, relMap)); 1455 | 1456 | //Store if map config should be applied to this require 1457 | //call for dependencies. 1458 | requireMod.skipMap = options.skipMap; 1459 | 1460 | requireMod.init(deps, callback, errback, { 1461 | enabled: true 1462 | }); 1463 | 1464 | checkLoaded(); 1465 | }); 1466 | 1467 | return localRequire; 1468 | } 1469 | 1470 | mixin(localRequire, { 1471 | isBrowser: isBrowser, 1472 | 1473 | /** 1474 | * Converts a module name + .extension into an URL path. 1475 | * *Requires* the use of a module name. It does not support using 1476 | * plain URLs like nameToUrl. 1477 | */ 1478 | toUrl: function (moduleNamePlusExt) { 1479 | var ext, 1480 | index = moduleNamePlusExt.lastIndexOf('.'), 1481 | segment = moduleNamePlusExt.split('/')[0], 1482 | isRelative = segment === '.' || segment === '..'; 1483 | 1484 | //Have a file extension alias, and it is not the 1485 | //dots from a relative path. 1486 | if (index !== -1 && (!isRelative || index > 1)) { 1487 | ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); 1488 | moduleNamePlusExt = moduleNamePlusExt.substring(0, index); 1489 | } 1490 | 1491 | return context.nameToUrl(normalize(moduleNamePlusExt, 1492 | relMap && relMap.id, true), ext, true); 1493 | }, 1494 | 1495 | defined: function (id) { 1496 | return hasProp(defined, makeModuleMap(id, relMap, false, true).id); 1497 | }, 1498 | 1499 | specified: function (id) { 1500 | id = makeModuleMap(id, relMap, false, true).id; 1501 | return hasProp(defined, id) || hasProp(registry, id); 1502 | } 1503 | }); 1504 | 1505 | //Only allow undef on top level require calls 1506 | if (!relMap) { 1507 | localRequire.undef = function (id) { 1508 | //Bind any waiting define() calls to this context, 1509 | //fix for #408 1510 | takeGlobalQueue(); 1511 | 1512 | var map = makeModuleMap(id, relMap, true), 1513 | mod = getOwn(registry, id); 1514 | 1515 | mod.undefed = true; 1516 | removeScript(id); 1517 | 1518 | delete defined[id]; 1519 | delete urlFetched[map.url]; 1520 | delete undefEvents[id]; 1521 | 1522 | //Clean queued defines too. Go backwards 1523 | //in array so that the splices do not 1524 | //mess up the iteration. 1525 | eachReverse(defQueue, function(args, i) { 1526 | if (args[0] === id) { 1527 | defQueue.splice(i, 1); 1528 | } 1529 | }); 1530 | delete context.defQueueMap[id]; 1531 | 1532 | if (mod) { 1533 | //Hold on to listeners in case the 1534 | //module will be attempted to be reloaded 1535 | //using a different config. 1536 | if (mod.events.defined) { 1537 | undefEvents[id] = mod.events; 1538 | } 1539 | 1540 | cleanRegistry(id); 1541 | } 1542 | }; 1543 | } 1544 | 1545 | return localRequire; 1546 | }, 1547 | 1548 | /** 1549 | * Called to enable a module if it is still in the registry 1550 | * awaiting enablement. A second arg, parent, the parent module, 1551 | * is passed in for context, when this method is overridden by 1552 | * the optimizer. Not shown here to keep code compact. 1553 | */ 1554 | enable: function (depMap) { 1555 | var mod = getOwn(registry, depMap.id); 1556 | if (mod) { 1557 | getModule(depMap).enable(); 1558 | } 1559 | }, 1560 | 1561 | /** 1562 | * Internal method used by environment adapters to complete a load event. 1563 | * A load event could be a script load or just a load pass from a synchronous 1564 | * load call. 1565 | * @param {String} moduleName the name of the module to potentially complete. 1566 | */ 1567 | completeLoad: function (moduleName) { 1568 | var found, args, mod, 1569 | shim = getOwn(config.shim, moduleName) || {}, 1570 | shExports = shim.exports; 1571 | 1572 | takeGlobalQueue(); 1573 | 1574 | while (defQueue.length) { 1575 | args = defQueue.shift(); 1576 | if (args[0] === null) { 1577 | args[0] = moduleName; 1578 | //If already found an anonymous module and bound it 1579 | //to this name, then this is some other anon module 1580 | //waiting for its completeLoad to fire. 1581 | if (found) { 1582 | break; 1583 | } 1584 | found = true; 1585 | } else if (args[0] === moduleName) { 1586 | //Found matching define call for this script! 1587 | found = true; 1588 | } 1589 | 1590 | callGetModule(args); 1591 | } 1592 | context.defQueueMap = {}; 1593 | 1594 | //Do this after the cycle of callGetModule in case the result 1595 | //of those calls/init calls changes the registry. 1596 | mod = getOwn(registry, moduleName); 1597 | 1598 | if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { 1599 | if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { 1600 | if (hasPathFallback(moduleName)) { 1601 | return; 1602 | } else { 1603 | return onError(makeError('nodefine', 1604 | 'No define call for ' + moduleName, 1605 | null, 1606 | [moduleName])); 1607 | } 1608 | } else { 1609 | //A script that does not call define(), so just simulate 1610 | //the call for it. 1611 | callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); 1612 | } 1613 | } 1614 | 1615 | checkLoaded(); 1616 | }, 1617 | 1618 | /** 1619 | * Converts a module name to a file path. Supports cases where 1620 | * moduleName may actually be just an URL. 1621 | * Note that it **does not** call normalize on the moduleName, 1622 | * it is assumed to have already been normalized. This is an 1623 | * internal API, not a public one. Use toUrl for the public API. 1624 | */ 1625 | nameToUrl: function (moduleName, ext, skipExt) { 1626 | var paths, syms, i, parentModule, url, 1627 | parentPath, bundleId, 1628 | pkgMain = getOwn(config.pkgs, moduleName); 1629 | 1630 | if (pkgMain) { 1631 | moduleName = pkgMain; 1632 | } 1633 | 1634 | bundleId = getOwn(bundlesMap, moduleName); 1635 | 1636 | if (bundleId) { 1637 | return context.nameToUrl(bundleId, ext, skipExt); 1638 | } 1639 | 1640 | //If a colon is in the URL, it indicates a protocol is used and it is just 1641 | //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) 1642 | //or ends with .js, then assume the user meant to use an url and not a module id. 1643 | //The slash is important for protocol-less URLs as well as full paths. 1644 | if (req.jsExtRegExp.test(moduleName)) { 1645 | //Just a plain path, not module name lookup, so just return it. 1646 | //Add extension if it is included. This is a bit wonky, only non-.js things pass 1647 | //an extension, this method probably needs to be reworked. 1648 | url = moduleName + (ext || ''); 1649 | } else { 1650 | //A module that needs to be converted to a path. 1651 | paths = config.paths; 1652 | 1653 | syms = moduleName.split('/'); 1654 | //For each module name segment, see if there is a path 1655 | //registered for it. Start with most specific name 1656 | //and work up from it. 1657 | for (i = syms.length; i > 0; i -= 1) { 1658 | parentModule = syms.slice(0, i).join('/'); 1659 | 1660 | parentPath = getOwn(paths, parentModule); 1661 | if (parentPath) { 1662 | //If an array, it means there are a few choices, 1663 | //Choose the one that is desired 1664 | if (isArray(parentPath)) { 1665 | parentPath = parentPath[0]; 1666 | } 1667 | syms.splice(0, i, parentPath); 1668 | break; 1669 | } 1670 | } 1671 | 1672 | //Join the path parts together, then figure out if baseUrl is needed. 1673 | url = syms.join('/'); 1674 | url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js')); 1675 | url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; 1676 | } 1677 | 1678 | return config.urlArgs && !/^blob\:/.test(url) ? 1679 | url + config.urlArgs(moduleName, url) : url; 1680 | }, 1681 | 1682 | //Delegates to req.load. Broken out as a separate function to 1683 | //allow overriding in the optimizer. 1684 | load: function (id, url) { 1685 | req.load(context, id, url); 1686 | }, 1687 | 1688 | /** 1689 | * Executes a module callback function. Broken out as a separate function 1690 | * solely to allow the build system to sequence the files in the built 1691 | * layer in the right sequence. 1692 | * 1693 | * @private 1694 | */ 1695 | execCb: function (name, callback, args, exports) { 1696 | return callback.apply(exports, args); 1697 | }, 1698 | 1699 | /** 1700 | * callback for script loads, used to check status of loading. 1701 | * 1702 | * @param {Event} evt the event from the browser for the script 1703 | * that was loaded. 1704 | */ 1705 | onScriptLoad: function (evt) { 1706 | //Using currentTarget instead of target for Firefox 2.0's sake. Not 1707 | //all old browsers will be supported, but this one was easy enough 1708 | //to support and still makes sense. 1709 | if (evt.type === 'load' || 1710 | (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { 1711 | //Reset interactive script so a script node is not held onto for 1712 | //to long. 1713 | interactiveScript = null; 1714 | 1715 | //Pull out the name of the module and the context. 1716 | var data = getScriptData(evt); 1717 | context.completeLoad(data.id); 1718 | } 1719 | }, 1720 | 1721 | /** 1722 | * Callback for script errors. 1723 | */ 1724 | onScriptError: function (evt) { 1725 | var data = getScriptData(evt); 1726 | if (!hasPathFallback(data.id)) { 1727 | var parents = []; 1728 | eachProp(registry, function(value, key) { 1729 | if (key.indexOf('_@r') !== 0) { 1730 | each(value.depMaps, function(depMap) { 1731 | if (depMap.id === data.id) { 1732 | parents.push(key); 1733 | return true; 1734 | } 1735 | }); 1736 | } 1737 | }); 1738 | return onError(makeError('scripterror', 'Script error for "' + data.id + 1739 | (parents.length ? 1740 | '", needed by: ' + parents.join(', ') : 1741 | '"'), evt, [data.id])); 1742 | } 1743 | } 1744 | }; 1745 | 1746 | context.require = context.makeRequire(); 1747 | return context; 1748 | } 1749 | 1750 | /** 1751 | * Main entry point. 1752 | * 1753 | * If the only argument to require is a string, then the module that 1754 | * is represented by that string is fetched for the appropriate context. 1755 | * 1756 | * If the first argument is an array, then it will be treated as an array 1757 | * of dependency string names to fetch. An optional function callback can 1758 | * be specified to execute when all of those dependencies are available. 1759 | * 1760 | * Make a local req variable to help Caja compliance (it assumes things 1761 | * on a require that are not standardized), and to give a short 1762 | * name for minification/local scope use. 1763 | */ 1764 | req = requirejs = function (deps, callback, errback, optional) { 1765 | 1766 | //Find the right context, use default 1767 | var context, config, 1768 | contextName = defContextName; 1769 | 1770 | // Determine if have config object in the call. 1771 | if (!isArray(deps) && typeof deps !== 'string') { 1772 | // deps is a config object 1773 | config = deps; 1774 | if (isArray(callback)) { 1775 | // Adjust args if there are dependencies 1776 | deps = callback; 1777 | callback = errback; 1778 | errback = optional; 1779 | } else { 1780 | deps = []; 1781 | } 1782 | } 1783 | 1784 | if (config && config.context) { 1785 | contextName = config.context; 1786 | } 1787 | 1788 | context = getOwn(contexts, contextName); 1789 | if (!context) { 1790 | context = contexts[contextName] = req.s.newContext(contextName); 1791 | } 1792 | 1793 | if (config) { 1794 | context.configure(config); 1795 | } 1796 | 1797 | return context.require(deps, callback, errback); 1798 | }; 1799 | 1800 | /** 1801 | * Support require.config() to make it easier to cooperate with other 1802 | * AMD loaders on globally agreed names. 1803 | */ 1804 | req.config = function (config) { 1805 | return req(config); 1806 | }; 1807 | 1808 | /** 1809 | * Execute something after the current tick 1810 | * of the event loop. Override for other envs 1811 | * that have a better solution than setTimeout. 1812 | * @param {Function} fn function to execute later. 1813 | */ 1814 | req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { 1815 | setTimeout(fn, 4); 1816 | } : function (fn) { fn(); }; 1817 | 1818 | /** 1819 | * Export require as a global, but only if it does not already exist. 1820 | */ 1821 | if (!require) { 1822 | require = req; 1823 | } 1824 | 1825 | req.version = version; 1826 | 1827 | //Used to filter out dependencies that are already paths. 1828 | req.jsExtRegExp = /^\/|:|\?|\.js$/; 1829 | req.isBrowser = isBrowser; 1830 | s = req.s = { 1831 | contexts: contexts, 1832 | newContext: newContext 1833 | }; 1834 | 1835 | //Create default context. 1836 | req({}); 1837 | 1838 | //Exports some context-sensitive methods on global require. 1839 | each([ 1840 | 'toUrl', 1841 | 'undef', 1842 | 'defined', 1843 | 'specified' 1844 | ], function (prop) { 1845 | //Reference from contexts instead of early binding to default context, 1846 | //so that during builds, the latest instance of the default context 1847 | //with its config gets used. 1848 | req[prop] = function () { 1849 | var ctx = contexts[defContextName]; 1850 | return ctx.require[prop].apply(ctx, arguments); 1851 | }; 1852 | }); 1853 | 1854 | if (isBrowser) { 1855 | head = s.head = document.getElementsByTagName('head')[0]; 1856 | //If BASE tag is in play, using appendChild is a problem for IE6. 1857 | //When that browser dies, this can be removed. Details in this jQuery bug: 1858 | //http://dev.jquery.com/ticket/2709 1859 | baseElement = document.getElementsByTagName('base')[0]; 1860 | if (baseElement) { 1861 | head = s.head = baseElement.parentNode; 1862 | } 1863 | } 1864 | 1865 | /** 1866 | * Any errors that require explicitly generates will be passed to this 1867 | * function. Intercept/override it if you want custom error handling. 1868 | * @param {Error} err the error object. 1869 | */ 1870 | req.onError = defaultOnError; 1871 | 1872 | /** 1873 | * Creates the node for the load command. Only used in browser envs. 1874 | */ 1875 | req.createNode = function (config, moduleName, url) { 1876 | var node = config.xhtml ? 1877 | document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : 1878 | document.createElement('script'); 1879 | node.type = config.scriptType || 'text/javascript'; 1880 | node.charset = 'utf-8'; 1881 | node.async = true; 1882 | return node; 1883 | }; 1884 | 1885 | /** 1886 | * Does the request to load a module for the browser case. 1887 | * Make this a separate function to allow other environments 1888 | * to override it. 1889 | * 1890 | * @param {Object} context the require context to find state. 1891 | * @param {String} moduleName the name of the module. 1892 | * @param {Object} url the URL to the module. 1893 | */ 1894 | req.load = function (context, moduleName, url) { 1895 | var config = (context && context.config) || {}, 1896 | node; 1897 | if (isBrowser) { 1898 | //In the browser so use a script tag 1899 | node = req.createNode(config, moduleName, url); 1900 | 1901 | node.setAttribute('data-requirecontext', context.contextName); 1902 | node.setAttribute('data-requiremodule', moduleName); 1903 | 1904 | //Set up load listener. Test attachEvent first because IE9 has 1905 | //a subtle issue in its addEventListener and script onload firings 1906 | //that do not match the behavior of all other browsers with 1907 | //addEventListener support, which fire the onload event for a 1908 | //script right after the script execution. See: 1909 | //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution 1910 | //UNFORTUNATELY Opera implements attachEvent but does not follow the script 1911 | //script execution mode. 1912 | if (node.attachEvent && 1913 | //Check if node.attachEvent is artificially added by custom script or 1914 | //natively supported by browser 1915 | //read https://github.com/requirejs/requirejs/issues/187 1916 | //if we can NOT find [native code] then it must NOT natively supported. 1917 | //in IE8, node.attachEvent does not have toString() 1918 | //Note the test for "[native code" with no closing brace, see: 1919 | //https://github.com/requirejs/requirejs/issues/273 1920 | !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && 1921 | !isOpera) { 1922 | //Probably IE. IE (at least 6-8) do not fire 1923 | //script onload right after executing the script, so 1924 | //we cannot tie the anonymous define call to a name. 1925 | //However, IE reports the script as being in 'interactive' 1926 | //readyState at the time of the define call. 1927 | useInteractive = true; 1928 | 1929 | node.attachEvent('onreadystatechange', context.onScriptLoad); 1930 | //It would be great to add an error handler here to catch 1931 | //404s in IE9+. However, onreadystatechange will fire before 1932 | //the error handler, so that does not help. If addEventListener 1933 | //is used, then IE will fire error before load, but we cannot 1934 | //use that pathway given the connect.microsoft.com issue 1935 | //mentioned above about not doing the 'script execute, 1936 | //then fire the script load event listener before execute 1937 | //next script' that other browsers do. 1938 | //Best hope: IE10 fixes the issues, 1939 | //and then destroys all installs of IE 6-9. 1940 | //node.attachEvent('onerror', context.onScriptError); 1941 | } else { 1942 | node.addEventListener('load', context.onScriptLoad, false); 1943 | node.addEventListener('error', context.onScriptError, false); 1944 | } 1945 | node.src = url; 1946 | 1947 | //Calling onNodeCreated after all properties on the node have been 1948 | //set, but before it is placed in the DOM. 1949 | if (config.onNodeCreated) { 1950 | config.onNodeCreated(node, config, moduleName, url); 1951 | } 1952 | 1953 | //For some cache cases in IE 6-8, the script executes before the end 1954 | //of the appendChild execution, so to tie an anonymous define 1955 | //call to the module name (which is stored on the node), hold on 1956 | //to a reference to this node, but clear after the DOM insertion. 1957 | currentlyAddingScript = node; 1958 | if (baseElement) { 1959 | head.insertBefore(node, baseElement); 1960 | } else { 1961 | head.appendChild(node); 1962 | } 1963 | currentlyAddingScript = null; 1964 | 1965 | return node; 1966 | } else if (isWebWorker) { 1967 | try { 1968 | //In a web worker, use importScripts. This is not a very 1969 | //efficient use of importScripts, importScripts will block until 1970 | //its script is downloaded and evaluated. However, if web workers 1971 | //are in play, the expectation is that a build has been done so 1972 | //that only one script needs to be loaded anyway. This may need 1973 | //to be reevaluated if other use cases become common. 1974 | 1975 | // Post a task to the event loop to work around a bug in WebKit 1976 | // where the worker gets garbage-collected after calling 1977 | // importScripts(): https://webkit.org/b/153317 1978 | setTimeout(function() {}, 0); 1979 | importScripts(url); 1980 | 1981 | //Account for anonymous modules 1982 | context.completeLoad(moduleName); 1983 | } catch (e) { 1984 | context.onError(makeError('importscripts', 1985 | 'importScripts failed for ' + 1986 | moduleName + ' at ' + url, 1987 | e, 1988 | [moduleName])); 1989 | } 1990 | } 1991 | }; 1992 | 1993 | function getInteractiveScript() { 1994 | if (interactiveScript && interactiveScript.readyState === 'interactive') { 1995 | return interactiveScript; 1996 | } 1997 | 1998 | eachReverse(scripts(), function (script) { 1999 | if (script.readyState === 'interactive') { 2000 | return (interactiveScript = script); 2001 | } 2002 | }); 2003 | return interactiveScript; 2004 | } 2005 | 2006 | //Look for a data-main script attribute, which could also adjust the baseUrl. 2007 | if (isBrowser && !cfg.skipDataMain) { 2008 | //Figure out baseUrl. Get it from the script tag with require.js in it. 2009 | eachReverse(scripts(), function (script) { 2010 | //Set the 'head' where we can append children by 2011 | //using the script's parent. 2012 | if (!head) { 2013 | head = script.parentNode; 2014 | } 2015 | 2016 | //Look for a data-main attribute to set main script for the page 2017 | //to load. If it is there, the path to data main becomes the 2018 | //baseUrl, if it is not already set. 2019 | dataMain = script.getAttribute('data-main'); 2020 | if (dataMain) { 2021 | //Preserve dataMain in case it is a path (i.e. contains '?') 2022 | mainScript = dataMain; 2023 | 2024 | //Set final baseUrl if there is not already an explicit one, 2025 | //but only do so if the data-main value is not a loader plugin 2026 | //module ID. 2027 | if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { 2028 | //Pull off the directory of data-main for use as the 2029 | //baseUrl. 2030 | src = mainScript.split('/'); 2031 | mainScript = src.pop(); 2032 | subPath = src.length ? src.join('/') + '/' : './'; 2033 | 2034 | cfg.baseUrl = subPath; 2035 | } 2036 | 2037 | //Strip off any trailing .js since mainScript is now 2038 | //like a module name. 2039 | mainScript = mainScript.replace(jsSuffixRegExp, ''); 2040 | 2041 | //If mainScript is still a path, fall back to dataMain 2042 | if (req.jsExtRegExp.test(mainScript)) { 2043 | mainScript = dataMain; 2044 | } 2045 | 2046 | //Put the data-main script in the files to load. 2047 | cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; 2048 | 2049 | return true; 2050 | } 2051 | }); 2052 | } 2053 | 2054 | /** 2055 | * The function that handles definitions of modules. Differs from 2056 | * require() in that a string for the module should be the first argument, 2057 | * and the function to execute after dependencies are loaded should 2058 | * return a value to define the module corresponding to the first argument's 2059 | * name. 2060 | */ 2061 | define = function (name, deps, callback) { 2062 | var node, context; 2063 | 2064 | //Allow for anonymous modules 2065 | if (typeof name !== 'string') { 2066 | //Adjust args appropriately 2067 | callback = deps; 2068 | deps = name; 2069 | name = null; 2070 | } 2071 | 2072 | //This module may not have dependencies 2073 | if (!isArray(deps)) { 2074 | callback = deps; 2075 | deps = null; 2076 | } 2077 | 2078 | //If no name, and callback is a function, then figure out if it a 2079 | //CommonJS thing with dependencies. 2080 | if (!deps && isFunction(callback)) { 2081 | deps = []; 2082 | //Remove comments from the callback string, 2083 | //look for require calls, and pull them into the dependencies, 2084 | //but only if there are function args. 2085 | if (callback.length) { 2086 | callback 2087 | .toString() 2088 | .replace(commentRegExp, commentReplace) 2089 | .replace(cjsRequireRegExp, function (match, dep) { 2090 | deps.push(dep); 2091 | }); 2092 | 2093 | //May be a CommonJS thing even without require calls, but still 2094 | //could use exports, and module. Avoid doing exports and module 2095 | //work though if it just needs require. 2096 | //REQUIRES the function to expect the CommonJS variables in the 2097 | //order listed below. 2098 | deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); 2099 | } 2100 | } 2101 | 2102 | //If in IE 6-8 and hit an anonymous define() call, do the interactive 2103 | //work. 2104 | if (useInteractive) { 2105 | node = currentlyAddingScript || getInteractiveScript(); 2106 | if (node) { 2107 | if (!name) { 2108 | name = node.getAttribute('data-requiremodule'); 2109 | } 2110 | context = contexts[node.getAttribute('data-requirecontext')]; 2111 | } 2112 | } 2113 | 2114 | //Always save off evaluating the def call until the script onload handler. 2115 | //This allows multiple modules to be in a file without prematurely 2116 | //tracing dependencies, and allows for anonymous module support, 2117 | //where the module name is not known until the script onload event 2118 | //occurs. If no context, use the global queue, and get it processed 2119 | //in the onscript load callback. 2120 | if (context) { 2121 | context.defQueue.push([name, deps, callback]); 2122 | context.defQueueMap[name] = true; 2123 | } else { 2124 | globalDefQueue.push([name, deps, callback]); 2125 | } 2126 | }; 2127 | 2128 | define.amd = { 2129 | jQuery: true 2130 | }; 2131 | 2132 | /** 2133 | * Executes the text. Normally just uses eval, but can be modified 2134 | * to use a better, environment-specific call. Only used for transpiling 2135 | * loader plugins, not for plain JS modules. 2136 | * @param {String} text the text to execute/evaluate. 2137 | */ 2138 | req.exec = function (text) { 2139 | /*jslint evil: true */ 2140 | return eval(text); 2141 | }; 2142 | 2143 | //Set up with config info. 2144 | req(cfg); 2145 | }(this, (typeof setTimeout === 'undefined' ? undefined : setTimeout))); 2146 | -------------------------------------------------------------------------------- /assets/script.js: -------------------------------------------------------------------------------- 1 | const delay = ms => new Promise(res => setTimeout(res, ms)); 2 | let jupyter_timeout_id = 0; 3 | 4 | /* 5 | * Connect to the jupyter server 6 | * to use binder or jupyter lite change the config below 7 | */ 8 | async function jupyterConnect(){ 9 | let secure = ""; // set to "s" if secure else set "" 10 | let server = document.getElementById("jupyter_server").querySelectorAll("textarea")[0].value; 11 | let server_token = document.getElementById("jupyter_token").querySelectorAll("textarea")[0].value; 12 | let jupyter_kernel = document.getElementById("jupyter_kernel").querySelectorAll("textarea")[0].value; 13 | 14 | let config = { 15 | bootstrap: false, 16 | preRenderHook: false, 17 | predefinedOutput: false, 18 | outputSelector: '[data-output]', 19 | requestKernel: true, 20 | mountActivateWidget: true, 21 | mountStatusWidget: true, 22 | useJupyterLite: false, 23 | useBinder: false, 24 | kernelOptions: { 25 | name: jupyter_kernel, 26 | kernelName: jupyter_kernel, 27 | }, 28 | serverSettings: { 29 | baseUrl: "http://"+server, 30 | wsUrl: "ws://"+server, 31 | token: server_token, 32 | }, 33 | selector: "[data-executable]", 34 | stripPrompts: false, 35 | mathjaxUrl: "file/extensions/CodeRunner/assets/thebe/mathjax.js", 36 | requirejsUrl: "file/extensions/CodeRunner/assets/require/require.js", 37 | mathjaxConfig: "TeX-AMS_CHTML-full,Safe", 38 | codeMirrorConfig: {}, 39 | }; 40 | window.thebe.configuration = config; 41 | 42 | // start setup 43 | window.thebe.mountStatusWidget(); 44 | window.thebe.bootstrap(config); 45 | 46 | // add callback for finished cells 47 | window.thebe.on("status", async function (evt, data) { 48 | if(data.status == "idle" && data.message == "Completed"){ 49 | // Send outputs back to gradio backend via button click event 50 | for (let i = 0; i < window.thebe.notebook.cells.length; i++) { 51 | console.log("sending value for cell", i); 52 | const cell = window.thebe.notebook.cells[i]; 53 | await jupyterSendDataBack(JSON.stringify(jupyterExtractOutputData(cell.id))); 54 | }; 55 | } 56 | }); 57 | 58 | // add callback for onchange of the chat 59 | let jupyter_mutObs = new MutationObserver(async function() { 60 | // only execute cells if nothing was executed for some time 61 | clearTimeout(jupyter_timeout_id); 62 | jupyter_timeout_id = setTimeout(async()=>{await jupyterNewCode();}, 500); 63 | }); 64 | jupyter_mutObs.observe(document.getElementById("chat-tab"), {childList:true, subtree: true}); 65 | 66 | // execute all cells on start up to fill in the session and connection parameters 67 | delay(500); 68 | await window.thebe.notebook.executeAll(); 69 | } 70 | 71 | // detect new code 72 | async function jupyterNewCode(){ 73 | // are there new cells? 74 | if (window.thebe.findCells(window.thebe.configuration.selector, window.thebe.configuration.outputSelector).length > 0) { 75 | window.thebe.replaceCells(window.thebe.configuration); 76 | delay(250); 77 | await window.thebe.notebook.executeAll(); 78 | } 79 | } 80 | 81 | // sent a value back to the python backend 82 | async function jupyterSendDataBack(data){ 83 | document.getElementById("jupyter_data").querySelector("textarea").value = data; 84 | document.getElementById("jupyter_data").querySelector("textarea").dispatchEvent(new Event("input")); 85 | await delay(200); 86 | document.getElementById("jupyter_data_submit").click(); 87 | await delay(200); 88 | } 89 | 90 | // get the cell output 91 | function jupyterExtractOutputData(cell_id){ 92 | let cell = window.thebe.notebook.getCellById(cell_id); 93 | let outputs = cell.outputs; 94 | computation_result = [] 95 | outputs.forEach(output => { 96 | if (output.output_type == "display_data") { 97 | // if an image was created and should be send back 98 | // has to be copied from the dom, can change with interactive application 99 | console.info("retrieve image not implemented"); 100 | computation_result.push({"type": "image", "data": "image handling is not implemented yet"}); 101 | } else { 102 | // get text outputs 103 | if (output.output_type == "execution_result"){ 104 | computation_result.push({"type": "text", "data": output.data["text/plain"]}); 105 | }else if (output.output_type == "stream") { 106 | computation_result.push({"type": "text", "data": output.text}); 107 | }else if (output.output_type == "error") { 108 | computation_result.push({"type": "error", "data": output.traceback, "error_type": output.ename, "error_value": output.evalue}); 109 | } else { 110 | console.error("not implemented"); 111 | } 112 | } 113 | }); 114 | // get the id to match the output to the input 115 | cell_index = window.thebe.notebook.cells.indexOf(window.thebe.notebook.getCellById(cell_id)); 116 | textgen_index = cell.area.node.parentElement.parentElement.parentElement.id.split("_").at(-1); 117 | return {id: cell_index, textgen_id: textgen_index, output: computation_result}; 118 | } -------------------------------------------------------------------------------- /assets/thebe/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Executable Books Project 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 12 | -------------------------------------------------------------------------------- /assets/thebe/index.js.LICENSE.txt: -------------------------------------------------------------------------------- 1 | /* 2 | object-assign 3 | (c) Sindre Sorhus 4 | @license MIT 5 | */ 6 | 7 | /*! 8 | * Sizzle CSS Selector Engine v2.3.10 9 | * https://sizzlejs.com/ 10 | * 11 | * Copyright JS Foundation and other contributors 12 | * Released under the MIT license 13 | * https://js.foundation/ 14 | * 15 | * Date: 2023-02-14 16 | */ 17 | 18 | /*! 19 | * is-plain-object 20 | * 21 | * Copyright (c) 2014-2017, Jon Schlinkert. 22 | * Released under the MIT License. 23 | */ 24 | 25 | /*! 26 | * jQuery JavaScript Library v3.6.4 27 | * https://jquery.com/ 28 | * 29 | * Includes Sizzle.js 30 | * https://sizzlejs.com/ 31 | * 32 | * Copyright OpenJS Foundation and other contributors 33 | * Released under the MIT license 34 | * https://jquery.org/license 35 | * 36 | * Date: 2023-03-08T15:28Z 37 | */ 38 | 39 | /*! ***************************************************************************** 40 | Copyright (c) Microsoft Corporation. 41 | 42 | Permission to use, copy, modify, and/or distribute this software for any 43 | purpose with or without fee is hereby granted. 44 | 45 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 46 | REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 47 | AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 48 | INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 49 | LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR 50 | OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 51 | PERFORMANCE OF THIS SOFTWARE. 52 | ***************************************************************************** */ 53 | 54 | /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ 55 | 56 | /** 57 | * @license React 58 | * react.production.min.js 59 | * 60 | * Copyright (c) Facebook, Inc. and its affiliates. 61 | * 62 | * This source code is licensed under the MIT license found in the 63 | * LICENSE file in the root directory of this source tree. 64 | */ 65 | 66 | /** @license React v17.0.2 67 | * react.production.min.js 68 | * 69 | * Copyright (c) Facebook, Inc. and its affiliates. 70 | * 71 | * This source code is licensed under the MIT license found in the 72 | * LICENSE file in the root directory of this source tree. 73 | */ 74 | -------------------------------------------------------------------------------- /assets/thebe/main.css: -------------------------------------------------------------------------------- 1 | .thebe-activate, 2 | .thebe-status { 3 | margin-bottom: 8px; 4 | } 5 | 6 | .thebe-button { 7 | border-radius: var(--button-large-radius) !important; 8 | padding: var(--button-large-padding) !important; 9 | font-weight: var(--button-large-text-weight) !important; 10 | display: inline-flex !important; 11 | justify-content: center !important; 12 | align-items: center !important; 13 | transition: var(--button-transition) !important; 14 | box-shadow: var(--button-shadow) !important; 15 | text-align: center !important; 16 | cursor: pointer !important; 17 | background-color: var(--button-secondary-background-fill) !important; 18 | } 19 | 20 | .thebe-button:hover { 21 | box-shadow: var(--button-shadow-hover) !important; 22 | } 23 | 24 | .thebe-run-button { 25 | background-color: var(--button-primary-background-fill); 26 | } 27 | 28 | 29 | 30 | /* input styling */ 31 | .CodeMirror-linenumbers, 32 | .CodeMirror-lines, 33 | .CodeMirror-scroll, 34 | .thebe-input { 35 | background-color: var(--jp-ui-font-color0) !important; 36 | } 37 | 38 | .CodeMirror-activeline { 39 | background-color: var(--jp-warn-color2) !important; 40 | } 41 | 42 | .cm-variable, 43 | .cm-property, 44 | .CodeMirror-line, 45 | .CodeMirror-linenumber 46 | .cm-operator { 47 | color: var(--jp-content-font-color0) !important; 48 | } 49 | 50 | .cm-def { 51 | color: var(--jp-brand-color1) !important; 52 | } 53 | 54 | .cm-string { 55 | color: var(--jp-accent-color1) !important; 56 | } 57 | 58 | -------------------------------------------------------------------------------- /assets/thebe/mathjax.js: -------------------------------------------------------------------------------- 1 | MathJax.Hub.Config({ 2 | extensions: ['tex2jax.js'], 3 | jax: ['input/TeX', 'output/HTML-CSS'], 4 | tex2jax: { 5 | inlineMath: [ 6 | ['$', '$'], 7 | ['\\(', '\\)'], 8 | ], 9 | displayMath: [ 10 | ['$$', '$$'], 11 | ['\\[', '\\]'], 12 | ], 13 | processEscapes: true, 14 | }, 15 | 'HTML-CSS': { fonts: ['TeX'] }, 16 | }); 17 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | scipy-notebook: 4 | image: jupyter/scipy-notebook 5 | ports: 6 | - 8888:8888 7 | container_name: jupyter_scipy 8 | command: "start-notebook.sh --NotebookApp.allow_origin='*' --NotebookApp.password=secret --NotebookApp.token=secret --NotebookApp.disable_check_xsrf=True --no-browser" 9 | user: root 10 | environment: 11 | GRANT_SUDO: "yes" 12 | 13 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xr4dsh/CodeRunner/6bda3256473d58e95b36f2fba4d16efed4f23609/requirements.txt -------------------------------------------------------------------------------- /script.py: -------------------------------------------------------------------------------- 1 | import gradio as gr 2 | import re 3 | import json 4 | from modules import chat, shared, ui_chat, html_generator 5 | from modules.text_generation import generate_reply_HF, generate_reply_custom 6 | import time 7 | import html 8 | from collections import defaultdict 9 | 10 | params = { 11 | "activate": True, 12 | "kernel": "python3", 13 | "jupyterlab": "localhost:8888", 14 | "jupyterlab_token": "secret", 15 | } 16 | 17 | 18 | outputs = defaultdict(dict) 19 | waiting_for_computation = False 20 | waiting_for_cell = 0 21 | jupyter_cells = 1 22 | input_evaluation = False 23 | 24 | # generate html code for jupyter code cells 25 | def thebe_code_block(m): 26 | string = "{content}' 54 | 55 | # render the code cell in the frontend correctly for user inputs 56 | def chat_input_modifier(text, visible_text, state): 57 | global waiting_for_computation, jupyter_cells, input_evaluation 58 | if not params['activate']: 59 | return text, visible_text 60 | vis_tex = visible_text 61 | visible_text = re.sub(r"```python\n(.*?)\n```", repl=count_replacements, string=visible_text, flags=re.S) 62 | if vis_tex != visible_text: 63 | # check if the user inputed a code cell 64 | input_evaluation = True 65 | return text, visible_text 66 | 67 | # remove all the
 
from the input 68 | # otherwise the model is confused 69 | def history_modifier(history): 70 | if len(history["internal"]) > 0: 71 | for i in range(0, len(history["internal"])): 72 | # find and replace all
 73 |             history["internal"][i][1] = re.sub(r"
(.*?)
", r"```python\n\1\n```", string=history["internal"][i][1], flags=re.S) 74 | return history 75 | 76 | # reset all values 77 | def data_reset(): 78 | global waiting_for_computation, waiting_for_cell, jupyter_cells, outputs 79 | waiting_for_computation = False 80 | waiting_for_cell = 0 81 | jupyter_cells = 1 82 | outputs = defaultdict(dict) 83 | 84 | # react to frontend changes and keep state ~synced 85 | def finished_exectution(jupyter_output): 86 | global waiting_for_computation, waiting_for_cell, jupyter_cells, outputs 87 | jupyter_output1 = str(jupyter_output) 88 | response_json = json.loads(jupyter_output1) 89 | if "reset" in response_json and response_json["reset"]: 90 | # reset the dict if needed 91 | outputs = defaultdict(dict) 92 | id = int(response_json["textgen_id"]) 93 | outputs[id]["output"] = response_json["output"] 94 | if waiting_for_cell == id: 95 | waiting_for_computation = False 96 | # print("json", outputs) 97 | 98 | # insert the output into the context 99 | def custom_generate_reply(question, original_question, seed, state, stopping_strings, is_chat): 100 | global update_history, waiting_for_computation, input_evaluation 101 | # print(question, original_question, seed, state, stopping_strings, is_chat) 102 | if shared.model.__class__.__name__ in ['LlamaCppModel', 'RWKVModel', 'ExllamaModel', 'Exllamav2Model', 103 | 'CtransformersModel']: 104 | generate_func = generate_reply_custom 105 | else: 106 | generate_func = generate_reply_HF 107 | 108 | if not params['activate']: 109 | for reply in generate_func(question, original_question, seed, state, stopping_strings, is_chat=is_chat): 110 | yield reply 111 | return 112 | 113 | if input_evaluation: 114 | # if user put code into the promt evaluate it before generating an output 115 | # currently only works for 1 cell per user message 116 | input_evaluation = False 117 | while waiting_for_computation: 118 | # wait for the computation to end 119 | time.sleep(0.2) 120 | computation_result = outputs[list(outputs)[-1]]["output"] 121 | output_text = "" 122 | # for the output concat all parts that are text 123 | for output in outputs[list(outputs)[-1]]["output"]: 124 | if output["type"] == "text": 125 | output_text += output["data"] 126 | question = question.replace(outputs[list(outputs)[-1]]["input"], outputs[list(outputs)[-1]]["input"] + "\nResult:\n" + output_text) 127 | code_pattern = re.compile(r"```python\n(.*?)\n```", re.DOTALL) 128 | skip_return = False 129 | # maybe handle internal and visible state differently instead of changing the history afterwards 130 | previous_generation_internal = "" 131 | previous_generation_view = "" 132 | # loop if model needs multiple code blocks for one answer 133 | while True: 134 | for reply in generate_func(question, original_question, seed, state, stopping_strings, is_chat=is_chat): 135 | if code_pattern.search(reply) and params['activate']: 136 | # found code block 137 | previous_generation_internal += reply 138 | reply = re.sub(r"```python\n(.*?)\n```", repl=count_replacements, string=reply, flags=re.S) 139 | previous_generation_view += reply 140 | skip_return = True 141 | # print("found code block", reply) 142 | yield previous_generation_view 143 | break 144 | # stream tokens 145 | yield previous_generation_view + reply 146 | if not skip_return: 147 | return 148 | else: 149 | # wait for cell to finish computation 150 | start_waiting = time.time() 151 | timeout = False 152 | # sometimes the ui does not update correctly, sending it multiple times fixes it. 153 | time.sleep(0.5) 154 | yield previous_generation_view 155 | time.sleep(0.5) 156 | yield previous_generation_view 157 | while waiting_for_computation: 158 | if time.time() - start_waiting > 30.0: 159 | # timeout did not answer after 30 seconds 160 | waiting_for_computation = False 161 | timeout = True 162 | print("timeout waiting for result") 163 | time.sleep(0.2) 164 | output_text = "" 165 | if timeout == False: 166 | # for the output concat all parts that are text 167 | for output in outputs[waiting_for_cell]["output"]: 168 | if output["type"] == "text": 169 | output_text += output["data"] 170 | if output["type"] == "error": 171 | print("an error occured", output["error_type"], output["data"]) 172 | output_text += output["error_type"] + "\n" + json.dumps(output["data"]) 173 | else: 174 | output_text = "timeout waiting for computation" 175 | previous_generation_internal += "\nResult: " + output_text 176 | previous_generation_view += "\nResult: " + output_text 177 | question += previous_generation_internal 178 | # print(question) 179 | original_question = question 180 | skip_return = False 181 | return 182 | 183 | # add global js script 184 | def generate_js(file_name): 185 | js = f""" 186 | (() => {{ 187 | let globalsScript = document.createElement("script"); 188 | globalsScript.src = "file/extensions/{file_name}"; 189 | document.head.appendChild(globalsScript); 190 | }})(); 191 | """ 192 | return js 193 | 194 | # add css styles for thebe 195 | def generate_css(file_name): 196 | css = f""" 197 | (() => {{ 198 | let globalstyle = document.createElement("link"); 199 | globalstyle.rel = "stylesheet"; 200 | globalstyle.href = "file/extensions/{file_name}"; 201 | document.head.appendChild(globalstyle); 202 | }})(); 203 | """ 204 | return css 205 | 206 | # insert thebe header config 207 | def generate_thebe_header(): 208 | header_creator = """ 209 | (() => {{ 210 | let globalScript = document.createElement("script"); 211 | globalScript.type = "text/x-thebe-config"; 212 | globalScript.src = ""; 213 | globalScript.innerHTML = "{'requestKernel': true, 'mountActivateWidget': true, 'mountStatusWidget': true, 'useJupyterLite': false, 'useBinder': false, 'kernelOptions': { 'name': 'python3'}, 'serverSettings': { 'baseUrl': 'http://localhost:8890', 'token': 'abc', 'wsUrl': 'ws://localhost:8890'}}"; 214 | document.head.appendChild(globalScript); 215 | }})(); 216 | """ 217 | return header_creator 218 | 219 | 220 | def ui(): 221 | # generate the ui 222 | with gr.Blocks(analytics_enabled=False) as interface: 223 | # insert header 224 | # Load CSS and DOM element to be used as proxy between Gradio and the injected JS modules 225 | gr.HTML(value="") 226 | gr.HTML(value="") 227 | # https://github.com/oobabooga/text-generation-webui/discussions/941 228 | gr.HTML(value="") 229 | gr.HTML(value="") 230 | # script to handle Code Cells in UI 231 | gr.HTML(value="") 232 | 233 | # add hidden button for data return 234 | json_text = gr.Textbox(visible=False, elem_id="jupyter_data") 235 | datareturn = gr.Button(visible=False, value="jupyter_button_hidden", elem_id="jupyter_data_submit") 236 | datareturn.click(finished_exectution, inputs=json_text) 237 | # Gradio elements 238 | with gr.Accordion("CodeRunner"): 239 | with gr.Row(): 240 | activate = gr.Checkbox(value=params['activate'], label='Activate CodeRunner') 241 | gr.HTML('') 242 | textgen_reset = gr.Button("Reset") 243 | textgen_reset.click(data_reset) 244 | with gr.Row(): 245 | jupyter_server_addr = gr.Textbox(show_label=False, value="localhost:8888", placeholder="localhost:8888", elem_id="jupyter_server") 246 | jupyter_server_token = gr.Textbox(show_label=False, value="secret", placeholder="secret-token", elem_id="jupyter_token") 247 | jupyter_server_kernel = gr.Textbox(show_label=False, value="python3", placeholder="kernel", elem_id="jupyter_kernel") 248 | with gr.Accordion("Status"): 249 | gr.HTML('
') 250 | gr.HTML('') 251 | 252 | 253 | # Event functions to update the parameters in the backend 254 | activate.change(lambda x: params.update({"activate": x}), activate, None) 255 | # language.change(lambda x: params.update({"language string": language_codes[x]}), language, None) 256 | jupyter_server_addr.change(lambda x: params.update({"jupyterlab": x}), jupyter_server_addr, None) 257 | jupyter_server_token.change(lambda x: params.update({"jupyterlab_token": x}), jupyter_server_token, None) 258 | jupyter_server_kernel.change(lambda x: params.update({"jupyterlab_kernel": x}), jupyter_server_kernel, None) 259 | --------------------------------------------------------------------------------