├── .eslintignore ├── .eslintrc.cjs ├── .github ├── ISSUE_TEMPLATE │ └── bug_report.md └── workflows │ ├── build.yml │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── __mocks__ └── browser.ts ├── __tests__ ├── test_background.ts └── test_options.ts ├── _locales └── en_US │ └── messages.json ├── build_xpi.sh ├── doc └── release.md ├── images ├── logo_96_blue.png └── logo_96_red.png ├── manifest.json ├── package.json ├── src ├── background.ts ├── common.ts ├── options.html ├── options.ts └── selectionHandler.js └── tsconfig.json /.eslintignore: -------------------------------------------------------------------------------- 1 | __mocks__ 2 | __tests__ 3 | dist 4 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: "@typescript-eslint/parser", 4 | plugins: ["@typescript-eslint"], 5 | extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"], 6 | }; 7 | -------------------------------------------------------------------------------- /.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 | **Versions** 11 | - OS: [e. g. Ubuntu 22.04] 12 | - Joplin Version [e. g. 2.14.22] 13 | - Thunderbird Version [e. g. 115.11.0] 14 | - Joplin Export add-on version [e. g. 0.0.6] 15 | 16 | **Describe the bug** 17 | A clear and concise description of what the bug is. 18 | 19 | **Screenshot or screen recording** 20 | If applicable, add screenshots or a screen recording to help explain your problem. 21 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | container: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v3 10 | - name: Build the addon 11 | run: ./build_xpi.sh 12 | - name: Release 13 | uses: softprops/action-gh-release@v2 14 | # release only if there is a release tag 15 | if: ${{ startsWith(github.ref, 'refs/tags/v') }} 16 | with: 17 | files: joplin-export.xpi 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | container: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v3 10 | - name: Install dependencies 11 | run: npm install 12 | - name: Run the tests 13 | run: npm test -- --coverage --verbose 14 | - name: Publish Code Coverage Results 15 | uses: codecov/codecov-action@v2 16 | with: 17 | files: ./coverage/coverage-final.json 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | coverage 2 | node_modules 3 | test_profile 4 | images/screenshots 5 | notes.txt 6 | *.xpi 7 | *.xcf 8 | package-lock.json 9 | 10 | # JS files are bundled by browserify. See "build_xpi.sh". 11 | dist 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Joplin Export Thunderbird Addon 2 | 3 | Easily export your Thunderbird emails to Joplin. 4 | 5 | [![build](https://github.com/marph91/thunderbird-joplin-export/actions/workflows/build.yml/badge.svg)](https://github.com/marph91/thunderbird-joplin-export/actions/workflows/build.yml) 6 | [![test](https://github.com/marph91/thunderbird-joplin-export/actions/workflows/test.yml/badge.svg)](https://github.com/marph91/thunderbird-joplin-export/actions/workflows/test.yml) 7 | [![codecov](https://codecov.io/gh/marph91/thunderbird-joplin-export/branch/master/graph/badge.svg?token=YZYEW7C1VM)](https://codecov.io/gh/marph91/thunderbird-joplin-export) 8 | 9 | ## Features 10 | 11 | - Export a text selection, a single email or multiple emails to Joplin. 12 | - Export by clicking the button or pressing the hotkey (by default "Ctrl+Alt+J") 13 | - Export the email as note or todo. 14 | - Add metadata to the title and body of the note: 15 | - Set a template for note title and body. 16 | - Trim the author or subject by regex. For example, remove "Re:" or "Fwd:". 17 | - Include the date in a [custom format](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). 18 | - Take a look at [this section](#include-metadata) for details. 19 | - Add tags and attachments from the email. 20 | 21 | ## Installation 22 | 23 | - Via [Thunderbird addon store](https://addons.thunderbird.net/en/thunderbird/addon/joplin-export/) (preferred) 24 | - Via manual import: 25 | 1. Download the artifacts from the [releases page](https://github.com/marph91/thunderbird-joplin-export/releases). 26 | 2. Import to Thunderbird via the addon manager: Tools -> Add-ons -> small gear at top right -> "Install Add-on From File...". 27 | 28 | ## Usage 29 | 30 | 1. Start Joplin. 31 | 2. [Enable the webclipper](https://joplinapp.org/clipper/) and copy the API token. 32 | 3. Configure the plugin: 33 | 1. Paste the API token to the token field. 34 | 2. Save 35 | 3. Refresh the available notebooks by pressing the small update button. 36 | 4. Select a destination notebook. 37 | 5. Save 38 | 4. Select any email. The Joplin button should be at the menu. 39 | 5. Export the email by clicking the button. If there is any problem, a notification will pop up. After a successful export, the email should be in the specified Joplin notebook. 40 | 41 | 42 | 43 | ### Include metadata 44 | 45 | In this section you will find some examples how to include email metadata into note title or body. All metadata of the [mail header object](https://webextension-api.thunderbird.net/en/latest/messages.html#messages-messageheader) can be used. 46 | 47 | By default, the note title template is `{{subject}} from {{author}}`. I. e. the `subject` and `author` keys are searched in the mail header object and inserted into the template if found. Since the subject contains often strings like `Re:` or `Fwd:`, these can be removed by defining a regex. The setting is called "Trim subject". For me, the regex `^(((Re|Fw|Fwd):|(\[.*\])) ?)*` works best. 48 | 49 | It is also possible to insert some metadata at the top of the note body. This can be done by defining a template in the "Note header" setting. The template should be specified in markdown syntax. Words surrounded by double curly brackets will be attempted to be replaced by the corresponding metadata, as done in the note title. 50 | 51 | The following two code snippets show examples of what the templates might look like. 52 | 53 | Plain text with closing separation line: 54 | 55 | ```text 56 | From: {{author}} 57 | Subject: {{subject}} 58 | Date: {{date}} 59 | To: {{recipients}} 60 | 61 | --- 62 | 63 | ``` 64 | 65 | Table with closing separation line: 66 | 67 | ```text 68 | | | | 69 | | ------- | -------------- | 70 | | From | {{author}} | 71 | | Subject | {{subject}} | 72 | | Date | {{date}} | 73 | | To | {{recipients}} | 74 | 75 | --- 76 | 77 | ``` 78 | 79 | ## Troubleshooting 80 | 81 | What to do when the export failed? 82 | 83 | 1. Check that Joplin is running and the webclipper is enabled. 84 | 2. Check that the plugin is configured correctly. There is a status field. The status should be "working". Make sure the API token is set correctly. 85 | 3. Check the developer console. Usually it can be opened by pressing "Ctrl + Shift + I" or going to "Extras -> Developer Tools". There should be some error message. 86 | 4. If the previous steps didn't resolve the issue, you can open a github issue or email me. 87 | 88 | ## Related Projects 89 | 90 | - [Overview in the Joplin forum](https://discourse.joplinapp.org/t/how-to-handle-emails-with-joplin-desktop/37469) 91 | - : Add all emails of an account to Joplin. 92 | - : Export notes from Joplin to your email client. 93 | - : Add all emails of one or more accounts to Joplin. 94 | 95 | ## Further ressources 96 | 97 | - 98 | - 99 | 100 | ## Changelog 101 | 102 | ### 0.0.10 103 | 104 | - Become a pure WebExtension (). 105 | - Add export button to separate message display windows. 106 | 107 | ### 0.0.9 108 | 109 | - Add support for Thunderbird up to version 138 (). 110 | 111 | ### 0.0.8 112 | 113 | - Bugfix: Make export working again when mail body is not displayed (). 114 | 115 | ### 0.0.6 116 | 117 | - Add `author` and `user_created_date` metadata. 118 | - Add support for Thunderbird up to version 127. 119 | 120 | ### 0.0.5 121 | 122 | - Add support for Thunderbird 117 (). 123 | 124 | ### 0.0.4 125 | 126 | - Add export via context menu (). 127 | 128 | ### 0.0.3 129 | 130 | - Add custom author and date (). 131 | - Fix naming of the default tags (). 132 | 133 | ### 0.0.2 134 | 135 | - Add user defined note title (). 136 | 137 | ### 0.0.1 138 | 139 | - Initial release. 140 | -------------------------------------------------------------------------------- /__mocks__/browser.ts: -------------------------------------------------------------------------------- 1 | // Mock all browser access, since we aren't in the frontend. 2 | 3 | type StorageEntry = Record; 4 | 5 | export const browser = { 6 | storage: { 7 | local: { 8 | data: {}, 9 | get: async (nameOrNames: string | Array) => { 10 | switch (typeof nameOrNames) { 11 | case "string": 12 | return { [nameOrNames]: browser.storage.local.data[nameOrNames] }; 13 | case "object": 14 | const result = {}; 15 | for (const name of nameOrNames) { 16 | result[name] = browser.storage.local.data[name]; 17 | } 18 | return result; 19 | default: 20 | throw Error(`Unsupported type: ${typeof nameOrNames}.`); 21 | } 22 | }, 23 | set: async (settings: StorageEntry) => { 24 | for (const [name, value] of Object.entries(settings)) { 25 | browser.storage.local.data[name] = value; 26 | } 27 | }, 28 | }, 29 | }, 30 | browserAction: { 31 | onClicked: { addListener: jest.fn() }, 32 | icon: undefined, 33 | setIcon: (icon: { path: string }) => { 34 | browser.browserAction.icon = icon.path; 35 | }, 36 | }, 37 | mailTabs: { 38 | getSelectedMessages: jest.fn( 39 | async (_tabId) => { messages: [], id: undefined } 40 | ), 41 | }, 42 | menus: { 43 | create: jest.fn(), 44 | onClicked: { addListener: jest.fn() }, 45 | }, 46 | messageDisplay: { 47 | getDisplayedMessage: jest.fn(), 48 | getDisplayedMessages: jest.fn(async (_tabId) => >[]), 49 | }, 50 | messages: { 51 | getFull: jest.fn(async () => { 52 | return { 53 | parts: [ 54 | { 55 | contentType: "text/html", 56 | body: "test content", 57 | parts: [], 58 | }, 59 | ], 60 | }; 61 | }), 62 | listTags: jest.fn(async () => { 63 | return [{ key: "$label1", tag: "Important" }]; 64 | }), 65 | listAttachments: jest.fn(), 66 | getAttachmentFile: jest.fn(), 67 | }, 68 | // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications/create 69 | notifications: { 70 | icon: undefined, 71 | title: undefined, 72 | message: undefined, 73 | create: (options: { iconUrl: string; title: string; message: string }) => { 74 | browser.notifications.icon = options.iconUrl; 75 | browser.notifications.title = options.title; 76 | browser.notifications.message = options.message; 77 | }, 78 | }, 79 | scripting: { messageDisplay: { registerScripts: jest.fn() } }, 80 | tabs: { 81 | // https://webextension-api.thunderbird.net/en/stable/tabs.html#get-tabid 82 | get: jest.fn(async (_tabId) => { type: "mail" }), 83 | // https://webextension-api.thunderbird.net/en/stable/tabs.html#sendmessage-tabid-message-options 84 | sendMessage: jest.fn(async (_tabId, _message) => ""), 85 | }, 86 | }; 87 | 88 | export const messenger = { 89 | commands: { 90 | onCommand: { 91 | addListener: jest.fn(), 92 | }, 93 | }, 94 | messages: { 95 | continueList: jest.fn(async (_id) => { messages: [], id: undefined }), 96 | }, 97 | scripting: { executeScript: jest.fn() }, 98 | tabs: { 99 | query: jest.fn(), 100 | }, 101 | }; 102 | -------------------------------------------------------------------------------- /__tests__/test_background.ts: -------------------------------------------------------------------------------- 1 | import express from "express"; 2 | 3 | // TODO: Navigating to __mocks__ shouldn't be needed. 4 | import { browser, messenger } from "../__mocks__/browser"; 5 | // @ts-ignore 6 | global.browser = browser; 7 | // @ts-ignore 8 | global.messenger = messenger; 9 | 10 | import { 11 | getAndProcessMessages, 12 | handleContextMenu, 13 | handleHotkey, 14 | handleMenuButton, 15 | onlyWhitespace, 16 | processMail, 17 | renderString, 18 | } from "../src/background"; 19 | 20 | // Simple test server. Will receive the request that should go to Joplin. 21 | let app = express(); 22 | let server: any; 23 | let requests: any; 24 | 25 | // Capture all console output. 26 | console.log = jest.fn(); 27 | console.warn = jest.fn(); 28 | console.error = jest.fn(); 29 | 30 | // https://dev.to/chrismilson/zip-iterator-in-typescript-ldm 31 | type Iterableify = { [K in keyof T]: Iterable }; 32 | function* zip>(...toZip: Iterableify): Generator { 33 | // Get iterators for all of the iterables. 34 | const iterators = toZip.map((i) => i[Symbol.iterator]()); 35 | 36 | while (true) { 37 | // Advance all of the iterators. 38 | const results = iterators.map((i) => i.next()); 39 | 40 | // If any of the iterators are done, we should stop. 41 | if (results.some(({ done }) => done)) { 42 | break; 43 | } 44 | 45 | // We can assert the yield type, since we know none 46 | // of the iterators are done. 47 | yield results.map(({ value }) => value) as T; 48 | } 49 | } 50 | 51 | const expectConsole = (expected: { [Key: string]: Array | number }) => { 52 | // Check whether the console output is as expected. 53 | 54 | for (const [method, lengthOrContent] of Object.entries(expected)) { 55 | // @ts-ignore 56 | const actual = >>console[method].mock.calls; 57 | if (typeof lengthOrContent === "number") { 58 | // Only check number of calls. 59 | expect(actual.length).toBe(lengthOrContent); 60 | } else { 61 | // Check content of calls. 62 | for (const [actualOutput, expectedOutput] of zip( 63 | actual, 64 | lengthOrContent 65 | )) { 66 | expect(actualOutput[0]).toBe(expectedOutput); 67 | } 68 | } 69 | } 70 | }; 71 | 72 | beforeAll(() => { 73 | // https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener 74 | server = app.listen(41142); 75 | app.use(express.json()); // allow easy access of request.body 76 | 77 | // TODO: How to flexibly assign and delete routes/middlewares? 78 | // https://stackoverflow.com/a/28369539/7410886 79 | app.use((req, res, next) => { 80 | requests.push(req); 81 | 82 | if (req.query.token !== "validToken") { 83 | res.status(401).send("Invalid token"); 84 | } 85 | 86 | let returnData: any; 87 | switch (req.path) { 88 | case "/notes": 89 | // console.log(req.body); 90 | returnData = { items: [] }; 91 | break; 92 | case "/resources": 93 | returnData = { items: [] }; 94 | break; 95 | case "/search": 96 | if (req.query.type === "tag") { 97 | switch (req.query.query) { 98 | case "existentTag": 99 | returnData = { items: [{ id: "arbitraryId" }] }; 100 | break; 101 | case "multipleTags": 102 | returnData = { 103 | items: [ 104 | { id: "arbitraryId1", title: "a" }, 105 | { id: "arbitraryId2", title: "b" }, 106 | ], 107 | }; 108 | break; 109 | default: 110 | returnData = { items: [] }; 111 | } 112 | } 113 | break; 114 | case "/tags": 115 | if (req.body.title.trim() !== req.body.title) { 116 | res 117 | .status(500) 118 | .send( 119 | "Tag shouldn't start or end with whitespaces. " + 120 | "They get stripped by Joplin, which can lead to inconsistent behaviour." 121 | ); 122 | } 123 | returnData = { items: [] }; 124 | break; 125 | default: 126 | //console.log(req.path); 127 | } 128 | 129 | if (req.method === "PUT" && req.path.startsWith("/notes")) { 130 | returnData = { items: [] }; 131 | } 132 | 133 | res.status(200).send(JSON.stringify(returnData)); 134 | }); 135 | }); 136 | 137 | beforeEach(() => { 138 | jest.clearAllMocks(); 139 | 140 | // TODO: How to reset the object properly? 141 | browser.notifications.icon = undefined; 142 | browser.notifications.title = undefined; 143 | browser.notifications.message = undefined; 144 | browser.browserAction.icon = undefined; 145 | 146 | // Set local storage to mostly default values. 147 | browser.storage.local.data = { 148 | joplinScheme: "http", 149 | joplinHost: "127.0.0.1", 150 | joplinPort: 41142, 151 | joplinToken: "validToken", 152 | 153 | joplinShowNotifications: "onFailure", 154 | 155 | joplinSubjectTrimRegex: "", 156 | joplinAuthorTrimRegex: "", 157 | joplinDateFormat: "", 158 | joplinNoteTitleTemplate: "{{subject}} from {{author}}", 159 | joplinNoteHeaderTemplate: "", 160 | joplinNoteParentFolder: "arbitrary folder", 161 | joplinNoteFormat: "text/html", 162 | joplinExportAsTodo: false, 163 | // Try to keep the tests minimal. 164 | joplinNoteTags: "", 165 | joplinNoteTagsFromEmail: false, 166 | joplinAttachments: "ignore", 167 | }; 168 | requests = []; 169 | }); 170 | 171 | afterAll(() => { 172 | server.close(); 173 | }); 174 | 175 | describe("handle button / hotkey / context menu", () => { 176 | test("API token not set", async () => { 177 | await browser.storage.local.set({ joplinToken: undefined }); 178 | 179 | await getAndProcessMessages({ id: 0 }, {}); 180 | expect(browser.notifications.icon).toBe("../images/logo_96_red.png"); 181 | expect(browser.notifications.title).toBe("Joplin export failed"); 182 | expect(browser.notifications.message).toBe("API token missing."); 183 | 184 | expectConsole({ 185 | log: 0, 186 | warn: 0, 187 | error: 0, 188 | }); 189 | }); 190 | 191 | test("invalid API token", async () => { 192 | await browser.storage.local.set({ joplinToken: "invalidToken" }); 193 | browser.mailTabs.getSelectedMessages.mockResolvedValueOnce({ 194 | messages: [{ id: 0 }], 195 | }); 196 | await getAndProcessMessages({ id: 0 }, {}); 197 | 198 | expect(browser.notifications.icon).toBe("../images/logo_96_red.png"); 199 | expect(browser.notifications.title).toBe("Joplin export failed"); 200 | expect(browser.notifications.message).toBe( 201 | "Please check the developer console." 202 | ); 203 | 204 | expectConsole({ 205 | log: 1, 206 | warn: 0, 207 | error: ["[Joplin Export] Failed to create note: Invalid token"], 208 | }); 209 | }); 210 | 211 | test.each` 212 | showNotificationsSetting | exportSuccessful | notificationShown 213 | ${"always"} | ${true} | ${true} 214 | ${"always"} | ${false} | ${true} 215 | ${"onSuccess"} | ${true} | ${true} 216 | ${"onSuccess"} | ${false} | ${false} 217 | ${"onFailure"} | ${true} | ${false} 218 | ${"onFailure"} | ${false} | ${true} 219 | ${"never"} | ${true} | ${false} 220 | ${"never"} | ${false} | ${false} 221 | `( 222 | "show notifications setting: $showNotificationsSetting | export success: $exportSuccessful | notification shown: $notificationShown", 223 | async ({ 224 | showNotificationsSetting, 225 | exportSuccessful, 226 | notificationShown, 227 | }) => { 228 | await browser.storage.local.set({ 229 | joplinShowNotifications: showNotificationsSetting, 230 | }); 231 | 232 | // "{ id: 0 }" yields a successful export. 233 | // "null" triggers the error "Mail header is empty". 234 | browser.mailTabs.getSelectedMessages.mockResolvedValueOnce({ 235 | messages: exportSuccessful ? [{ id: 0 }] : [null], 236 | }); 237 | 238 | await getAndProcessMessages({ id: 0 }, {}); 239 | 240 | // Check the notification. 241 | let expectedResult = { 242 | icon: undefined, 243 | title: undefined, 244 | message: undefined, 245 | }; 246 | if (notificationShown) { 247 | if (exportSuccessful) { 248 | expectedResult = { 249 | icon: "../images/logo_96_blue.png", 250 | title: "Joplin export succeeded", 251 | message: "Exported one email.", 252 | }; 253 | } else { 254 | expectedResult = { 255 | icon: "../images/logo_96_red.png", 256 | title: "Joplin export failed", 257 | message: "Please check the developer console.", 258 | }; 259 | } 260 | } 261 | expect(browser.notifications).toEqual( 262 | expect.objectContaining(expectedResult) 263 | ); 264 | 265 | expectConsole({ 266 | log: exportSuccessful ? 1 : 0, 267 | warn: 0, 268 | error: exportSuccessful ? 0 : 1, 269 | }); 270 | } 271 | ); 272 | 273 | test("export by menu button", async () => { 274 | messenger.tabs.query.mockResolvedValueOnce([{ id: 1 }]); 275 | browser.mailTabs.getSelectedMessages.mockResolvedValueOnce({ 276 | messages: [{ id: 1 }], 277 | }); 278 | 279 | await handleMenuButton({ id: 1 }, { menuItemId: "export_to_joplin" }); 280 | 281 | expect(requests.length).toBe(1); 282 | expectConsole({ 283 | log: 1, 284 | warn: 0, 285 | error: 0, 286 | }); 287 | }); 288 | 289 | test("export by hotkey", async () => { 290 | messenger.tabs.query.mockResolvedValueOnce([{ id: 1 }]); 291 | browser.mailTabs.getSelectedMessages.mockResolvedValueOnce({ 292 | messages: [{ id: 1 }], 293 | }); 294 | 295 | await handleHotkey("export_to_joplin"); 296 | 297 | expect(requests.length).toBe(1); 298 | expectConsole({ 299 | log: 1, 300 | warn: 0, 301 | error: 0, 302 | }); 303 | }); 304 | 305 | test("export by context menu", async () => { 306 | messenger.tabs.query.mockResolvedValueOnce([{ id: 1 }]); 307 | browser.mailTabs.getSelectedMessages.mockResolvedValueOnce({ 308 | messages: [{ id: 1 }], 309 | }); 310 | 311 | await handleContextMenu({ menuItemId: "export_to_joplin" }, { id: 1 }); 312 | 313 | expect(requests.length).toBe(1); 314 | expectConsole({ 315 | log: 1, 316 | warn: 0, 317 | error: 0, 318 | }); 319 | }); 320 | }); 321 | 322 | describe("handle displayed and selected mails", () => { 323 | test("one selected mail", async () => { 324 | messenger.tabs.query.mockResolvedValueOnce([{ id: 1 }]); 325 | browser.mailTabs.getSelectedMessages.mockResolvedValueOnce({ 326 | messages: [{ id: 1 }], 327 | }); 328 | 329 | await getAndProcessMessages({ id: 1 }, {}); 330 | 331 | expect(requests.length).toBe(1); 332 | expectConsole({ 333 | log: 1, 334 | warn: 0, 335 | error: 0, 336 | }); 337 | }); 338 | 339 | test("no selected mail, one displayed mail", async () => { 340 | messenger.tabs.query.mockResolvedValueOnce([{ id: 1 }]); 341 | browser.tabs.get.mockResolvedValueOnce({ type: "messageDisplay" }); 342 | browser.messageDisplay.getDisplayedMessages.mockResolvedValueOnce([ 343 | { id: 1 }, 344 | ]); 345 | 346 | await getAndProcessMessages({ id: 1 }, {}); 347 | 348 | expect(requests.length).toBe(1); 349 | expectConsole({ 350 | log: 1, 351 | warn: 0, 352 | error: 0, 353 | }); 354 | }); 355 | 356 | test("no selectedmail, no displayed mail", async () => { 357 | messenger.tabs.query.mockResolvedValueOnce([{ id: 1 }]); 358 | 359 | await getAndProcessMessages({ id: 1 }, {}); 360 | 361 | expect(requests.length).toBe(0); 362 | expectConsole({ 363 | log: 0, 364 | warn: 1, 365 | error: 0, 366 | }); 367 | }); 368 | }); 369 | 370 | describe("process mail", () => { 371 | test("empty header", async () => { 372 | const result = await processMail(undefined, { id: 0 }); 373 | expect(result).toBe("Mail header is empty"); 374 | 375 | expectConsole({ 376 | log: 0, 377 | warn: 0, 378 | error: 0, 379 | }); 380 | }); 381 | 382 | test("undefined body", async () => { 383 | browser.messages.getFull.mockResolvedValueOnce(undefined); 384 | 385 | // Arbitrary id, since we mock the mail anyway. 386 | const result = await processMail({ id: 0 }, { id: 0 }); 387 | expect(result).toBe("Mail body is empty"); 388 | 389 | expectConsole({ 390 | log: 0, 391 | warn: 0, 392 | error: 0, 393 | }); 394 | }); 395 | 396 | test("empty body", async () => { 397 | browser.messages.getFull.mockResolvedValueOnce({}); 398 | 399 | const result = await processMail({ id: 0 }, { id: 0 }); 400 | expect(result).toBe("Mail body is empty"); 401 | 402 | expectConsole({ 403 | log: 0, 404 | warn: 0, 405 | error: 0, 406 | }); 407 | }); 408 | 409 | test("add header info", async () => { 410 | const subject = "test subject"; 411 | const author = "test author"; 412 | const date = new Date("1995-12-17T03:24:00"); 413 | const recipients = ["recipient 1", "recipient 2"]; 414 | const body = "test body"; 415 | 416 | await browser.storage.local.set({ 417 | joplinNoteHeaderTemplate: ` 418 | From: {{author}} 419 | Subject: {{subject}} 420 | Date: {{date}} 421 | To: {{recipients}} 422 | 423 | --- 424 | 425 | `, 426 | }); 427 | 428 | const result = await processMail( 429 | { 430 | id: 1, 431 | subject: subject, 432 | author: author, 433 | date: date, 434 | recipients: recipients, 435 | }, 436 | { 437 | id: 0, 438 | } 439 | ); 440 | 441 | expect(result).toBe(null); 442 | // 1 request to create the note. 443 | // 1 request to add the header info. 444 | expect(requests.length).toBe(2); 445 | for (const info of [ 446 | subject, 447 | author, 448 | date.toString(), 449 | recipients[0], 450 | recipients[1], 451 | ]) { 452 | expect(requests[1].body.body).toContain(info); 453 | } 454 | expectConsole({ 455 | log: 1, 456 | warn: 0, 457 | error: 0, 458 | }); 459 | }); 460 | 461 | test.each` 462 | preferredFormat | htmlAvailable | plainAvailable | resultFormat 463 | ${"text/html"} | ${false} | ${false} | ${null} 464 | ${"text/html"} | ${false} | ${true} | ${"text/plain"} 465 | ${"text/html"} | ${true} | ${false} | ${"text/html"} 466 | ${"text/html"} | ${true} | ${true} | ${"text/html"} 467 | ${"text/plain"} | ${false} | ${false} | ${null} 468 | ${"text/plain"} | ${false} | ${true} | ${"text/plain"} 469 | ${"text/plain"} | ${true} | ${false} | ${"text/html"} 470 | ${"text/plain"} | ${true} | ${true} | ${"text/plain"} 471 | `( 472 | "preferred: $preferredFormat | available: html: $htmlAvailable, plain: $plainAvailable | result: $resultFormat", 473 | async ({ 474 | preferredFormat, 475 | htmlAvailable, 476 | plainAvailable, 477 | resultFormat, 478 | }) => { 479 | const subject = "test subject"; 480 | const author = "test author"; 481 | const date = new Date(Date.now()); 482 | const body = "test body"; 483 | 484 | await browser.storage.local.set({ joplinNoteFormat: preferredFormat }); 485 | 486 | browser.messages.getFull.mockResolvedValueOnce({ 487 | parts: [ 488 | { 489 | contentType: "text/html", 490 | body: htmlAvailable ? body : "", 491 | parts: [], 492 | }, 493 | { 494 | contentType: "text/plain", 495 | body: plainAvailable ? body : "", 496 | parts: [], 497 | }, 498 | ], 499 | }); 500 | 501 | const result = await processMail( 502 | { 503 | id: 0, 504 | subject: subject, 505 | author: author, 506 | date: date, 507 | }, 508 | { 509 | id: 0, 510 | } 511 | ); 512 | 513 | if (!resultFormat) { 514 | expect(result).toBe("Mail body is empty"); 515 | return; 516 | } 517 | 518 | expect(result).toBe(null); 519 | expect(requests.length).toBe(1); 520 | expect(requests[0].method).toBe("POST"); 521 | expect(requests[0].url).toBe( 522 | `/notes?fields=id,body&token=${browser.storage.local.data.joplinToken}` 523 | ); 524 | const expectedKey = resultFormat === "text/html" ? "body_html" : "body"; 525 | expect(requests[0].body).toEqual({ 526 | [expectedKey]: body, 527 | parent_id: browser.storage.local.data.joplinNoteParentFolder, 528 | title: `${subject} from ${author}`, 529 | is_todo: 0, 530 | author: author, 531 | user_created_time: date.getTime(), 532 | }); 533 | 534 | // Finally check the console output. 535 | const message = 536 | resultFormat === "text/html" 537 | ? "[Joplin Export] Sending complete email in HTML format." 538 | : "[Joplin Export] Sending complete email in plain format."; 539 | expectConsole({ 540 | log: [message], 541 | warn: 0, 542 | error: 0, 543 | }); 544 | } 545 | ); 546 | 547 | test("export selection", async () => { 548 | const subject = "test subject"; 549 | const author = "test author"; 550 | const date = new Date(Date.now()); 551 | const body = "test body"; 552 | 553 | browser.messageDisplay.getDisplayedMessage.mockResolvedValueOnce({ id: 1 }); 554 | browser.tabs.sendMessage.mockResolvedValueOnce(body); 555 | 556 | const result = await processMail( 557 | { 558 | id: 0, 559 | subject: subject, 560 | author: author, 561 | date: date, 562 | }, 563 | { 564 | id: 0, 565 | } 566 | ); 567 | expect(result).toBe(null); 568 | 569 | expect(requests.length).toBe(1); 570 | expect(requests[0].body).toEqual({ 571 | body: body, 572 | parent_id: browser.storage.local.data.joplinNoteParentFolder, 573 | title: `${subject} from ${author}`, 574 | is_todo: 0, 575 | author: author, 576 | user_created_time: date.getTime(), 577 | }); 578 | 579 | expectConsole({ 580 | log: ["[Joplin Export] Sending selection in plain format."], 581 | warn: 0, 582 | error: 0, 583 | }); 584 | }); 585 | 586 | test("export as todo", async () => { 587 | await browser.storage.local.set({ joplinExportAsTodo: true }); 588 | 589 | const result = await processMail({ id: 0 }, { id: 0 }); 590 | 591 | expect(result).toBe(null); 592 | expect(requests.length).toBe(1); 593 | expect(requests[0].body).toEqual(expect.objectContaining({ is_todo: 1 })); 594 | 595 | expectConsole({ 596 | log: 1, 597 | warn: 0, 598 | error: 0, 599 | }); 600 | }); 601 | 602 | test.each` 603 | inputSubject | regexString | expectedSubject 604 | ${"Re: Re: Fwd:[topic] subject Re:"} | ${""} | ${"Re: Re: Fwd:[topic] subject Re:"} 605 | ${"Re: Re: Fwd:[topic] subject Re:"} | ${"^(((Re|Fw|Fwd):|(\\[.*\\])) ?)*"} | ${"subject Re:"} 606 | `( 607 | "modify subject by regex: $regexString", 608 | async ({ inputSubject, regexString, expectedSubject }) => { 609 | const author = "author name"; 610 | await browser.storage.local.set({ joplinSubjectTrimRegex: regexString }); 611 | 612 | const result = await processMail( 613 | { 614 | id: 1, 615 | subject: inputSubject, 616 | author: author, 617 | }, 618 | { 619 | id: 0, 620 | } 621 | ); 622 | 623 | expect(result).toBe(null); 624 | expect(requests.length).toBe(1); 625 | expect(requests[0].body).toEqual( 626 | expect.objectContaining({ title: `${expectedSubject} from ${author}` }) 627 | ); 628 | 629 | expectConsole({ 630 | log: 1, 631 | warn: 0, 632 | error: 0, 633 | }); 634 | } 635 | ); 636 | 637 | test.each` 638 | inputAuthor | regexString | expectedAuthor 639 | ${"John Doof "} | ${""} | ${"John Doof "} 640 | ${"John Doof "} | ${" ?<.*>$"} | ${"John Doof"} 641 | `( 642 | "modify author by regex: $regexString", 643 | async ({ inputAuthor, regexString, expectedAuthor }) => { 644 | const subject = "some subject"; 645 | await browser.storage.local.set({ joplinAuthorTrimRegex: regexString }); 646 | 647 | const result = await processMail( 648 | { 649 | id: 1, 650 | subject: subject, 651 | author: inputAuthor, 652 | }, 653 | { 654 | id: 0, 655 | } 656 | ); 657 | 658 | expect(result).toBe(null); 659 | expect(requests.length).toBe(1); 660 | expect(requests[0].body).toEqual( 661 | expect.objectContaining({ title: `${subject} from ${expectedAuthor}` }) 662 | ); 663 | 664 | expectConsole({ 665 | log: 1, 666 | warn: 0, 667 | error: 0, 668 | }); 669 | } 670 | ); 671 | 672 | test.each` 673 | inputDate | dateFormat | expectedDate 674 | ${new Date(2022, 4, 6)} | ${""} | ${new Date(2022, 4, 6).toString()} 675 | ${new Date("1995-12-17T03:24:00")} | ${"d.L.y T"} | ${"17.12.1995 03:24"} 676 | `( 677 | "apply date format: $dateFormat", 678 | async ({ inputDate, dateFormat, expectedDate }) => { 679 | const author = "author name"; 680 | const subject = "some subject"; 681 | await browser.storage.local.set({ 682 | joplinNoteTitleTemplate: "{{subject}} from {{author}} at {{date}}", 683 | joplinDateFormat: dateFormat, 684 | }); 685 | 686 | const result = await processMail( 687 | { 688 | id: 1, 689 | subject: subject, 690 | author: author, 691 | date: inputDate, 692 | }, 693 | { 694 | id: 0, 695 | } 696 | ); 697 | 698 | expect(result).toBe(null); 699 | expect(requests.length).toBe(1); 700 | expect(requests[0].body).toEqual( 701 | expect.objectContaining({ 702 | title: `${subject} from ${author} at ${expectedDate}`, 703 | }) 704 | ); 705 | 706 | expectConsole({ 707 | log: 1, 708 | warn: 0, 709 | error: 0, 710 | }); 711 | } 712 | ); 713 | }); 714 | 715 | describe("process tag", () => { 716 | test.each` 717 | emailTags | includeEmailTags | customTags 718 | ${[]} | ${false} | ${""} 719 | ${[]} | ${false} | ${"customTag"} 720 | ${[]} | ${true} | ${""} 721 | ${[]} | ${true} | ${"customTag"} 722 | ${["$label1"]} | ${false} | ${""} 723 | ${["$label1"]} | ${false} | ${"customTag"} 724 | ${["$label1"]} | ${true} | ${""} 725 | ${["$label1"]} | ${true} | ${"customTag"} 726 | ${[]} | ${false} | ${" customTag "} 727 | `( 728 | "emailTags: $emailTags | includeEmailTags: $includeEmailTags | customTags: $customTags", 729 | async ({ emailTags, includeEmailTags, customTags }) => { 730 | await browser.storage.local.set({ 731 | joplinNoteTags: customTags, 732 | joplinNoteTagsFromEmail: includeEmailTags, 733 | }); 734 | 735 | const result = await processMail({ id: 0, tags: emailTags }, { id: 0 }); 736 | expect(result).toBe(null); 737 | 738 | // 1 request to create the note. 739 | // 3 requests per tag: get tags, create tag, attach tag to note 740 | expect(requests.length).toBe( 741 | 1 + 742 | 3 * Number(customTags != "") + 743 | 3 * Number(includeEmailTags && emailTags.length > 0) 744 | ); 745 | 746 | expectConsole({ 747 | log: 1, 748 | warn: 0, 749 | error: 0, 750 | }); 751 | } 752 | ); 753 | 754 | test("tag already existent", async () => { 755 | await browser.storage.local.set({ joplinNoteTags: "existentTag" }); 756 | 757 | const result = await processMail({ id: 0, tags: [] }, { id: 0 }); 758 | expect(result).toBe(null); 759 | 760 | // 1 request to create the note. 761 | // 1 request for searching the tag. 762 | // 1 request for attaching the tag to the note. 763 | expect(requests.length).toBe(3); 764 | 765 | expectConsole({ 766 | log: 1, 767 | warn: 0, 768 | error: 0, 769 | }); 770 | }); 771 | 772 | test("too many tags existent", async () => { 773 | await browser.storage.local.set({ joplinNoteTags: "multipleTags" }); 774 | 775 | const result = await processMail({ id: 0, tags: [] }, { id: 0 }); 776 | expect(result).toBe(null); 777 | 778 | // 1 request to create the note. 779 | // 1 request for searching the tag. 780 | expect(requests.length).toBe(2); 781 | 782 | expectConsole({ 783 | log: 1, 784 | warn: ['[Joplin Export] Too many matching tags for "multipleTags": a, b'], 785 | error: 0, 786 | }); 787 | }); 788 | }); 789 | 790 | describe("process attachment", () => { 791 | beforeAll(() => { 792 | // FormData is not available: https://stackoverflow.com/a/59726560/7410886 793 | // It works, but not sure how to resolve the typescript issues. 794 | function FormDataMock() { 795 | // @ts-ignore 796 | this.append = jest.fn(); 797 | } 798 | // @ts-ignore 799 | global.FormData = FormDataMock; 800 | }); 801 | 802 | test.each` 803 | attachments | handleAttachments 804 | ${[]} | ${"attach"} 805 | ${[]} | ${"ignore"} 806 | ${["foo"]} | ${"attach"} 807 | ${["foo"]} | ${"ignore"} 808 | `( 809 | "attachments: $attachments | handleAttachments: $handleAttachments", 810 | async ({ attachments, handleAttachments }) => { 811 | await browser.storage.local.set({ joplinAttachments: handleAttachments }); 812 | 813 | // Don't use once, since the functions gets only called in specific circumstances. 814 | browser.messages.listAttachments.mockResolvedValue( 815 | attachments.map((a: string) => { 816 | return { name: a, partName: a }; 817 | }) 818 | ); 819 | browser.messages.getAttachmentFile.mockResolvedValue(attachments); 820 | 821 | const result = await processMail({ id: 0 }, { id: 0 }); 822 | expect(result).toBe(null); 823 | 824 | // 1 request to create the note. 825 | // 1 request for creating the attachment (= resource in joplin). 826 | // 1 request for attaching the resource to the note. 827 | expect(requests.length).toBe( 828 | 1 + 2 * Number(handleAttachments === "attach" && attachments.length > 0) 829 | ); 830 | 831 | expectConsole({ 832 | log: 1, 833 | warn: 0, 834 | error: 0, 835 | }); 836 | } 837 | ); 838 | }); 839 | 840 | describe("util", () => { 841 | test.each` 842 | input | expectedOutput 843 | ${""} | ${true} 844 | ${" "} | ${true} 845 | ${" \n \t "} | ${true} 846 | ${"foo"} | ${false} 847 | ${" bar "} | ${false} 848 | `( 849 | "onlyWhitespace | input: $input | expectedOutput: $expectedOutput", 850 | ({ input, expectedOutput }) => { 851 | expect(onlyWhitespace(input)).toBe(expectedOutput); 852 | } 853 | ); 854 | 855 | test.each` 856 | template | context | expectedOutput 857 | ${""} | ${{}} | ${""} 858 | ${""} | ${{ defined: "123" }} | ${""} 859 | ${"{{}}"} | ${{}} | ${"{{}}"} 860 | ${"{{ }}"} | ${{}} | ${"{{ }}"} 861 | ${"{{undefined}}"} | ${{ defined: "123" }} | ${"{{undefined}}"} 862 | ${"{{defined}}"} | ${{ defined: "123" }} | ${"123"} 863 | ${"{{ defined }}"} | ${{ defined: "123" }} | ${"123"} 864 | ${"{{{{defined}}}}"} | ${{ defined: "123" }} | ${"{{{{defined}}}}"} 865 | ${"{{defined}}: {{undefined}}"} | ${{ defined: "123" }} | ${"123: {{undefined}}"} 866 | ${"{{defined}}: {{defined}}"} | ${{ defined: "123" }} | ${"123: 123"} 867 | ${"{{defined}}\n{{defined}}"} | ${{ defined: "123" }} | ${"123\n123"} 868 | ${"{{array}}"} | ${{ array: ["1", "2"] }} | ${"1,2"} 869 | ${"{{bool}}"} | ${{ bool: true }} | ${"true"} 870 | `( 871 | "renderString | template: $template | context: $context | expectedOutput: $expectedOutput", 872 | ({ template, context, expectedOutput }) => { 873 | expect(renderString(template, context)).toBe(expectedOutput); 874 | } 875 | ); 876 | }); 877 | -------------------------------------------------------------------------------- /__tests__/test_options.ts: -------------------------------------------------------------------------------- 1 | import fs from "fs"; 2 | import path from "path"; 3 | const html = fs.readFileSync(path.resolve(__dirname, "../dist/options.html")); 4 | 5 | // TODO: Navigating to __mocks__ shouldn't be needed. 6 | import { browser, messenger } from "../__mocks__/browser"; 7 | 8 | import { JSDOM } from "jsdom"; 9 | 10 | jest.dontMock("fs"); 11 | 12 | let dom: any; 13 | const setting_ids = [ 14 | "joplinScheme", 15 | "joplinHost", 16 | "joplinPort", 17 | "joplinToken", 18 | "joplinShowNotifications", 19 | "joplinSubjectTrimRegex", 20 | "joplinAuthorTrimRegex", 21 | "joplinDateFormat", 22 | "joplinNoteTitleTemplate", 23 | "joplinNoteHeaderTemplate", 24 | "joplinNoteFormat", 25 | "joplinExportAsTodo", 26 | "joplinAttachments", 27 | "joplinNoteTags", 28 | "joplinNoteTagsFromEmail", 29 | ]; 30 | 31 | describe("options", function () { 32 | beforeAll((done) => { 33 | dom = new JSDOM(html.toString(), { 34 | runScripts: "dangerously", 35 | resources: "usable", 36 | // https://github.com/jsdom/jsdom/issues/3023#issuecomment-883585057 37 | url: `file://${__dirname}/../dist/options.html`, 38 | }); 39 | // @ts-ignore 40 | global.browser = browser; 41 | dom.window.browser = browser; 42 | // @ts-ignore 43 | global.messenger = messenger; 44 | 45 | // Wait until the dom isready. 46 | dom.window.document.addEventListener("DOMContentLoaded", () => { 47 | done(); 48 | }); 49 | }); 50 | 51 | afterEach(() => { 52 | // restore the original func after test 53 | jest.resetModules(); 54 | }); 55 | 56 | test("settings exist", () => { 57 | for (const id of setting_ids) { 58 | expect(dom.window.document.getElementById(id)).toBeTruthy(); 59 | } 60 | }); 61 | 62 | test("local cache init", () => { 63 | expect(Object.keys(browser.storage.local.data)).toEqual(setting_ids); 64 | }); 65 | 66 | test("save settings", async () => { 67 | // Modify some arbitrary settings and check if they are in the local storage after saving. 68 | const settings = { 69 | joplinScheme: "https", 70 | joplinToken: "abc", 71 | joplinAttachments: "ignore", 72 | joplinNoteTagsFromEmail: false, 73 | }; 74 | 75 | for (const [setting_name, setting_value] of Object.entries(settings)) { 76 | const element = dom.window.document.getElementById(setting_name); 77 | if (typeof setting_value === "boolean") { 78 | element.checked = setting_value; 79 | } else { 80 | element.value = setting_value; 81 | } 82 | } 83 | const saveButton = dom.window.document.getElementById("btnSave"); 84 | await saveButton.dispatchEvent(new dom.window.MouseEvent("click")); 85 | 86 | expect(browser.storage.local.data).toEqual( 87 | expect.objectContaining(settings) 88 | ); 89 | }); 90 | }); 91 | -------------------------------------------------------------------------------- /_locales/en_US/messages.json: -------------------------------------------------------------------------------- 1 | { 2 | "extensionDescription": { 3 | "message": "Export emails to Joplin" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /build_xpi.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -e # exit on error 4 | 5 | # install dependencies 6 | npm install 7 | 8 | # transpile ts modules 9 | npx browserify src/common.ts src/background.ts -p tsify -o dist/background.js 10 | npx browserify src/common.ts src/options.ts -p tsify -o dist/options.js 11 | 12 | # Copy the needed files to the dist folder. 13 | cp src/*.html src/*.js* dist 14 | 15 | # create thunderbird addon 16 | rm -f joplin-export.xpi 17 | zip joplin-export.xpi _locales/**/*.json images/*.png dist/* manifest.json 18 | -------------------------------------------------------------------------------- /doc/release.md: -------------------------------------------------------------------------------- 1 | # How to do a release 2 | 3 | 1. Increment the version at [`manifest.json`](../manifest.json). 4 | 2. Build the add-on manually via [`build_xpi.sh`](../build_xpi.sh) 5 | 3. Test it (see section below). 6 | 4. Push the changes. 7 | 5. Add the changes at the changelog in the readme. 8 | 6. Create and push the tag: `git tag vX.Y.Z && git push origin vX.Y.Z` 9 | 7. Submit the add-on at . 10 | 11 | NB: [List of valid Thunderbird versions](https://addons.thunderbird.net/en-US/thunderbird/pages/appversions/) 12 | 13 | ## How to test a release 14 | 15 | The automated tests should be successful. Additionally, the following cases should be tested manually: 16 | 17 | Export via: 18 | 19 | - Menu button 20 | - Context menu 21 | - Hotkey 22 | 23 | Tabs/windows: 24 | 25 | - Mail tab with mail body 26 | - Mail tab without mail body 27 | - Mail in a separate tab 28 | - Mail in a separate window 29 | -------------------------------------------------------------------------------- /images/logo_96_blue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marph91/thunderbird-joplin-export/1aa6bbc5bb0ad7b3971a210619cae728aef2defc/images/logo_96_blue.png -------------------------------------------------------------------------------- /images/logo_96_red.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marph91/thunderbird-joplin-export/1aa6bbc5bb0ad7b3971a210619cae728aef2defc/images/logo_96_red.png -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "Joplin Export", 4 | "description": "__MSG_extensionDescription__", 5 | "version": "0.0.10", 6 | "author": "Marph", 7 | "homepage_url": "https://github.com/marph91/thunderbird-joplin-export", 8 | "applications": { 9 | "gecko": { 10 | "id": "joplin-export@martin.doerfelt", 11 | "strict_min_version": "128.0" 12 | } 13 | }, 14 | "background": { 15 | "scripts": ["dist/background.js"] 16 | }, 17 | "browser_action": { 18 | "default_title": "Joplin Export", 19 | "default_icon": "images/logo_96_blue.png", 20 | "default_windows": ["normal", "messageDisplay"] 21 | }, 22 | "commands": { 23 | "export_to_joplin": { 24 | "suggested_key": { 25 | "default": "Ctrl+Alt+J" 26 | }, 27 | "description": "Export emails by hotkey." 28 | } 29 | }, 30 | "options_ui": { 31 | "page": "dist/options.html" 32 | }, 33 | "permissions": [ 34 | "menus", 35 | "messagesRead", 36 | "notifications", 37 | "storage", 38 | "scripting" 39 | ], 40 | "icons": { 41 | "96": "images/logo_96_blue.png" 42 | }, 43 | "default_locale": "en_US" 44 | } 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "browserify": "^17.0.1", 4 | "luxon": "^3.5.0", 5 | "tsify": "^5.0.4" 6 | }, 7 | "devDependencies": { 8 | "@types/express": "^5.0.0", 9 | "@types/jest": "^29.5.14", 10 | "@types/jsdom": "^21.1.7", 11 | "@types/luxon": "^3.4.2", 12 | "@typescript-eslint/eslint-plugin": "^8.26.1", 13 | "@typescript-eslint/parser": "^8.26.1", 14 | "eslint": "^9.22.0", 15 | "express": "^4.21.2", 16 | "jest": "^29.7.0", 17 | "jsdom": "^26.0.0", 18 | "ts-jest": "^29.2.6", 19 | "typescript": "^5.8.2" 20 | }, 21 | "scripts": { 22 | "compile-options": "npx browserify src/common.ts src/options.ts -p tsify -o dist/options.js", 23 | "copy-html": "cp src/*.html dist", 24 | "lint": "eslint .", 25 | "test": "npm run -s compile-options && npm run -s copy-html && jest" 26 | }, 27 | "jest": { 28 | "preset": "ts-jest" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/background.ts: -------------------------------------------------------------------------------- 1 | import { DateTime } from "luxon"; 2 | import { generateUrl, getSetting } from "./common"; 3 | 4 | declare const browser: any; 5 | declare const messenger: any; 6 | 7 | ////////////////////////////////////////////////// 8 | // Export by menu button 9 | ////////////////////////////////////////////////// 10 | 11 | async function handleMenuButton(tab: { id: number }, info: any) { 12 | console.debug("[Joplin Export] Export via menu button."); 13 | await getAndProcessMessages(tab, {}); 14 | } 15 | 16 | ////////////////////////////////////////////////// 17 | // Export by context menu 18 | ////////////////////////////////////////////////// 19 | 20 | browser.menus.create({ 21 | id: "export_to_joplin", 22 | title: "Joplin Export", 23 | // https://developer.thunderbird.net/add-ons/mailextensions/supported-ui-elements#menu-items 24 | contexts: ["message_list", "page", "frame", "selection"], 25 | }); 26 | 27 | async function handleContextMenu( 28 | info: { menuItemId: string }, 29 | tab: { id: number } 30 | ) { 31 | if (info.menuItemId === "export_to_joplin") { 32 | console.debug("[Joplin Export] Export via context menu."); 33 | await getAndProcessMessages(tab, {}); 34 | } 35 | } 36 | 37 | ////////////////////////////////////////////////// 38 | // Export by hotkey 39 | ////////////////////////////////////////////////// 40 | 41 | async function handleHotkey(command: string) { 42 | // Called if hotkey is pressed. 43 | 44 | if (command === "export_to_joplin") { 45 | console.debug("[Joplin Export] Export via hotkey."); 46 | // Only the active tab is queried. So the array contains always exactly one element. 47 | const [activeTab] = await messenger.tabs.query({ 48 | active: true, 49 | currentWindow: true, 50 | }); 51 | await getAndProcessMessages(activeTab, {}); 52 | } 53 | } 54 | 55 | function onlyWhitespace(str: string) { 56 | return str.trim().length === 0; 57 | } 58 | 59 | function renderString(inputString: string, context: { [key: string]: any }) { 60 | // Replace all occurrences of "{{x}}" in a string. 61 | // Take the new value from the "context" argument. 62 | // Leave the string unmodified if the new value isn't in the "context". 63 | 64 | // Don't use a template engine like nunchucks: 65 | // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy#valid_examples 66 | 67 | const re = /{{.*?}}/g; 68 | const matches = inputString.match(re); 69 | if (!matches) { 70 | return inputString; 71 | } 72 | 73 | let renderedString = inputString; 74 | for (const match of matches) { 75 | const trimmedMatch = match.slice(2, -2).trim(); 76 | if (!(trimmedMatch in context)) { 77 | // Don't replace if there is no matching value. 78 | // It would result in an "undefined" string. 79 | continue; 80 | } 81 | renderedString = renderedString.replace(match, context[trimmedMatch]); 82 | } 83 | return renderedString; 84 | } 85 | 86 | ////////////////////////////////////////////////// 87 | // Register content script for selections 88 | ////////////////////////////////////////////////// 89 | 90 | browser.scripting.messageDisplay.registerScripts([ 91 | { 92 | id: "selectionHandler", 93 | js: ["dist/selectionHandler.js"], 94 | }, 95 | ]); 96 | 97 | async function getSelection(tab: { id: number }, retry: boolean = true) { 98 | // Abort, if the tab is not displaying a message. 99 | let message = await browser.messageDisplay.getDisplayedMessage(tab.id); 100 | if (!message) { 101 | return ""; 102 | } 103 | 104 | try { 105 | // Await the call here, so we can catch connection errors and retry. 106 | return await browser.tabs.sendMessage(tab.id, { 107 | action: "getSelection", 108 | }); 109 | } catch {} 110 | 111 | if (retry) { 112 | // Script was not loaded yet, which could happen if the add-on was loaded 113 | // while the message was already open. 114 | await messenger.scripting.executeScript({ 115 | target: { tabId: tab.id }, 116 | files: ["dist/selectionHandler.js"], 117 | }); 118 | // We only retry once. 119 | return getSelection(tab, false); 120 | } 121 | return ""; 122 | } 123 | 124 | ////////////////////////////////////////////////// 125 | // Main export function 126 | ////////////////////////////////////////////////// 127 | 128 | async function getAndProcessMessages(tab: { id: number }, info: any) { 129 | // Called after button is clicked or hotkey is pressed. 130 | 131 | let success = true; 132 | let notificationIcon = "../images/logo_96_red.png"; 133 | let notificationTitle = "Joplin export failed"; 134 | let notificationMessage; 135 | 136 | // Check for Joplin API token. If it isn't present, we can skip everything else. 137 | const apiToken = await getSetting("joplinToken"); 138 | if (!apiToken) { 139 | notificationMessage = "API token missing."; 140 | success = false; 141 | } else { 142 | const messages = await getMessages(tab.id); 143 | 144 | // Process the mails and check for success. 145 | const results = await Promise.all( 146 | messages.map((mailHeader: any) => processMail(mailHeader, tab)) 147 | ); 148 | for (const error of results) { 149 | if (error) { 150 | console.error(`[Joplin Export] ${error}`); 151 | success = false; 152 | } 153 | } 154 | 155 | // Prepare the notification text. 156 | if (success) { 157 | notificationIcon = "../images/logo_96_blue.png"; 158 | notificationTitle = "Joplin export succeeded"; 159 | notificationMessage = 160 | results.length == 1 161 | ? "Exported one email." 162 | : `Exported ${results.length} emails.`; 163 | } else { 164 | notificationMessage = "Please check the developer console."; 165 | } 166 | } 167 | 168 | // Emit the notification if configured. 169 | const showNotifications = await getSetting("joplinShowNotifications"); 170 | if ( 171 | (success && ["always", "onSuccess"].includes(showNotifications)) || 172 | (!success && ["always", "onFailure"].includes(showNotifications)) 173 | ) { 174 | browser.notifications.create({ 175 | type: "basic", 176 | iconUrl: notificationIcon, 177 | title: notificationTitle, 178 | message: notificationMessage, 179 | }); 180 | } 181 | } 182 | 183 | async function getSelectedMessagesUnpaginated(tabId: number) { 184 | let page = await browser.mailTabs.getSelectedMessages(tabId); 185 | let messages = page.messages; 186 | 187 | while (page.id) { 188 | page = await messenger.messages.continueList(page.id); 189 | messages.push(...page.messages); 190 | } 191 | return messages; 192 | } 193 | 194 | async function getMessages(tabId: number) { 195 | const tab = await browser.tabs.get(tabId); 196 | let messages; 197 | switch (tab.type) { 198 | case "mail": 199 | messages = await getSelectedMessagesUnpaginated(tabId); 200 | break; 201 | case "messageDisplay": 202 | messages = await browser.messageDisplay.getDisplayedMessages(tabId); 203 | break; 204 | default: 205 | console.debug(`Unsupported tab type ${tab.type}.`); 206 | messages = []; 207 | } 208 | 209 | const logMessage = `[Joplin Export] Got ${messages.length} emails at tab ${tabId}.`; 210 | if (messages.length > 0) { 211 | console.debug(logMessage); 212 | } else { 213 | console.warn(logMessage); 214 | } 215 | 216 | return messages; 217 | } 218 | 219 | async function processMail(mailHeader: any, tab: { id: number }) { 220 | ////////////////////////////////////////////////// 221 | // Mail content 222 | ////////////////////////////////////////////////// 223 | 224 | // https://webextension-api.thunderbird.net/en/latest/messages.html#messages-messageheader 225 | if (!mailHeader) { 226 | return "Mail header is empty"; 227 | } 228 | 229 | // Technically it's possible to export a note without specifying a parent notebook. 230 | // However, it's rather annoying for the user. 231 | const parentId = await getSetting("joplinNoteParentFolder"); 232 | if (!parentId) { 233 | return `Invalid destination notebook: ${parentId}.`; 234 | } 235 | 236 | // Add a note with the email content 237 | // Customization 238 | const regexStringSubject = (await getSetting("joplinSubjectTrimRegex")) || ""; 239 | const regexStringAuthor = (await getSetting("joplinAuthorTrimRegex")) || ""; 240 | const dateFormat = (await getSetting("joplinDateFormat")) || ""; 241 | const trimmedSubject = 242 | regexStringSubject === "" 243 | ? mailHeader.subject 244 | : mailHeader.subject.replace(new RegExp(regexStringSubject), ""); 245 | const trimmedAuthor = 246 | regexStringAuthor === "" 247 | ? mailHeader.author 248 | : mailHeader.author.replace(new RegExp(regexStringAuthor), ""); 249 | const formattedDate = 250 | dateFormat === "" 251 | ? mailHeader.date 252 | : DateTime.fromJSDate(mailHeader.date).toFormat(dateFormat); 253 | const renderingContext = { 254 | ...mailHeader, 255 | subject: trimmedSubject, 256 | author: trimmedAuthor, 257 | date: formattedDate, 258 | }; 259 | 260 | // Title 261 | const titleRendered = renderString( 262 | (await getSetting("joplinNoteTitleTemplate")) || "", 263 | renderingContext 264 | ); 265 | 266 | const data: { 267 | title: string; 268 | parent_id: string; 269 | is_todo: number; 270 | author: string; 271 | user_created_time: number; 272 | body?: string; 273 | body_html?: string; 274 | } = { 275 | title: titleRendered, 276 | parent_id: parentId, 277 | is_todo: Number(await getSetting("joplinExportAsTodo")), 278 | author: mailHeader.author, 279 | user_created_time: mailHeader.date ? mailHeader.date.getTime() : 0, 280 | }; 281 | 282 | // Body 283 | type ContentType = "text/html" | "text/plain"; 284 | type Mail = { body: string; contentType: ContentType; parts: Array }; 285 | 286 | function getMailContent(mail: Mail, contentType: ContentType, content = "") { 287 | if (!mail) { 288 | return content; 289 | } 290 | if (mail.body && mail.contentType === contentType) { 291 | content += mail.body; 292 | } 293 | if (mail.parts) { 294 | for (const part of mail.parts) { 295 | content = getMailContent(part, contentType, content); 296 | } 297 | } 298 | return content; 299 | } 300 | 301 | // If there is selected text, prefer it over the full email. 302 | const selectedText = await getSelection(tab); 303 | if (onlyWhitespace(selectedText)) { 304 | const mailObject = await browser.messages.getFull(mailHeader.id); 305 | 306 | // text/html and text/plain seem to be the only used MIME types for the body. 307 | const mailBodyHtml = getMailContent(mailObject, "text/html"); 308 | const mailBodyPlain = getMailContent(mailObject, "text/plain"); 309 | if (!mailBodyHtml && !mailBodyPlain) { 310 | return "Mail body is empty"; 311 | } 312 | 313 | // If the preferred content type doesn't contain data, fall back to the other content type. 314 | const contentType = await getSetting("joplinNoteFormat"); 315 | if ((contentType === "text/html" && mailBodyHtml) || !mailBodyPlain) { 316 | console.log("[Joplin Export] Sending complete email in HTML format."); 317 | data["body_html"] = mailBodyHtml; 318 | } 319 | if ((contentType === "text/plain" && mailBodyPlain) || !mailBodyHtml) { 320 | console.log("[Joplin Export] Sending complete email in plain format."); 321 | data["body"] = mailBodyPlain; 322 | } 323 | } else { 324 | console.log("[Joplin Export] Sending selection in plain format."); 325 | data["body"] = selectedText; 326 | } 327 | 328 | // https://javascript.info/fetch 329 | let url = await generateUrl("notes", ["fields=id,body"]); 330 | let response = await fetch(url, { 331 | method: "POST", 332 | headers: { "Content-Type": "application/json" }, 333 | body: JSON.stringify(data), 334 | }); 335 | if (!response.ok) { 336 | return `Failed to create note: ${await response.text()}`; 337 | } 338 | let noteInfo = await response.json(); 339 | 340 | // Add user defined header info. 341 | // Do it only here, because we don't need any plain/html switching. 342 | // Disadvantage is the extra request. 343 | const renderTemplate = (await getSetting("joplinNoteHeaderTemplate")) || ""; 344 | if (renderTemplate) { 345 | const headerInfo = renderString(renderTemplate, renderingContext); 346 | url = await generateUrl(`notes/${noteInfo["id"]}`, ["fields=id,body"]); 347 | response = await fetch(url, { 348 | method: "PUT", 349 | headers: { "Content-Type": "application/json" }, 350 | body: JSON.stringify({ body: headerInfo + noteInfo["body"] }), 351 | }); 352 | if (!response.ok) { 353 | return `Failed to add header info to note: ${await response.text()}`; 354 | } 355 | noteInfo = await response.json(); 356 | } 357 | 358 | ////////////////////////////////////////////////// 359 | // Tags 360 | ////////////////////////////////////////////////// 361 | 362 | // User specified tags are stored in a comma separated string. 363 | const userTagsString = await getSetting("joplinNoteTags"); 364 | let tags = userTagsString ? userTagsString.split(",") : []; 365 | 366 | const includeMailTags = await getSetting("joplinNoteTagsFromEmail"); 367 | if (includeMailTags) { 368 | // Find each tag key in the mapping and return the corresponding, human readable value. 369 | const tagMapping = await browser.messages.listTags(); 370 | const mailTags = mailHeader.tags.map((tagKey: string) => { 371 | return tagMapping.find((mapping: any) => mapping.key === tagKey).tag; 372 | }); 373 | 374 | tags = tags.concat(mailTags); 375 | } 376 | 377 | for (const tag of tags) { 378 | // Strip spaces from tags, since they get stripped inside Joplin anyway. See: 379 | // https://discourse.joplinapp.org/t/joplin-export-export-emails-from-thunderbird-to-joplin/24792/26 380 | const strippedTag = tag.trim(); 381 | 382 | // Check whether tag exists already 383 | url = await generateUrl("search", [`query=${strippedTag}`, "type=tag"]); 384 | response = await fetch(url); 385 | if (!response.ok) { 386 | console.warn( 387 | `[Joplin Export] Search for tag failed: ${await response.text()}` 388 | ); 389 | continue; 390 | } 391 | const searchResult = await response.json(); 392 | const matchingTags = searchResult["items"]; 393 | 394 | let tagId; 395 | if (matchingTags.length === 0) { 396 | // create new tag 397 | url = await generateUrl("tags"); 398 | response = await fetch(url, { 399 | method: "POST", 400 | headers: { "Content-Type": "application/json" }, 401 | body: JSON.stringify({ title: strippedTag }), 402 | }); 403 | if (!response.ok) { 404 | console.warn( 405 | `[Joplin Export] Failed to create tag: ${await response.text()}` 406 | ); 407 | continue; 408 | } 409 | const tagInfo = await response.json(); 410 | tagId = tagInfo["id"]; 411 | } else if (matchingTags.length === 1) { 412 | // use id of the existing tag 413 | tagId = matchingTags[0]["id"]; 414 | } else { 415 | const matchingTagsString = matchingTags 416 | .map((e: { id: string; title: string }) => e.title) 417 | .join(", "); 418 | console.warn( 419 | `[Joplin Export] Too many matching tags for "${strippedTag}": ${matchingTagsString}` 420 | ); 421 | continue; 422 | } 423 | 424 | // attach tag to note 425 | url = await generateUrl(`tags/${tagId}/notes`); 426 | response = await fetch(url, { 427 | method: "POST", 428 | headers: { "Content-Type": "application/json" }, 429 | body: JSON.stringify({ id: noteInfo["id"] }), 430 | }); 431 | if (!response.ok) { 432 | console.warn( 433 | `[Joplin Export] Failed to attach tag to note: ${await response.text()}` 434 | ); 435 | continue; // not necessary, but added in case of a future refactoring 436 | } 437 | } 438 | 439 | ////////////////////////////////////////////////// 440 | // Attachments 441 | ////////////////////////////////////////////////// 442 | 443 | const howToHandleAttachments = await getSetting("joplinAttachments"); 444 | if (howToHandleAttachments === "ignore") { 445 | return null; 446 | } 447 | 448 | // https://webextension-api.thunderbird.net/en/latest/messages.html#getattachmentfile-messageid-partname 449 | const attachments = await browser.messages.listAttachments(mailHeader.id); 450 | if (attachments && attachments.length != 0) { 451 | let attachmentString = "\n\n**Attachments**: "; 452 | for (const attachment of attachments) { 453 | const attachmentFile = await browser.messages.getAttachmentFile( 454 | mailHeader.id, 455 | attachment.partName 456 | ); 457 | 458 | const formData = new FormData(); 459 | formData.append("data", attachmentFile); 460 | formData.append("props", JSON.stringify({ title: attachment.name })); 461 | // https://joplinapp.org/api/references/rest_api/#post-resources 462 | url = await generateUrl("resources"); 463 | response = await fetch(url, { 464 | method: "POST", 465 | body: formData, 466 | }); 467 | if (!response.ok) { 468 | console.warn( 469 | `[Joplin Export] Failed to create resource: ${await response.text()}` 470 | ); 471 | continue; 472 | } 473 | const resourceInfo = await response.json(); 474 | attachmentString += `\n[${attachment.name}](:/${resourceInfo["id"]})`; 475 | } 476 | 477 | // Always operate on body, even if previously used body_html. 478 | url = await generateUrl(`notes/${noteInfo["id"]}`); 479 | response = await fetch(url, { 480 | method: "PUT", 481 | headers: { "Content-Type": "application/json" }, 482 | body: JSON.stringify({ body: noteInfo["body"] + attachmentString }), 483 | }); 484 | if (!response.ok) { 485 | console.warn( 486 | `[Joplin Export] Failed to attach resource to note: ${await response.text()}` 487 | ); 488 | } 489 | } 490 | return null; 491 | } 492 | 493 | // Three ways to export notes: by menu button, hotkey or context menu. 494 | browser.browserAction.onClicked.addListener(handleMenuButton); 495 | messenger.commands.onCommand.addListener(handleHotkey); 496 | browser.menus.onClicked.addListener(handleContextMenu); 497 | 498 | // Only needed for testing. 499 | export { 500 | getAndProcessMessages, 501 | handleContextMenu, 502 | handleHotkey, 503 | handleMenuButton, 504 | onlyWhitespace, 505 | processMail, 506 | renderString, 507 | }; 508 | -------------------------------------------------------------------------------- /src/common.ts: -------------------------------------------------------------------------------- 1 | // TODO: Why isn't this working even when the "dom" lib is enabled in tsconfig? 2 | declare const browser: any; 3 | 4 | export async function generateUrl(path: string, query: Array = []) { 5 | // Create a valid URL to access the Joplin API. 6 | // I. e. add base URL and token. 7 | const { joplinScheme, joplinHost, joplinPort, joplinToken } = 8 | await browser.storage.local.get([ 9 | "joplinScheme", 10 | "joplinHost", 11 | "joplinPort", 12 | "joplinToken", 13 | ]); 14 | // Note: This modifies the original array, since it's passed by reference. 15 | query.push(`token=${joplinToken}`); 16 | return `${joplinScheme}://${joplinHost}:${joplinPort}/${path}?${query.join( 17 | "&" 18 | )}`; 19 | } 20 | 21 | export async function getSetting(name: string) { 22 | // Convenience wrapper to get a setting from local storage. 23 | // @ts-ignore 24 | return (await browser.storage.local.get(name))[name]; 25 | } 26 | -------------------------------------------------------------------------------- /src/options.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 86 | 87 | 88 | 89 | 90 |
91 | Joplin Webclipper Configuration 92 |

