@twin.org/mailbox-connector-imap 0.9.3-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +29 -0
  3. package/dist/es/configSchema/imapEmailConnectorConfigSchema.js +51 -0
  4. package/dist/es/configSchema/imapEmailConnectorConfigSchema.js.map +1 -0
  5. package/dist/es/imapEmailConnector.js +236 -0
  6. package/dist/es/imapEmailConnector.js.map +1 -0
  7. package/dist/es/index.js +9 -0
  8. package/dist/es/index.js.map +1 -0
  9. package/dist/es/models/IImapEmailConnectorConfig.js +4 -0
  10. package/dist/es/models/IImapEmailConnectorConfig.js.map +1 -0
  11. package/dist/es/models/IImapEmailConnectorConstructorOptions.js +2 -0
  12. package/dist/es/models/IImapEmailConnectorConstructorOptions.js.map +1 -0
  13. package/dist/es/models/IImapEmailConnectorFolderState.js +4 -0
  14. package/dist/es/models/IImapEmailConnectorFolderState.js.map +1 -0
  15. package/dist/es/models/IImapEmailConnectorState.js +2 -0
  16. package/dist/es/models/IImapEmailConnectorState.js.map +1 -0
  17. package/dist/types/configSchema/imapEmailConnectorConfigSchema.d.ts +5 -0
  18. package/dist/types/imapEmailConnector.d.ts +40 -0
  19. package/dist/types/index.d.ts +6 -0
  20. package/dist/types/models/IImapEmailConnectorConfig.d.ts +44 -0
  21. package/dist/types/models/IImapEmailConnectorConstructorOptions.d.ts +19 -0
  22. package/dist/types/models/IImapEmailConnectorFolderState.d.ts +16 -0
  23. package/dist/types/models/IImapEmailConnectorState.d.ts +12 -0
  24. package/docs/changelog.md +17 -0
  25. package/docs/examples.md +98 -0
  26. package/docs/reference/classes/ImapEmailConnector.md +123 -0
  27. package/docs/reference/index.md +16 -0
  28. package/docs/reference/interfaces/IImapEmailConnectorConfig.md +94 -0
  29. package/docs/reference/interfaces/IImapEmailConnectorConstructorOptions.md +33 -0
  30. package/docs/reference/interfaces/IImapEmailConnectorFolderState.md +22 -0
  31. package/docs/reference/interfaces/IImapEmailConnectorState.md +15 -0
  32. package/docs/reference/variables/ImapEmailConnectorConfigSchema.md +5 -0
  33. package/locales/en.json +21 -0
  34. package/package.json +56 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 IOTA Stiftung.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # TWIN Mailbox Connector IMAP
2
+
3
+ This package implements an IMAP connector for email mailbox ingestion.
4
+
5
+ ## Installation
6
+
7
+ ```shell
8
+ npm install @twin.org/mailbox-connector-imap
9
+ ```
10
+
11
+ ## Docker
12
+
13
+ To perform testing of this component it may be necessary to launch a local instance to communicate with.
14
+
15
+ ```shell
16
+ docker run -p 53025:3025 -p 58027:8080 -p 53143:3143 --name twin-messaging-imap -d -e GREENMAIL_OPTS="-Dgreenmail.setup.test.all -Dgreenmail.hostname=0.0.0.0 -Dgreenmail.users=test:test@localhost -Dgreenmail.verbose" greenmail/standalone:2.1.3
17
+ ```
18
+
19
+ ## Examples
20
+
21
+ Usage of the APIs is shown in the examples [docs/examples.md](docs/examples.md)
22
+
23
+ ## Reference
24
+
25
+ Detailed reference documentation for the API can be found in [docs/reference/index.md](docs/reference/index.md)
26
+
27
+ ## Changelog
28
+
29
+ The changes between each version can be found in [docs/changelog.md](docs/changelog.md)
@@ -0,0 +1,51 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ import { EntitySchemaPropertyType } from "@twin.org/entity";
4
+ /**
5
+ * The configuration field schema for IMAP connectors.
6
+ */
7
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8
+ export const ImapEmailConnectorConfigSchema = [
9
+ {
10
+ labelKey: "imapEmailConnectorConfigSchema.host",
11
+ propertyKey: "host",
12
+ type: EntitySchemaPropertyType.String
13
+ },
14
+ {
15
+ labelKey: "imapEmailConnectorConfigSchema.port",
16
+ propertyKey: "port",
17
+ type: EntitySchemaPropertyType.Integer,
18
+ defaultValue: 993
19
+ },
20
+ {
21
+ labelKey: "imapEmailConnectorConfigSchema.secure",
22
+ propertyKey: "secure",
23
+ type: EntitySchemaPropertyType.Boolean,
24
+ defaultValue: true
25
+ },
26
+ {
27
+ labelKey: "imapEmailConnectorConfigSchema.username",
28
+ propertyKey: "username",
29
+ type: EntitySchemaPropertyType.String
30
+ },
31
+ {
32
+ labelKey: "imapEmailConnectorConfigSchema.password",
33
+ propertyKey: "password",
34
+ type: EntitySchemaPropertyType.String,
35
+ isSecure: true
36
+ },
37
+ {
38
+ labelKey: "imapEmailConnectorConfigSchema.folders",
39
+ propertyKey: "folders",
40
+ type: EntitySchemaPropertyType.Array,
41
+ itemType: EntitySchemaPropertyType.String,
42
+ defaultValue: ["INBOX"]
43
+ },
44
+ {
45
+ labelKey: "imapEmailConnectorConfigSchema.pollingIntervalMinutes",
46
+ propertyKey: "pollingIntervalMinutes",
47
+ type: EntitySchemaPropertyType.Integer,
48
+ defaultValue: 2
49
+ }
50
+ ];
51
+ //# sourceMappingURL=imapEmailConnectorConfigSchema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imapEmailConnectorConfigSchema.js","sourceRoot":"","sources":["../../../src/configSchema/imapEmailConnectorConfigSchema.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAG5D;;GAEG;AACH,gEAAgE;AAChE,MAAM,CAAC,MAAM,8BAA8B,GAA0B;IACpE;QACC,QAAQ,EAAE,qCAAqC;QAC/C,WAAW,EAAE,MAAM;QACnB,IAAI,EAAE,wBAAwB,CAAC,MAAM;KACrC;IACD;QACC,QAAQ,EAAE,qCAAqC;QAC/C,WAAW,EAAE,MAAM;QACnB,IAAI,EAAE,wBAAwB,CAAC,OAAO;QACtC,YAAY,EAAE,GAAG;KACjB;IACD;QACC,QAAQ,EAAE,uCAAuC;QACjD,WAAW,EAAE,QAAQ;QACrB,IAAI,EAAE,wBAAwB,CAAC,OAAO;QACtC,YAAY,EAAE,IAAI;KAClB;IACD;QACC,QAAQ,EAAE,yCAAyC;QACnD,WAAW,EAAE,UAAU;QACvB,IAAI,EAAE,wBAAwB,CAAC,MAAM;KACrC;IACD;QACC,QAAQ,EAAE,yCAAyC;QACnD,WAAW,EAAE,UAAU;QACvB,IAAI,EAAE,wBAAwB,CAAC,MAAM;QACrC,QAAQ,EAAE,IAAI;KACd;IACD;QACC,QAAQ,EAAE,wCAAwC;QAClD,WAAW,EAAE,SAAS;QACtB,IAAI,EAAE,wBAAwB,CAAC,KAAK;QACpC,QAAQ,EAAE,wBAAwB,CAAC,MAAM;QACzC,YAAY,EAAE,CAAC,OAAO,CAAC;KACvB;IACD;QACC,QAAQ,EAAE,uDAAuD;QACjE,WAAW,EAAE,wBAAwB;QACrC,IAAI,EAAE,wBAAwB,CAAC,OAAO;QACtC,YAAY,EAAE,CAAC;KACf;CACD,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { EntitySchemaPropertyType } from \"@twin.org/entity\";\nimport type { IMailboxConfigField } from \"@twin.org/mailbox-models\";\n\n/**\n * The configuration field schema for IMAP connectors.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const ImapEmailConnectorConfigSchema: IMailboxConfigField[] = [\n\t{\n\t\tlabelKey: \"imapEmailConnectorConfigSchema.host\",\n\t\tpropertyKey: \"host\",\n\t\ttype: EntitySchemaPropertyType.String\n\t},\n\t{\n\t\tlabelKey: \"imapEmailConnectorConfigSchema.port\",\n\t\tpropertyKey: \"port\",\n\t\ttype: EntitySchemaPropertyType.Integer,\n\t\tdefaultValue: 993\n\t},\n\t{\n\t\tlabelKey: \"imapEmailConnectorConfigSchema.secure\",\n\t\tpropertyKey: \"secure\",\n\t\ttype: EntitySchemaPropertyType.Boolean,\n\t\tdefaultValue: true\n\t},\n\t{\n\t\tlabelKey: \"imapEmailConnectorConfigSchema.username\",\n\t\tpropertyKey: \"username\",\n\t\ttype: EntitySchemaPropertyType.String\n\t},\n\t{\n\t\tlabelKey: \"imapEmailConnectorConfigSchema.password\",\n\t\tpropertyKey: \"password\",\n\t\ttype: EntitySchemaPropertyType.String,\n\t\tisSecure: true\n\t},\n\t{\n\t\tlabelKey: \"imapEmailConnectorConfigSchema.folders\",\n\t\tpropertyKey: \"folders\",\n\t\ttype: EntitySchemaPropertyType.Array,\n\t\titemType: EntitySchemaPropertyType.String,\n\t\tdefaultValue: [\"INBOX\"]\n\t},\n\t{\n\t\tlabelKey: \"imapEmailConnectorConfigSchema.pollingIntervalMinutes\",\n\t\tpropertyKey: \"pollingIntervalMinutes\",\n\t\ttype: EntitySchemaPropertyType.Integer,\n\t\tdefaultValue: 2\n\t}\n];\n"]}
@@ -0,0 +1,236 @@
1
+ import { BaseError, ComponentFactory, GeneralError, Guards, Is, Mutex } from "@twin.org/core";
2
+ import { MailHelper } from "@twin.org/mailbox-models";
3
+ import { ImapFlow } from "imapflow";
4
+ /**
5
+ * IMAP email protocol connector. Polls configured folders for new messages using imapflow.
6
+ */
7
+ export class ImapEmailConnector {
8
+ /**
9
+ * The class name.
10
+ */
11
+ static CLASS_NAME = "ImapEmailConnector";
12
+ /**
13
+ * The protocol namespace identifier.
14
+ */
15
+ static NAMESPACE = "imap";
16
+ /**
17
+ * The logging component.
18
+ * @internal
19
+ */
20
+ _logging;
21
+ /**
22
+ * The task scheduler component used for polling.
23
+ * @internal
24
+ */
25
+ _taskScheduler;
26
+ /**
27
+ * The resolved configuration for this connector instance.
28
+ * @internal
29
+ */
30
+ _config;
31
+ /**
32
+ * The identifier of the currently active instance being polled.
33
+ * @internal
34
+ */
35
+ _instanceId;
36
+ /**
37
+ * Set when retrieve has been called and cleared when retrieveStop is called.
38
+ * @internal
39
+ */
40
+ _retrieving;
41
+ /**
42
+ * The last successfully persisted connector state, updated after each successful callback.
43
+ * @internal
44
+ */
45
+ _state;
46
+ /**
47
+ * Create a new instance of ImapEmailConnector.
48
+ * @param options The options for the connector.
49
+ */
50
+ constructor(options) {
51
+ Guards.object(ImapEmailConnector.CLASS_NAME, "options", options);
52
+ Guards.object(ImapEmailConnector.CLASS_NAME, "options.config", options.config);
53
+ Guards.stringValue(ImapEmailConnector.CLASS_NAME, "options.config.host", options.config.host);
54
+ Guards.stringValue(ImapEmailConnector.CLASS_NAME, "options.config.username", options.config.username);
55
+ Guards.stringValue(ImapEmailConnector.CLASS_NAME, "options.config.password", options.config.password);
56
+ this._logging = ComponentFactory.getIfExists(options.loggingComponentType);
57
+ this._taskScheduler = ComponentFactory.get(options.taskSchedulerComponentType ?? "task-scheduler");
58
+ const secure = options.config.secure ?? true;
59
+ this._config = {
60
+ host: options.config.host,
61
+ port: options.config.port ?? (secure ? 993 : 143),
62
+ secure,
63
+ username: options.config.username,
64
+ password: options.config.password,
65
+ folders: options.config.folders ?? ["INBOX"],
66
+ pollingIntervalMinutes: Math.max(1, options.config.pollingIntervalMinutes ?? 2),
67
+ mutexTimeoutMs: options.config.mutexTimeoutMs
68
+ };
69
+ this._retrieving = false;
70
+ }
71
+ /**
72
+ * Get the class name.
73
+ * @returns The class name.
74
+ */
75
+ className() {
76
+ return ImapEmailConnector.CLASS_NAME;
77
+ }
78
+ /**
79
+ * Start the internal polling loop for the given instance.
80
+ * @param instanceId The identifier of the mailbox instance being polled.
81
+ * @param state The current connector state for the instance.
82
+ * @param authCallback Callback invoked when authentication fails during a poll cycle.
83
+ * @param retrievalCallback Callback invoked with retrieved messages after each poll cycle.
84
+ * @returns A promise that resolves when the polling loop has been started.
85
+ */
86
+ async retrieve(instanceId, state, authCallback, retrievalCallback) {
87
+ await this.retrieveStop();
88
+ this._retrieving = true;
89
+ this._instanceId = instanceId;
90
+ this._state = state;
91
+ await this._taskScheduler.addTask(instanceId, [{ intervalMinutes: this._config.pollingIntervalMinutes }], async () => {
92
+ await this.poll(authCallback, retrievalCallback);
93
+ });
94
+ }
95
+ /**
96
+ * Stop the polling loop for this connector.
97
+ * @returns A promise that resolves when the polling loop has been stopped.
98
+ */
99
+ async retrieveStop() {
100
+ if (Is.stringValue(this._instanceId)) {
101
+ this._retrieving = false;
102
+ await this._taskScheduler.removeTask(this._instanceId);
103
+ this._instanceId = undefined;
104
+ this._state = undefined;
105
+ }
106
+ }
107
+ /**
108
+ * Poll each configured folder for new messages.
109
+ * @param authCallback Callback invoked when authentication fails.
110
+ * @param retrievalCallback Callback invoked with retrieved messages.
111
+ * @internal
112
+ */
113
+ async poll(authCallback, retrievalCallback) {
114
+ if (Is.empty(this._state) || !Is.stringValue(this._instanceId)) {
115
+ return;
116
+ }
117
+ // Capture the instance id and state for this poll cycle, retrieveStop can clear the
118
+ // instance fields while a poll is in progress and the mutex must still be released
119
+ // under the key it was locked with.
120
+ const instanceId = this._instanceId;
121
+ const state = this._state;
122
+ await Mutex.lock(instanceId, {
123
+ timeoutMs: this._config.mutexTimeoutMs,
124
+ throwOnTimeout: true
125
+ });
126
+ const client = new ImapFlow({
127
+ host: this._config.host,
128
+ port: this._config.port,
129
+ secure: this._config.secure,
130
+ auth: { user: this._config.username, pass: this._config.password },
131
+ logger: false
132
+ });
133
+ try {
134
+ await client.connect();
135
+ for (const folder of this._config.folders) {
136
+ const continued = await this.pollFolder(client, folder, retrievalCallback);
137
+ if (!continued) {
138
+ break;
139
+ }
140
+ }
141
+ }
142
+ catch (error) {
143
+ const pollError = new GeneralError(ImapEmailConnector.CLASS_NAME, "pollFailed", undefined, BaseError.fromError(error));
144
+ const rawError = Is.object(error)
145
+ ? error
146
+ : undefined;
147
+ const isAuthFailure = rawError?.authenticationFailed === true;
148
+ if (isAuthFailure) {
149
+ await authCallback(instanceId, state, true, undefined, pollError);
150
+ }
151
+ else {
152
+ await retrievalCallback(instanceId, undefined, state, pollError);
153
+ }
154
+ }
155
+ finally {
156
+ try {
157
+ await client.logout();
158
+ client.close();
159
+ }
160
+ catch {
161
+ // ignore, not much we can do if the connection is already closed
162
+ // but don't want to prevent the mutex from being unlocked in the finally block below
163
+ }
164
+ Mutex.unlock(instanceId);
165
+ }
166
+ }
167
+ /**
168
+ * Poll a single folder for messages with UIDs beyond the last seen UID.
169
+ * Each parsed message is forwarded to the retrieval callback; returning false aborts processing.
170
+ * @param client The connected ImapFlow client.
171
+ * @param folder The folder path to poll.
172
+ * @param retrievalCallback Callback invoked for each parsed email; return false to abort.
173
+ * @returns True if all messages were processed, false if processing was aborted.
174
+ * @internal
175
+ */
176
+ async pollFolder(client, folder, retrievalCallback) {
177
+ if (Is.empty(this._state) || !Is.stringValue(this._instanceId)) {
178
+ return true;
179
+ }
180
+ this._state.folders ??= {};
181
+ const folderState = this._state.folders[folder] ?? {};
182
+ this._state.folders[folder] = folderState;
183
+ const lock = await client.getMailboxLock(folder);
184
+ try {
185
+ if (!client.mailbox) {
186
+ return true;
187
+ }
188
+ const uidValidity = client.mailbox.uidValidity.toString();
189
+ if (folderState.uidValidity !== uidValidity) {
190
+ folderState.uidValidity = uidValidity;
191
+ folderState.lastUid = 0;
192
+ }
193
+ const lastUid = folderState.lastUid ?? 0;
194
+ const searchQuery = lastUid > 0 ? { uid: `${lastUid + 1}:*` } : { all: true };
195
+ const uids = await client.search(searchQuery, { uid: true });
196
+ if (uids !== false && Is.arrayValue(uids)) {
197
+ const msgStream = client.fetch(uids, { uid: true, source: true, flags: true }, { uid: true });
198
+ // Any early exit from this loop (return, break or throw) must terminate the
199
+ // fetch iterator, otherwise imapflow leaves the FETCH command pending and the
200
+ // LOGOUT queued behind it in poll() never resolves, so the mutex is never
201
+ // released. for await calls the iterator's return() on every exit path.
202
+ for await (const msg of msgStream) {
203
+ if (!this._retrieving) {
204
+ return false;
205
+ }
206
+ const currentLastUid = folderState.lastUid ?? 0;
207
+ if (Is.notEmpty(msg.uid) && msg.uid > currentLastUid) {
208
+ if (Is.notEmpty(msg.source)) {
209
+ const email = await MailHelper.parseEmail(msg.source.toString(), msg.flags ? [...msg.flags] : undefined);
210
+ if (Is.notEmpty(email)) {
211
+ await this._logging?.log({
212
+ level: "info",
213
+ source: ImapEmailConnector.CLASS_NAME,
214
+ ts: Date.now(),
215
+ message: "emailReceived",
216
+ data: { subject: email.subject }
217
+ });
218
+ folderState.lastUid = msg.uid;
219
+ const shouldContinue = await retrievalCallback(this._instanceId, email, this._state);
220
+ if (!shouldContinue) {
221
+ folderState.lastUid = currentLastUid;
222
+ return false;
223
+ }
224
+ }
225
+ }
226
+ }
227
+ }
228
+ }
229
+ }
230
+ finally {
231
+ lock.release();
232
+ }
233
+ return true;
234
+ }
235
+ }
236
+ //# sourceMappingURL=imapEmailConnector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imapEmailConnector.js","sourceRoot":"","sources":["../../src/imapEmailConnector.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAO9F,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAEtD,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAMpC;;GAEG;AACH,MAAM,OAAO,kBAAkB;IAC9B;;OAEG;IACI,MAAM,CAAU,UAAU,wBAAwC;IAEzE;;OAEG;IACI,MAAM,CAAU,SAAS,GAAW,MAAM,CAAC;IAElD;;;OAGG;IACc,QAAQ,CAAqB;IAE9C;;;OAGG;IACc,cAAc,CAA0B;IAEzD;;;OAGG;IACc,OAAO,CAM2B;IAEnD;;;OAGG;IACK,WAAW,CAAU;IAE7B;;;OAGG;IACK,WAAW,CAAU;IAE7B;;;OAGG;IACK,MAAM,CAA4B;IAE1C;;;OAGG;IACH,YAAY,OAA8C;QACzD,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,UAAU,aAAmB,OAAO,CAAC,CAAC;QACvE,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,UAAU,oBAA0B,OAAO,CAAC,MAAM,CA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AAG,CAAC,MAAM,CAAC,QAAQ,EAAE,EACrB,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CACtC,CAAC;4BACF,IAAI,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;gCACxB,MAAM,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC;oCACxB,KAAK,EAAE,MAAM;oCACb,MAAM,EAAE,kBAAkB,CAAC,UAAU;oCACrC,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE;oCACd,OAAO,EAAE,eAAe;oCACxB,IAAI,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE;iCAChC,CAAC,CAAC;gCACH,WAAW,CAAC,OAAO,GAAG,GAAG,CAAC,GAAG,CAAC;gCAC9B,MAAM,cAAc,GAAG,MAAM,iBAAiB,CAC7C,IAAI,CAAC,WAAW,EAChB,KAAK,EACL,IAAI,CAAC,MAAM,CACX,CAAC;gCACF,IAAI,CAAC,cAAc,EAAE,CAAC;oCACrB,WAAW,CAAC,OAAO,GAAG,cAAc,CAAC;oCACrC,OAAO,KAAK,CAAC;gCACd,CAAC;4BACF,CAAC;wBACF,CAAC;oBACF,CAAC;gBACF,CAAC;YACF,CAAC;QACF,CAAC;gBAAS,CAAC;YACV,IAAI,CAAC,OAAO,EAAE,CAAC;QAChB,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { ITaskSchedulerComponent } from \"@twin.org/background-task-models\";\nimport { BaseError, ComponentFactory, GeneralError, Guards, Is, Mutex } from \"@twin.org/core\";\nimport type { ILoggingComponent } from \"@twin.org/logging-models\";\nimport type {\n\tIEmailProtocolConnector,\n\tIEmailProtocolConnectorAuthCallback,\n\tIEmailProtocolConnectorRetrievalCallback\n} from \"@twin.org/mailbox-models\";\nimport { MailHelper } from \"@twin.org/mailbox-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { ImapFlow } from \"imapflow\";\nimport type { IImapEmailConnectorConfig } from \"./models/IImapEmailConnectorConfig.js\";\nimport type { IImapEmailConnectorConstructorOptions } from \"./models/IImapEmailConnectorConstructorOptions.js\";\nimport type { IImapEmailConnectorFolderState } from \"./models/IImapEmailConnectorFolderState.js\";\nimport type { IImapEmailConnectorState } from \"./models/IImapEmailConnectorState.js\";\n\n/**\n * IMAP email protocol connector. Polls configured folders for new messages using imapflow.\n */\nexport class ImapEmailConnector implements IEmailProtocolConnector<IImapEmailConnectorState> {\n\t/**\n\t * The class name.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<ImapEmailConnector>();\n\n\t/**\n\t * The protocol namespace identifier.\n\t */\n\tpublic static readonly NAMESPACE: string = \"imap\";\n\n\t/**\n\t * The logging component.\n\t * @internal\n\t */\n\tprivate readonly _logging?: ILoggingComponent;\n\n\t/**\n\t * The task scheduler component used for polling.\n\t * @internal\n\t */\n\tprivate readonly _taskScheduler: ITaskSchedulerComponent;\n\n\t/**\n\t * The resolved configuration for this connector instance.\n\t * @internal\n\t */\n\tprivate readonly _config: Required<\n\t\tPick<\n\t\t\tIImapEmailConnectorConfig,\n\t\t\t\"host\" | \"port\" | \"secure\" | \"username\" | \"password\" | \"folders\" | \"pollingIntervalMinutes\"\n\t\t>\n\t> &\n\t\tPick<IImapEmailConnectorConfig, \"mutexTimeoutMs\">;\n\n\t/**\n\t * The identifier of the currently active instance being polled.\n\t * @internal\n\t */\n\tprivate _instanceId?: string;\n\n\t/**\n\t * Set when retrieve has been called and cleared when retrieveStop is called.\n\t * @internal\n\t */\n\tprivate _retrieving: boolean;\n\n\t/**\n\t * The last successfully persisted connector state, updated after each successful callback.\n\t * @internal\n\t */\n\tprivate _state?: IImapEmailConnectorState;\n\n\t/**\n\t * Create a new instance of ImapEmailConnector.\n\t * @param options The options for the connector.\n\t */\n\tconstructor(options: IImapEmailConnectorConstructorOptions) {\n\t\tGuards.object(ImapEmailConnector.CLASS_NAME, nameof(options), options);\n\t\tGuards.object(ImapEmailConnector.CLASS_NAME, nameof(options.config), options.config);\n\t\tGuards.stringValue(\n\t\t\tImapEmailConnector.CLASS_NAME,\n\t\t\tnameof(options.config.host),\n\t\t\toptions.config.host\n\t\t);\n\t\tGuards.stringValue(\n\t\t\tImapEmailConnector.CLASS_NAME,\n\t\t\tnameof(options.config.username),\n\t\t\toptions.config.username\n\t\t);\n\t\tGuards.stringValue(\n\t\t\tImapEmailConnector.CLASS_NAME,\n\t\t\tnameof(options.config.password),\n\t\t\toptions.config.password\n\t\t);\n\n\t\tthis._logging = ComponentFactory.getIfExists<ILoggingComponent>(options.loggingComponentType);\n\n\t\tthis._taskScheduler = ComponentFactory.get<ITaskSchedulerComponent>(\n\t\t\toptions.taskSchedulerComponentType ?? \"task-scheduler\"\n\t\t);\n\n\t\tconst secure = options.config.secure ?? true;\n\t\tthis._config = {\n\t\t\thost: options.config.host,\n\t\t\tport: options.config.port ?? (secure ? 993 : 143),\n\t\t\tsecure,\n\t\t\tusername: options.config.username,\n\t\t\tpassword: options.config.password,\n\t\t\tfolders: options.config.folders ?? [\"INBOX\"],\n\t\t\tpollingIntervalMinutes: Math.max(1, options.config.pollingIntervalMinutes ?? 2),\n\t\t\tmutexTimeoutMs: options.config.mutexTimeoutMs\n\t\t};\n\t\tthis._retrieving = false;\n\t}\n\n\t/**\n\t * Get the class name.\n\t * @returns The class name.\n\t */\n\tpublic className(): string {\n\t\treturn ImapEmailConnector.CLASS_NAME;\n\t}\n\n\t/**\n\t * Start the internal polling loop for the given instance.\n\t * @param instanceId The identifier of the mailbox instance being polled.\n\t * @param state The current connector state for the instance.\n\t * @param authCallback Callback invoked when authentication fails during a poll cycle.\n\t * @param retrievalCallback Callback invoked with retrieved messages after each poll cycle.\n\t * @returns A promise that resolves when the polling loop has been started.\n\t */\n\tpublic async retrieve(\n\t\tinstanceId: string,\n\t\tstate: IImapEmailConnectorState,\n\t\tauthCallback: IEmailProtocolConnectorAuthCallback,\n\t\tretrievalCallback: IEmailProtocolConnectorRetrievalCallback\n\t): Promise<void> {\n\t\tawait this.retrieveStop();\n\n\t\tthis._retrieving = true;\n\t\tthis._instanceId = instanceId;\n\t\tthis._state = state;\n\n\t\tawait this._taskScheduler.addTask(\n\t\t\tinstanceId,\n\t\t\t[{ intervalMinutes: this._config.pollingIntervalMinutes }],\n\t\t\tasync () => {\n\t\t\t\tawait this.poll(authCallback, retrievalCallback);\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Stop the polling loop for this connector.\n\t * @returns A promise that resolves when the polling loop has been stopped.\n\t */\n\tpublic async retrieveStop(): Promise<void> {\n\t\tif (Is.stringValue(this._instanceId)) {\n\t\t\tthis._retrieving = false;\n\t\t\tawait this._taskScheduler.removeTask(this._instanceId);\n\t\t\tthis._instanceId = undefined;\n\t\t\tthis._state = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Poll each configured folder for new messages.\n\t * @param authCallback Callback invoked when authentication fails.\n\t * @param retrievalCallback Callback invoked with retrieved messages.\n\t * @internal\n\t */\n\tprivate async poll(\n\t\tauthCallback: IEmailProtocolConnectorAuthCallback,\n\t\tretrievalCallback: IEmailProtocolConnectorRetrievalCallback\n\t): Promise<void> {\n\t\tif (Is.empty(this._state) || !Is.stringValue(this._instanceId)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Capture the instance id and state for this poll cycle, retrieveStop can clear the\n\t\t// instance fields while a poll is in progress and the mutex must still be released\n\t\t// under the key it was locked with.\n\t\tconst instanceId = this._instanceId;\n\t\tconst state = this._state;\n\n\t\tawait Mutex.lock(instanceId, {\n\t\t\ttimeoutMs: this._config.mutexTimeoutMs,\n\t\t\tthrowOnTimeout: true\n\t\t});\n\n\t\tconst client = new ImapFlow({\n\t\t\thost: this._config.host,\n\t\t\tport: this._config.port,\n\t\t\tsecure: this._config.secure,\n\t\t\tauth: { user: this._config.username, pass: this._config.password },\n\t\t\tlogger: false\n\t\t});\n\n\t\ttry {\n\t\t\tawait client.connect();\n\n\t\t\tfor (const folder of this._config.folders) {\n\t\t\t\tconst continued = await this.pollFolder(client, folder, retrievalCallback);\n\t\t\t\tif (!continued) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst pollError = new GeneralError(\n\t\t\t\tImapEmailConnector.CLASS_NAME,\n\t\t\t\t\"pollFailed\",\n\t\t\t\tundefined,\n\t\t\t\tBaseError.fromError(error)\n\t\t\t);\n\n\t\t\tconst rawError = Is.object<{ authenticationFailed?: unknown; response?: unknown }>(error)\n\t\t\t\t? error\n\t\t\t\t: undefined;\n\t\t\tconst isAuthFailure = rawError?.authenticationFailed === true;\n\t\t\tif (isAuthFailure) {\n\t\t\t\tawait authCallback(instanceId, state, true, undefined, pollError);\n\t\t\t} else {\n\t\t\t\tawait retrievalCallback(instanceId, undefined, state, pollError);\n\t\t\t}\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait client.logout();\n\t\t\t\tclient.close();\n\t\t\t} catch {\n\t\t\t\t// ignore, not much we can do if the connection is already closed\n\t\t\t\t// but don't want to prevent the mutex from being unlocked in the finally block below\n\t\t\t}\n\t\t\tMutex.unlock(instanceId);\n\t\t}\n\t}\n\n\t/**\n\t * Poll a single folder for messages with UIDs beyond the last seen UID.\n\t * Each parsed message is forwarded to the retrieval callback; returning false aborts processing.\n\t * @param client The connected ImapFlow client.\n\t * @param folder The folder path to poll.\n\t * @param retrievalCallback Callback invoked for each parsed email; return false to abort.\n\t * @returns True if all messages were processed, false if processing was aborted.\n\t * @internal\n\t */\n\tprivate async pollFolder(\n\t\tclient: ImapFlow,\n\t\tfolder: string,\n\t\tretrievalCallback: IEmailProtocolConnectorRetrievalCallback\n\t): Promise<boolean> {\n\t\tif (Is.empty(this._state) || !Is.stringValue(this._instanceId)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tthis._state.folders ??= {};\n\t\tconst folderState: IImapEmailConnectorFolderState = this._state.folders[folder] ?? {};\n\t\tthis._state.folders[folder] = folderState;\n\n\t\tconst lock = await client.getMailboxLock(folder);\n\t\ttry {\n\t\t\tif (!client.mailbox) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tconst uidValidity = client.mailbox.uidValidity.toString();\n\n\t\t\tif (folderState.uidValidity !== uidValidity) {\n\t\t\t\tfolderState.uidValidity = uidValidity;\n\t\t\t\tfolderState.lastUid = 0;\n\t\t\t}\n\n\t\t\tconst lastUid = folderState.lastUid ?? 0;\n\t\t\tconst searchQuery = lastUid > 0 ? { uid: `${lastUid + 1}:*` } : { all: true };\n\t\t\tconst uids = await client.search(searchQuery, { uid: true });\n\n\t\t\tif (uids !== false && Is.arrayValue(uids)) {\n\t\t\t\tconst msgStream = client.fetch(\n\t\t\t\t\tuids,\n\t\t\t\t\t{ uid: true, source: true, flags: true },\n\t\t\t\t\t{ uid: true }\n\t\t\t\t);\n\t\t\t\t// Any early exit from this loop (return, break or throw) must terminate the\n\t\t\t\t// fetch iterator, otherwise imapflow leaves the FETCH command pending and the\n\t\t\t\t// LOGOUT queued behind it in poll() never resolves, so the mutex is never\n\t\t\t\t// released. for await calls the iterator's return() on every exit path.\n\t\t\t\tfor await (const msg of msgStream) {\n\t\t\t\t\tif (!this._retrieving) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tconst currentLastUid = folderState.lastUid ?? 0;\n\t\t\t\t\tif (Is.notEmpty(msg.uid) && msg.uid > currentLastUid) {\n\t\t\t\t\t\tif (Is.notEmpty(msg.source)) {\n\t\t\t\t\t\t\tconst email = await MailHelper.parseEmail(\n\t\t\t\t\t\t\t\tmsg.source.toString(),\n\t\t\t\t\t\t\t\tmsg.flags ? [...msg.flags] : undefined\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (Is.notEmpty(email)) {\n\t\t\t\t\t\t\t\tawait this._logging?.log({\n\t\t\t\t\t\t\t\t\tlevel: \"info\",\n\t\t\t\t\t\t\t\t\tsource: ImapEmailConnector.CLASS_NAME,\n\t\t\t\t\t\t\t\t\tts: Date.now(),\n\t\t\t\t\t\t\t\t\tmessage: \"emailReceived\",\n\t\t\t\t\t\t\t\t\tdata: { subject: email.subject }\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tfolderState.lastUid = msg.uid;\n\t\t\t\t\t\t\t\tconst shouldContinue = await retrievalCallback(\n\t\t\t\t\t\t\t\t\tthis._instanceId,\n\t\t\t\t\t\t\t\t\temail,\n\t\t\t\t\t\t\t\t\tthis._state\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (!shouldContinue) {\n\t\t\t\t\t\t\t\t\tfolderState.lastUid = currentLastUid;\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tlock.release();\n\t\t}\n\t\treturn true;\n\t}\n}\n"]}
@@ -0,0 +1,9 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export * from "./configSchema/imapEmailConnectorConfigSchema.js";
4
+ export * from "./imapEmailConnector.js";
5
+ export * from "./models/IImapEmailConnectorConfig.js";
6
+ export * from "./models/IImapEmailConnectorConstructorOptions.js";
7
+ export * from "./models/IImapEmailConnectorFolderState.js";
8
+ export * from "./models/IImapEmailConnectorState.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,kDAAkD,CAAC;AACjE,cAAc,yBAAyB,CAAC;AACxC,cAAc,uCAAuC,CAAC;AACtD,cAAc,mDAAmD,CAAC;AAClE,cAAc,4CAA4C,CAAC;AAC3D,cAAc,sCAAsC,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./configSchema/imapEmailConnectorConfigSchema.js\";\nexport * from \"./imapEmailConnector.js\";\nexport * from \"./models/IImapEmailConnectorConfig.js\";\nexport * from \"./models/IImapEmailConnectorConstructorOptions.js\";\nexport * from \"./models/IImapEmailConnectorFolderState.js\";\nexport * from \"./models/IImapEmailConnectorState.js\";\n"]}
@@ -0,0 +1,4 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export {};
4
+ //# sourceMappingURL=IImapEmailConnectorConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IImapEmailConnectorConfig.js","sourceRoot":"","sources":["../../../src/models/IImapEmailConnectorConfig.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * Configuration for the IMAP email connector.\n */\nexport interface IImapEmailConnectorConfig {\n\t/**\n\t * The hostname or IP address of the IMAP server.\n\t */\n\thost: string;\n\n\t/**\n\t * The port number to connect to.\n\t * @default 993\n\t */\n\tport?: number;\n\n\t/**\n\t * Whether to use a direct TLS connection.\n\t * Set to false to use a plain connection (STARTTLS may still be negotiated).\n\t * @default true\n\t */\n\tsecure?: boolean;\n\n\t/**\n\t * The username to authenticate with.\n\t */\n\tusername: string;\n\n\t/**\n\t * The password to authenticate with. Stored securely in the vault.\n\t */\n\tpassword: string;\n\n\t/**\n\t * The folder paths to poll for new messages.\n\t * Nested paths use the server's hierarchy delimiter, e.g. \"Work/Projects\".\n\t * @default [\"INBOX\"]\n\t */\n\tfolders?: string[];\n\n\t/**\n\t * How often to poll for new messages, in minutes.\n\t * @default 2\n\t */\n\tpollingIntervalMinutes?: number;\n\n\t/**\n\t * Maximum time in milliseconds to wait for the poll mutex before skipping the tick.\n\t * When not set, the mutex waits based on the system default.\n\t */\n\tmutexTimeoutMs?: number;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IImapEmailConnectorConstructorOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IImapEmailConnectorConstructorOptions.js","sourceRoot":"","sources":["../../../src/models/IImapEmailConnectorConstructorOptions.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IImapEmailConnectorConfig } from \"./IImapEmailConnectorConfig.js\";\n\n/**\n * Constructor options for the IMAP email connector.\n */\nexport interface IImapEmailConnectorConstructorOptions {\n\t/**\n\t * The configuration for the IMAP connector.\n\t */\n\tconfig: IImapEmailConnectorConfig;\n\n\t/**\n\t * The component type for the task scheduler used to manage polling intervals.\n\t * @default \"task-scheduler\"\n\t */\n\ttaskSchedulerComponentType?: string;\n\n\t/**\n\t * The component type for logging.\n\t */\n\tloggingComponentType?: string;\n}\n"]}
@@ -0,0 +1,4 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export {};
4
+ //# sourceMappingURL=IImapEmailConnectorFolderState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IImapEmailConnectorFolderState.js","sourceRoot":"","sources":["../../../src/models/IImapEmailConnectorFolderState.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * Per-folder polling state for the IMAP connector.\n */\nexport interface IImapEmailConnectorFolderState {\n\t/**\n\t * The UID validity value at the time of the last successful poll,\n\t * serialised as a string to survive JSON round-trips.\n\t * When this changes the connector resets lastUid to 0.\n\t */\n\tuidValidity?: string;\n\n\t/**\n\t * The highest UID successfully processed in the last poll cycle.\n\t * The next poll fetches UIDs strictly greater than this value.\n\t */\n\tlastUid?: number;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IImapEmailConnectorState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IImapEmailConnectorState.js","sourceRoot":"","sources":["../../../src/models/IImapEmailConnectorState.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IImapEmailConnectorFolderState } from \"./IImapEmailConnectorFolderState.js\";\n\n/**\n * Top-level polling state for the IMAP connector, keyed by folder path.\n */\nexport interface IImapEmailConnectorState {\n\t/**\n\t * Per-folder state, keyed by the folder path as configured.\n\t */\n\tfolders?: { [folderPath: string]: IImapEmailConnectorFolderState };\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import type { IMailboxConfigField } from "@twin.org/mailbox-models";
2
+ /**
3
+ * The configuration field schema for IMAP connectors.
4
+ */
5
+ export declare const ImapEmailConnectorConfigSchema: IMailboxConfigField[];
@@ -0,0 +1,40 @@
1
+ import type { IEmailProtocolConnector, IEmailProtocolConnectorAuthCallback, IEmailProtocolConnectorRetrievalCallback } from "@twin.org/mailbox-models";
2
+ import type { IImapEmailConnectorConstructorOptions } from "./models/IImapEmailConnectorConstructorOptions.js";
3
+ import type { IImapEmailConnectorState } from "./models/IImapEmailConnectorState.js";
4
+ /**
5
+ * IMAP email protocol connector. Polls configured folders for new messages using imapflow.
6
+ */
7
+ export declare class ImapEmailConnector implements IEmailProtocolConnector<IImapEmailConnectorState> {
8
+ /**
9
+ * The class name.
10
+ */
11
+ static readonly CLASS_NAME: string;
12
+ /**
13
+ * The protocol namespace identifier.
14
+ */
15
+ static readonly NAMESPACE: string;
16
+ /**
17
+ * Create a new instance of ImapEmailConnector.
18
+ * @param options The options for the connector.
19
+ */
20
+ constructor(options: IImapEmailConnectorConstructorOptions);
21
+ /**
22
+ * Get the class name.
23
+ * @returns The class name.
24
+ */
25
+ className(): string;
26
+ /**
27
+ * Start the internal polling loop for the given instance.
28
+ * @param instanceId The identifier of the mailbox instance being polled.
29
+ * @param state The current connector state for the instance.
30
+ * @param authCallback Callback invoked when authentication fails during a poll cycle.
31
+ * @param retrievalCallback Callback invoked with retrieved messages after each poll cycle.
32
+ * @returns A promise that resolves when the polling loop has been started.
33
+ */
34
+ retrieve(instanceId: string, state: IImapEmailConnectorState, authCallback: IEmailProtocolConnectorAuthCallback, retrievalCallback: IEmailProtocolConnectorRetrievalCallback): Promise<void>;
35
+ /**
36
+ * Stop the polling loop for this connector.
37
+ * @returns A promise that resolves when the polling loop has been stopped.
38
+ */
39
+ retrieveStop(): Promise<void>;
40
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./configSchema/imapEmailConnectorConfigSchema.js";
2
+ export * from "./imapEmailConnector.js";
3
+ export * from "./models/IImapEmailConnectorConfig.js";
4
+ export * from "./models/IImapEmailConnectorConstructorOptions.js";
5
+ export * from "./models/IImapEmailConnectorFolderState.js";
6
+ export * from "./models/IImapEmailConnectorState.js";
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Configuration for the IMAP email connector.
3
+ */
4
+ export interface IImapEmailConnectorConfig {
5
+ /**
6
+ * The hostname or IP address of the IMAP server.
7
+ */
8
+ host: string;
9
+ /**
10
+ * The port number to connect to.
11
+ * @default 993
12
+ */
13
+ port?: number;
14
+ /**
15
+ * Whether to use a direct TLS connection.
16
+ * Set to false to use a plain connection (STARTTLS may still be negotiated).
17
+ * @default true
18
+ */
19
+ secure?: boolean;
20
+ /**
21
+ * The username to authenticate with.
22
+ */
23
+ username: string;
24
+ /**
25
+ * The password to authenticate with. Stored securely in the vault.
26
+ */
27
+ password: string;
28
+ /**
29
+ * The folder paths to poll for new messages.
30
+ * Nested paths use the server's hierarchy delimiter, e.g. "Work/Projects".
31
+ * @default ["INBOX"]
32
+ */
33
+ folders?: string[];
34
+ /**
35
+ * How often to poll for new messages, in minutes.
36
+ * @default 2
37
+ */
38
+ pollingIntervalMinutes?: number;
39
+ /**
40
+ * Maximum time in milliseconds to wait for the poll mutex before skipping the tick.
41
+ * When not set, the mutex waits based on the system default.
42
+ */
43
+ mutexTimeoutMs?: number;
44
+ }
@@ -0,0 +1,19 @@
1
+ import type { IImapEmailConnectorConfig } from "./IImapEmailConnectorConfig.js";
2
+ /**
3
+ * Constructor options for the IMAP email connector.
4
+ */
5
+ export interface IImapEmailConnectorConstructorOptions {
6
+ /**
7
+ * The configuration for the IMAP connector.
8
+ */
9
+ config: IImapEmailConnectorConfig;
10
+ /**
11
+ * The component type for the task scheduler used to manage polling intervals.
12
+ * @default "task-scheduler"
13
+ */
14
+ taskSchedulerComponentType?: string;
15
+ /**
16
+ * The component type for logging.
17
+ */
18
+ loggingComponentType?: string;
19
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Per-folder polling state for the IMAP connector.
3
+ */
4
+ export interface IImapEmailConnectorFolderState {
5
+ /**
6
+ * The UID validity value at the time of the last successful poll,
7
+ * serialised as a string to survive JSON round-trips.
8
+ * When this changes the connector resets lastUid to 0.
9
+ */
10
+ uidValidity?: string;
11
+ /**
12
+ * The highest UID successfully processed in the last poll cycle.
13
+ * The next poll fetches UIDs strictly greater than this value.
14
+ */
15
+ lastUid?: number;
16
+ }
@@ -0,0 +1,12 @@
1
+ import type { IImapEmailConnectorFolderState } from "./IImapEmailConnectorFolderState.js";
2
+ /**
3
+ * Top-level polling state for the IMAP connector, keyed by folder path.
4
+ */
5
+ export interface IImapEmailConnectorState {
6
+ /**
7
+ * Per-folder state, keyed by the folder path as configured.
8
+ */
9
+ folders?: {
10
+ [folderPath: string]: IImapEmailConnectorFolderState;
11
+ };
12
+ }
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## [0.9.3-next.1](https://github.com/iotaledger/twin-messaging/compare/mailbox-connector-imap-v0.9.3-next.0...mailbox-connector-imap-v0.9.3-next.1) (2026-09-04)
4
+
5
+
6
+ ### Features
7
+
8
+ * add email ingestion ([#56](https://github.com/iotaledger/twin-messaging/issues/56)) ([390806d](https://github.com/iotaledger/twin-messaging/commit/390806d2690843f44de0b6a8a5e5de616b16c278))
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @twin.org/mailbox-models bumped from 0.9.3-next.0 to 0.9.3-next.1
16
+
17
+ ## Changelog
@@ -0,0 +1,98 @@
1
+ # Mailbox Connector IMAP Examples
2
+
3
+ A polling connector for email ingestion via the IMAP protocol, with per-folder UID tracking.
4
+
5
+ ## ImapEmailConnector
6
+
7
+ ```typescript
8
+ import {
9
+ ImapEmailConnector,
10
+ ImapEmailConnectorConfigSchema
11
+ } from '@twin.org/mailbox-connector-imap';
12
+ import {
13
+ EmailProtocolConnectorFactory,
14
+ EmailProtocolConnectorSchemaFactory
15
+ } from '@twin.org/mailbox-models';
16
+
17
+ // Register the connector and its config schema with the shared factories
18
+ EmailProtocolConnectorFactory.register(
19
+ ImapEmailConnector.NAMESPACE,
20
+ () =>
21
+ new ImapEmailConnector({
22
+ config: {
23
+ host: 'imap.example.com',
24
+ username: 'user@example.com',
25
+ password: 'secret'
26
+ }
27
+ })
28
+ );
29
+
30
+ EmailProtocolConnectorSchemaFactory.register(
31
+ ImapEmailConnector.NAMESPACE,
32
+ () => ImapEmailConnectorConfigSchema
33
+ );
34
+
35
+ const schema = EmailProtocolConnectorSchemaFactory.get(ImapEmailConnector.NAMESPACE);
36
+ console.log(schema.find(f => f.isSecure)?.propertyKey); // "password"
37
+ ```
38
+
39
+ ```typescript
40
+ import { ImapEmailConnector } from '@twin.org/mailbox-connector-imap';
41
+ import type { IImapEmailConnectorState } from '@twin.org/mailbox-connector-imap';
42
+ import type {
43
+ IEmailProtocolConnectorAuthCallback,
44
+ IEmailProtocolConnectorRetrievalCallback
45
+ } from '@twin.org/mailbox-models';
46
+
47
+ const connector = new ImapEmailConnector({
48
+ config: {
49
+ host: 'imap.example.com',
50
+ port: 993,
51
+ secure: true,
52
+ username: 'user@example.com',
53
+ password: 'secret',
54
+ folders: ['INBOX', 'Work/Projects'],
55
+ batchSize: 5,
56
+ pollingIntervalMinutes: 2
57
+ }
58
+ });
59
+
60
+ // State persisted between poll cycles; tracks the last UID seen per folder
61
+ const state: IImapEmailConnectorState = {};
62
+
63
+ const authCallback: IEmailProtocolConnectorAuthCallback = async (
64
+ mailboxId,
65
+ requiresAuth,
66
+ updatedState,
67
+ error,
68
+ authState
69
+ ) => {
70
+ if (requiresAuth) {
71
+ console.log(`Mailbox ${mailboxId} needs re-authentication`);
72
+ }
73
+ };
74
+
75
+ const retrievalCallback: IEmailProtocolConnectorRetrievalCallback = async (
76
+ mailboxId,
77
+ messages,
78
+ updatedState,
79
+ error
80
+ ) => {
81
+ console.log(messages.length); // number of messages in this batch
82
+ for (const message of messages) {
83
+ console.log(message.subject); // e.g. "Project update"
84
+ console.log(message.flags); // e.g. ["\\Seen"]
85
+ console.log(message.htmlContent !== undefined); // true when HTML part is present
86
+ }
87
+ if (error !== undefined) {
88
+ console.log(error.message); // description of the retrieval problem
89
+ }
90
+ // Persist updatedState to resume from the last seen UID on the next poll cycle
91
+ };
92
+
93
+ // Start the polling loop; the scheduler fires it every pollingIntervalMinutes
94
+ await connector.retrieve('mailbox-abc', state, authCallback, retrievalCallback);
95
+
96
+ // Stop polling when the mailbox is removed or disabled
97
+ await connector.retrieveStop();
98
+ ```
@@ -0,0 +1,123 @@
1
+ # Class: ImapEmailConnector
2
+
3
+ IMAP email protocol connector. Polls configured folders for new messages using imapflow.
4
+
5
+ ## Implements
6
+
7
+ - `IEmailProtocolConnector`\<[`IImapEmailConnectorState`](../interfaces/IImapEmailConnectorState.md)\>
8
+
9
+ ## Constructors
10
+
11
+ ### Constructor
12
+
13
+ > **new ImapEmailConnector**(`options`): `ImapEmailConnector`
14
+
15
+ Create a new instance of ImapEmailConnector.
16
+
17
+ #### Parameters
18
+
19
+ ##### options
20
+
21
+ [`IImapEmailConnectorConstructorOptions`](../interfaces/IImapEmailConnectorConstructorOptions.md)
22
+
23
+ The options for the connector.
24
+
25
+ #### Returns
26
+
27
+ `ImapEmailConnector`
28
+
29
+ ## Properties
30
+
31
+ ### CLASS\_NAME {#class_name}
32
+
33
+ > `readonly` `static` **CLASS\_NAME**: `string`
34
+
35
+ The class name.
36
+
37
+ ***
38
+
39
+ ### NAMESPACE {#namespace}
40
+
41
+ > `readonly` `static` **NAMESPACE**: `string` = `"imap"`
42
+
43
+ The protocol namespace identifier.
44
+
45
+ ## Methods
46
+
47
+ ### className() {#classname}
48
+
49
+ > **className**(): `string`
50
+
51
+ Get the class name.
52
+
53
+ #### Returns
54
+
55
+ `string`
56
+
57
+ The class name.
58
+
59
+ #### Implementation of
60
+
61
+ `IEmailProtocolConnector.className`
62
+
63
+ ***
64
+
65
+ ### retrieve() {#retrieve}
66
+
67
+ > **retrieve**(`instanceId`, `state`, `authCallback`, `retrievalCallback`): `Promise`\<`void`\>
68
+
69
+ Start the internal polling loop for the given instance.
70
+
71
+ #### Parameters
72
+
73
+ ##### instanceId
74
+
75
+ `string`
76
+
77
+ The identifier of the mailbox instance being polled.
78
+
79
+ ##### state
80
+
81
+ [`IImapEmailConnectorState`](../interfaces/IImapEmailConnectorState.md)
82
+
83
+ The current connector state for the instance.
84
+
85
+ ##### authCallback
86
+
87
+ `IEmailProtocolConnectorAuthCallback`
88
+
89
+ Callback invoked when authentication fails during a poll cycle.
90
+
91
+ ##### retrievalCallback
92
+
93
+ `IEmailProtocolConnectorRetrievalCallback`
94
+
95
+ Callback invoked with retrieved messages after each poll cycle.
96
+
97
+ #### Returns
98
+
99
+ `Promise`\<`void`\>
100
+
101
+ A promise that resolves when the polling loop has been started.
102
+
103
+ #### Implementation of
104
+
105
+ `IEmailProtocolConnector.retrieve`
106
+
107
+ ***
108
+
109
+ ### retrieveStop() {#retrievestop}
110
+
111
+ > **retrieveStop**(): `Promise`\<`void`\>
112
+
113
+ Stop the polling loop for this connector.
114
+
115
+ #### Returns
116
+
117
+ `Promise`\<`void`\>
118
+
119
+ A promise that resolves when the polling loop has been stopped.
120
+
121
+ #### Implementation of
122
+
123
+ `IEmailProtocolConnector.retrieveStop`
@@ -0,0 +1,16 @@
1
+ # @twin.org/mailbox-connector-imap
2
+
3
+ ## Classes
4
+
5
+ - [ImapEmailConnector](classes/ImapEmailConnector.md)
6
+
7
+ ## Interfaces
8
+
9
+ - [IImapEmailConnectorConfig](interfaces/IImapEmailConnectorConfig.md)
10
+ - [IImapEmailConnectorConstructorOptions](interfaces/IImapEmailConnectorConstructorOptions.md)
11
+ - [IImapEmailConnectorFolderState](interfaces/IImapEmailConnectorFolderState.md)
12
+ - [IImapEmailConnectorState](interfaces/IImapEmailConnectorState.md)
13
+
14
+ ## Variables
15
+
16
+ - [ImapEmailConnectorConfigSchema](variables/ImapEmailConnectorConfigSchema.md)
@@ -0,0 +1,94 @@
1
+ # Interface: IImapEmailConnectorConfig
2
+
3
+ Configuration for the IMAP email connector.
4
+
5
+ ## Properties
6
+
7
+ ### host {#host}
8
+
9
+ > **host**: `string`
10
+
11
+ The hostname or IP address of the IMAP server.
12
+
13
+ ***
14
+
15
+ ### port? {#port}
16
+
17
+ > `optional` **port?**: `number`
18
+
19
+ The port number to connect to.
20
+
21
+ #### Default
22
+
23
+ ```ts
24
+ 993
25
+ ```
26
+
27
+ ***
28
+
29
+ ### secure? {#secure}
30
+
31
+ > `optional` **secure?**: `boolean`
32
+
33
+ Whether to use a direct TLS connection.
34
+ Set to false to use a plain connection (STARTTLS may still be negotiated).
35
+
36
+ #### Default
37
+
38
+ ```ts
39
+ true
40
+ ```
41
+
42
+ ***
43
+
44
+ ### username {#username}
45
+
46
+ > **username**: `string`
47
+
48
+ The username to authenticate with.
49
+
50
+ ***
51
+
52
+ ### password {#password}
53
+
54
+ > **password**: `string`
55
+
56
+ The password to authenticate with. Stored securely in the vault.
57
+
58
+ ***
59
+
60
+ ### folders? {#folders}
61
+
62
+ > `optional` **folders?**: `string`[]
63
+
64
+ The folder paths to poll for new messages.
65
+ Nested paths use the server's hierarchy delimiter, e.g. "Work/Projects".
66
+
67
+ #### Default
68
+
69
+ ```ts
70
+ ["INBOX"]
71
+ ```
72
+
73
+ ***
74
+
75
+ ### pollingIntervalMinutes? {#pollingintervalminutes}
76
+
77
+ > `optional` **pollingIntervalMinutes?**: `number`
78
+
79
+ How often to poll for new messages, in minutes.
80
+
81
+ #### Default
82
+
83
+ ```ts
84
+ 2
85
+ ```
86
+
87
+ ***
88
+
89
+ ### mutexTimeoutMs? {#mutextimeoutms}
90
+
91
+ > `optional` **mutexTimeoutMs?**: `number`
92
+
93
+ Maximum time in milliseconds to wait for the poll mutex before skipping the tick.
94
+ When not set, the mutex waits based on the system default.
@@ -0,0 +1,33 @@
1
+ # Interface: IImapEmailConnectorConstructorOptions
2
+
3
+ Constructor options for the IMAP email connector.
4
+
5
+ ## Properties
6
+
7
+ ### config {#config}
8
+
9
+ > **config**: [`IImapEmailConnectorConfig`](IImapEmailConnectorConfig.md)
10
+
11
+ The configuration for the IMAP connector.
12
+
13
+ ***
14
+
15
+ ### taskSchedulerComponentType? {#taskschedulercomponenttype}
16
+
17
+ > `optional` **taskSchedulerComponentType?**: `string`
18
+
19
+ The component type for the task scheduler used to manage polling intervals.
20
+
21
+ #### Default
22
+
23
+ ```ts
24
+ "task-scheduler"
25
+ ```
26
+
27
+ ***
28
+
29
+ ### loggingComponentType? {#loggingcomponenttype}
30
+
31
+ > `optional` **loggingComponentType?**: `string`
32
+
33
+ The component type for logging.
@@ -0,0 +1,22 @@
1
+ # Interface: IImapEmailConnectorFolderState
2
+
3
+ Per-folder polling state for the IMAP connector.
4
+
5
+ ## Properties
6
+
7
+ ### uidValidity? {#uidvalidity}
8
+
9
+ > `optional` **uidValidity?**: `string`
10
+
11
+ The UID validity value at the time of the last successful poll,
12
+ serialised as a string to survive JSON round-trips.
13
+ When this changes the connector resets lastUid to 0.
14
+
15
+ ***
16
+
17
+ ### lastUid? {#lastuid}
18
+
19
+ > `optional` **lastUid?**: `number`
20
+
21
+ The highest UID successfully processed in the last poll cycle.
22
+ The next poll fetches UIDs strictly greater than this value.
@@ -0,0 +1,15 @@
1
+ # Interface: IImapEmailConnectorState
2
+
3
+ Top-level polling state for the IMAP connector, keyed by folder path.
4
+
5
+ ## Properties
6
+
7
+ ### folders? {#folders}
8
+
9
+ > `optional` **folders?**: `object`
10
+
11
+ Per-folder state, keyed by the folder path as configured.
12
+
13
+ #### Index Signature
14
+
15
+ \[`folderPath`: `string`\]: [`IImapEmailConnectorFolderState`](IImapEmailConnectorFolderState.md)
@@ -0,0 +1,5 @@
1
+ # Variable: ImapEmailConnectorConfigSchema
2
+
3
+ > `const` **ImapEmailConnectorConfigSchema**: `IMailboxConfigField`[]
4
+
5
+ The configuration field schema for IMAP connectors.
@@ -0,0 +1,21 @@
1
+ {
2
+ "error": {
3
+ "imapEmailConnector": {
4
+ "pollFailed": "Poll failed"
5
+ }
6
+ },
7
+ "info": {
8
+ "imapEmailConnector": {
9
+ "emailReceived": "Email received \"{subject}\""
10
+ }
11
+ },
12
+ "imapEmailConnectorConfigSchema": {
13
+ "host": "Host",
14
+ "port": "Port",
15
+ "secure": "Secure",
16
+ "username": "Username",
17
+ "password": "Password",
18
+ "folders": "Folders",
19
+ "pollingIntervalMinutes": "Polling Interval (Minutes)"
20
+ }
21
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@twin.org/mailbox-connector-imap",
3
+ "version": "0.9.3-next.1",
4
+ "description": "IMAP connector for email mailbox ingestion.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/iotaledger/twin-messaging.git",
8
+ "directory": "packages/mailbox-connector-imap"
9
+ },
10
+ "author": "martyn.janes@iota.org",
11
+ "license": "Apache-2.0",
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=24.0.0"
15
+ },
16
+ "dependencies": {
17
+ "@twin.org/background-task-models": "next",
18
+ "@twin.org/core": "next",
19
+ "@twin.org/entity": "next",
20
+ "@twin.org/logging-models": "next",
21
+ "@twin.org/mailbox-models": "0.9.3-next.1",
22
+ "@twin.org/nameof": "next",
23
+ "imapflow": "1.7.7"
24
+ },
25
+ "main": "./dist/es/index.js",
26
+ "types": "./dist/types/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/types/index.d.ts",
30
+ "import": "./dist/es/index.js",
31
+ "default": "./dist/es/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist/es",
36
+ "dist/types",
37
+ "locales",
38
+ "docs"
39
+ ],
40
+ "keywords": [
41
+ "twin",
42
+ "trade",
43
+ "iota",
44
+ "framework",
45
+ "blockchain",
46
+ "messaging",
47
+ "mailbox",
48
+ "email",
49
+ "imap",
50
+ "connector"
51
+ ],
52
+ "bugs": {
53
+ "url": "git+https://github.com/iotaledger/twin-messaging/issues"
54
+ },
55
+ "homepage": "https://twindev.org"
56
+ }