93 | 94 | 95 |

96 |

97 | 98 | 99 |

100 |

101 | 102 | 103 |

104 |

105 | 106 | 107 | 108 | 109 | 110 |

111 |

112 | 113 | 114 | 115 | 116 | 117 | 118 |

119 |

120 | 121 | 122 | 124 | 125 | 126 |

127 |
128 | 129 |
130 | Export 131 |

132 | 133 | 139 | 140 | 141 | 142 |

143 |
144 | 145 |
146 | Note 147 |

148 | 149 | 150 | 152 | 153 | 154 |

155 |

156 | 157 | 158 | 160 | 161 | 162 |

163 |

164 | 165 | 166 | 167 | 168 | 169 |

170 |

171 | 172 | 173 | 175 | 176 | 177 |

178 |

179 | 180 | 181 | 183 | 184 | 185 |

186 |

187 | 188 | 194 | 195 | 196 | 197 | 198 |

199 |

200 | 201 | 205 | 206 | 207 | 208 |

209 |

210 | 211 | 212 | Export as TODO 213 |

214 |

215 | 216 | 217 | 218 | 219 | 220 |

221 |

222 | 223 | 224 | Include Tags from Email 225 |

226 |

227 | 228 | 232 |

233 |
234 | 235 |

236 | 237 | 238 | 239 | -------------------------------------------------------------------------------- /src/options.ts: -------------------------------------------------------------------------------- 1 | import { generateUrl, getSetting } from "./common"; 2 | 3 | declare const browser: any; 4 | declare const btnSave: HTMLButtonElement; 5 | declare const btnRefreshNotebooks: HTMLButtonElement; 6 | 7 | const default_map: { [key: string]: string | number | boolean } = { 8 | joplinScheme: "http", 9 | joplinHost: "127.0.0.1", 10 | joplinPort: 41184, 11 | joplinToken: "", 12 | joplinShowNotifications: "onFailure", 13 | joplinSubjectTrimRegex: "", 14 | joplinAuthorTrimRegex: "", 15 | joplinDateFormat: "D T", 16 | joplinNoteTitleTemplate: "{{subject}} from {{author}}", 17 | joplinNoteHeaderTemplate: "", 18 | joplinNoteFormat: "text/html", 19 | joplinExportAsTodo: false, 20 | joplinAttachments: "attach", 21 | joplinNoteTags: "email", 22 | joplinNoteTagsFromEmail: true, 23 | }; 24 | 25 | async function checkJoplinConnection() { 26 | let url = await generateUrl("ping"); 27 | let response; 28 | try { 29 | response = await fetch(url); 30 | } catch (e) { 31 | return { 32 | working: false, 33 | message: 34 | "Pinging Joplin failed. Please check that Joplin is running and the webclipper is enabled.", 35 | }; 36 | } 37 | 38 | const response_text = await response.text(); 39 | if (response_text !== "JoplinClipperServer") { 40 | return { 41 | working: false, 42 | message: `Unexpected ping response "${response_text}". Please check that addon and Joplin versions are matching.`, 43 | }; 44 | } 45 | 46 | // Ping doesn't care for the token, so we need to check another endpoint. 47 | url = await generateUrl("folders"); 48 | response = await fetch(url); 49 | if (!response.ok) { 50 | return { 51 | working: false, 52 | message: `Unexpected http status "${response.status}". Please check that the configuration is correct.`, 53 | }; 54 | } 55 | 56 | return { working: true, message: "" }; 57 | } 58 | 59 | async function updateConnectionStatus() { 60 | const connectionStatus = document.getElementById( 61 | "joplinStatus" 62 | ) as HTMLInputElement; 63 | const { working, message } = await checkJoplinConnection(); 64 | if (working) { 65 | connectionStatus.style.color = "blue"; 66 | connectionStatus.value = "working"; 67 | } else { 68 | connectionStatus.style.color = "red"; 69 | connectionStatus.value = message; 70 | } 71 | 72 | return working; 73 | } 74 | 75 | async function displayUrl() { 76 | (document.getElementById("joplinUrl") as HTMLInputElement).value = 77 | (document.getElementById("joplinScheme") as HTMLInputElement).value + 78 | "://" + 79 | (document.getElementById("joplinHost") as HTMLInputElement).value + 80 | ":" + 81 | (document.getElementById("joplinPort") as HTMLInputElement).value; 82 | } 83 | 84 | async function savePrefs() { 85 | for (const setting in default_map) { 86 | const element = document.getElementById(setting) as HTMLInputElement; 87 | let value; 88 | if (element.type === "checkbox") { 89 | value = element.checked; 90 | } else { 91 | value = element.value; 92 | } 93 | browser.storage.local.set({ [setting]: value }); 94 | } 95 | 96 | await displayUrl(); 97 | 98 | // The parent notebook can only be set if the connection is functional! 99 | const working = await updateConnectionStatus(); 100 | if (!working) { 101 | return; 102 | } 103 | 104 | await browser.storage.local.set({ 105 | joplinNoteParentFolder: ( 106 | document.getElementById("joplinNoteParentFolder") as HTMLInputElement 107 | ).value, 108 | }); 109 | } 110 | 111 | async function refreshNotebooks() { 112 | // https://stackoverflow.com/a/8674667/7410886 113 | type NotebookTree = Array<{ 114 | id: string; 115 | title: string; 116 | children: NotebookTree; 117 | }>; 118 | function fillNotebookSelect( 119 | tree: NotebookTree, 120 | select: HTMLSelectElement, 121 | indentationLevel = 0 122 | ) { 123 | for (const notebook of tree) { 124 | const opt = document.createElement("option"); 125 | opt.value = notebook.id; 126 | // Spaces: https://stackoverflow.com/a/17855282/7410886 127 | opt.text = "\xA0\xA0".repeat(indentationLevel) + " " + notebook.title; 128 | select.appendChild(opt); 129 | 130 | if (notebook.children) { 131 | fillNotebookSelect(notebook.children, select, (indentationLevel += 1)); 132 | } 133 | } 134 | } 135 | const url = await generateUrl("folders", ["as_tree=1"]); 136 | const response = await fetch(url); 137 | if (!response.ok) { 138 | return; 139 | } 140 | const notebookTree = await response.json(); 141 | const notebookSelect = document.getElementById( 142 | "joplinNoteParentFolder" 143 | ) as HTMLSelectElement; 144 | // Clear all options before inserting new ones. 145 | while (notebookSelect.firstChild) { 146 | notebookSelect.firstChild.remove(); 147 | } 148 | const opt = document.createElement("option"); 149 | opt.value = ""; 150 | opt.text = "< Select Notebook >"; 151 | notebookSelect.appendChild(opt); 152 | fillNotebookSelect(notebookTree, notebookSelect); 153 | 154 | // Set notebook if possible 155 | const parentFolderId = await getSetting("joplinNoteParentFolder"); 156 | if (parentFolderId) { 157 | notebookSelect.value = parentFolderId; 158 | } 159 | } 160 | 161 | async function initOptions() { 162 | btnSave.addEventListener("click", savePrefs); 163 | btnRefreshNotebooks.addEventListener("click", refreshNotebooks); 164 | 165 | // Try to obtain the settings from local storage. If not possible, fall back to the defaults. 166 | for (const setting in default_map) { 167 | const currentValue = await getSetting(setting); 168 | // 'false' is a valid value. Only check for 'null' and 'undefined'. 169 | const newValue = currentValue != null ? currentValue : default_map[setting]; 170 | await browser.storage.local.set({ [setting]: newValue }); 171 | } 172 | 173 | // Set values of the UI 174 | for (const setting in default_map) { 175 | const element = document.getElementById(setting) as HTMLInputElement; 176 | const value = await getSetting(setting); 177 | if (element.type === "checkbox") { 178 | element.checked = value; 179 | } else { 180 | element.value = value; 181 | } 182 | } 183 | 184 | await displayUrl(); 185 | 186 | // The parent notebook can only be set if the connection is functional! 187 | const working = await updateConnectionStatus(); 188 | if (!working) { 189 | return; 190 | } 191 | 192 | await refreshNotebooks(); 193 | } 194 | 195 | document.addEventListener("DOMContentLoaded", initOptions, { once: true }); 196 | -------------------------------------------------------------------------------- /src/selectionHandler.js: -------------------------------------------------------------------------------- 1 | /* 2 | * This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this 4 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 5 | */ 6 | 7 | async function getSelection() { 8 | let selection = window.getSelection(); 9 | return selection.toString(); 10 | } 11 | 12 | messenger.runtime.onMessage.addListener((message, sender) => { 13 | switch (message.action) { 14 | case "getSelection": 15 | return getSelection(); 16 | } 17 | return false; 18 | }); 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | "lib": ["dom"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 22 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | 26 | /* Modules */ 27 | "module": "commonjs", /* Specify what module code is generated. */ 28 | // "rootDir": "./", /* Specify the root folder within your source files. */ 29 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 30 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 31 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 32 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 33 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 34 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 35 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 36 | // "resolveJsonModule": true, /* Enable importing .json files */ 37 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 38 | 39 | /* JavaScript Support */ 40 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ 41 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 42 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 43 | 44 | /* Emit */ 45 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 46 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 47 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 48 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 49 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 50 | "outDir": "./dist", /* Specify an output folder for all emitted files. */ 51 | // "removeComments": true, /* Disable emitting comments. */ 52 | // "noEmit": true, /* Disable emitting files from a compilation. */ 53 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 54 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 55 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 56 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 59 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 60 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 61 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 62 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 63 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 64 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 65 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 66 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 67 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 68 | 69 | /* Interop Constraints */ 70 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 71 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 72 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ 73 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 74 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 75 | 76 | /* Type Checking */ 77 | "strict": true, /* Enable all strict type-checking options. */ 78 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ 79 | // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ 80 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 81 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 82 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 83 | // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ 84 | // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 85 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 86 | // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ 87 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 88 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 89 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 90 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 91 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 92 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 93 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 94 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 95 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 96 | 97 | /* Completeness */ 98 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 99 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 100 | }, 101 | "include": [ 102 | "./src/*.ts" 103 | ] 104 | } 105 | --------------------------------------------------------------------------------