mailset 0.7.0__py3-none-any.whl

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.
mailset/__init__.py ADDED
@@ -0,0 +1,121 @@
1
+ """Mailset for a product's server: send mail from a mailbox your app was
2
+ granted, verify your hook's webhooks, and run any of Mailset's public
3
+ commands.
4
+
5
+ ``MAILSET_KEY`` comes from ``mailset keys create --send --mailbox <address>``,
6
+ approved with a passkey, and can send only as that mailbox. ``MAILSET_TOKEN``,
7
+ an API token from ``mailset tokens create``, is a person's, and runs what
8
+ they may::
9
+
10
+ from mailset import Mailset
11
+
12
+ mailset = Mailset() # MAILSET_KEY, else MAILSET_TOKEN, from the environment
13
+ sent = mailset.send({
14
+ "from": "Acme <hello@example.com>",
15
+ "to": "ana@example.com",
16
+ "subject": "Your code",
17
+ "text": "Your code is 123456.",
18
+ })
19
+
20
+ Every input and answer is a ``TypedDict``: a plain dict whose keys are the
21
+ API's fields in snake_case (``from`` stays ``from``). Every command's types
22
+ are in ``mailset.types``. The one method named otherwise is ``import``, a
23
+ Python keyword: ``contacts.import_contacts`` and ``rules.import_rules``.
24
+
25
+ Docs: https://mailset.app/docs/sdk and https://mailset.app/docs/api.
26
+ """
27
+
28
+ from . import types, webhooks
29
+ from ._client import AsyncMailset, Mailset
30
+ from ._convert import from_api, to_api
31
+ from ._core import Approval
32
+ from ._errors import (
33
+ APIConnectionError,
34
+ APITimeoutError,
35
+ AuthenticationError,
36
+ ConflictError,
37
+ InvalidRequestError,
38
+ Issue,
39
+ MailsetError,
40
+ NotFoundError,
41
+ PasskeyPurpose,
42
+ PasskeyRequiredError,
43
+ PermissionDeniedError,
44
+ RateLimitError,
45
+ ServerError,
46
+ )
47
+ from ._handwritten import (
48
+ CampaignMessage,
49
+ CampaignSubmitInput,
50
+ DeliveryLine,
51
+ DeliveryPage,
52
+ DeliverySearchInput,
53
+ DeliveryStatus,
54
+ SendingSubmitInput,
55
+ Track,
56
+ )
57
+ from ._message import (
58
+ Address,
59
+ Attachment,
60
+ BuiltMessage,
61
+ NamedAddress,
62
+ Recipients,
63
+ SendInput,
64
+ build_message,
65
+ read_attachment,
66
+ )
67
+ from ._platform import MailsetUpgradeWarning
68
+ from ._resources import SDK_VERSION
69
+ from ._send import NotSent, SendResult, Sent, Skipped
70
+ from .types import DeliveryClient, KeyStatus
71
+ from .webhooks import MailEvent
72
+
73
+ __version__ = SDK_VERSION
74
+
75
+ __all__ = [
76
+ "APIConnectionError",
77
+ "APITimeoutError",
78
+ "Address",
79
+ "Approval",
80
+ "AsyncMailset",
81
+ "Attachment",
82
+ "AuthenticationError",
83
+ "BuiltMessage",
84
+ "CampaignMessage",
85
+ "CampaignSubmitInput",
86
+ "ConflictError",
87
+ "DeliveryClient",
88
+ "DeliveryLine",
89
+ "DeliveryPage",
90
+ "DeliverySearchInput",
91
+ "DeliveryStatus",
92
+ "InvalidRequestError",
93
+ "Issue",
94
+ "KeyStatus",
95
+ "MailEvent",
96
+ "Mailset",
97
+ "MailsetError",
98
+ "MailsetUpgradeWarning",
99
+ "NamedAddress",
100
+ "NotFoundError",
101
+ "NotSent",
102
+ "PasskeyPurpose",
103
+ "PasskeyRequiredError",
104
+ "PermissionDeniedError",
105
+ "RateLimitError",
106
+ "Recipients",
107
+ "SendInput",
108
+ "SendResult",
109
+ "SendingSubmitInput",
110
+ "Sent",
111
+ "ServerError",
112
+ "Skipped",
113
+ "Track",
114
+ "__version__",
115
+ "build_message",
116
+ "from_api",
117
+ "read_attachment",
118
+ "to_api",
119
+ "types",
120
+ "webhooks",
121
+ ]
mailset/_base.py ADDED
@@ -0,0 +1,54 @@
1
+ """What every group of the client is: a handle on the client's core."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Mapping, Optional
6
+
7
+ if TYPE_CHECKING:
8
+ from ._core import AsyncCore, SyncCore
9
+
10
+ __all__ = ["AsyncGroup", "SyncGroup"]
11
+
12
+
13
+ class SyncGroup:
14
+ """A group of ``Mailset``'s commands, such as ``mailset.domains``."""
15
+
16
+ def __init__(self, core: SyncCore) -> None:
17
+ self._core = core
18
+
19
+ def __repr__(self) -> str:
20
+ return f"<{type(self).__name__}>"
21
+
22
+ def _call(
23
+ self,
24
+ command: str,
25
+ params: Optional[Mapping[str, Any]],
26
+ given: str,
27
+ answer: str,
28
+ org: Optional[str],
29
+ approval: Optional[str],
30
+ timeout: Optional[float],
31
+ ) -> Any:
32
+ return self._core.command(command, params, given, answer, org, approval, timeout)
33
+
34
+
35
+ class AsyncGroup:
36
+ """A group of ``AsyncMailset``'s commands, such as ``mailset.domains``."""
37
+
38
+ def __init__(self, core: AsyncCore) -> None:
39
+ self._core = core
40
+
41
+ def __repr__(self) -> str:
42
+ return f"<{type(self).__name__}>"
43
+
44
+ async def _call(
45
+ self,
46
+ command: str,
47
+ params: Optional[Mapping[str, Any]],
48
+ given: str,
49
+ answer: str,
50
+ org: Optional[str],
51
+ approval: Optional[str],
52
+ timeout: Optional[float],
53
+ ) -> Any:
54
+ return await self._core.command(command, params, given, answer, org, approval, timeout)
mailset/_client.py ADDED
@@ -0,0 +1,309 @@
1
+ """``Mailset`` and ``AsyncMailset``: a client for one credential."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import TracebackType
6
+ from typing import (
7
+ Any,
8
+ Awaitable,
9
+ Callable,
10
+ List,
11
+ Mapping,
12
+ Optional,
13
+ Sequence,
14
+ Type,
15
+ Union,
16
+ overload,
17
+ )
18
+
19
+ import httpx
20
+
21
+ from ._convert import to_wire
22
+ from ._core import Approval, AsyncCore, SyncCore
23
+ from ._credentials import credential_from
24
+ from ._errors import MailsetError
25
+ from ._handwritten import Approvals, AsyncApprovals, AsyncKey, Key
26
+ from ._message import SendInput
27
+ from ._resources import AsyncMailsetCommands, MailsetCommands
28
+ from ._send import Batch, SendResult, Sent, one, results_of, submit_input
29
+ from .webhooks import Webhooks
30
+
31
+ __all__ = ["AsyncMailset", "Mailset"]
32
+
33
+ def _many(message: Any) -> bool:
34
+ return isinstance(message, (list, tuple))
35
+
36
+
37
+ class Mailset(MailsetCommands):
38
+ """A client for one credential: send mail, and run any of Mailset's
39
+ public commands, grouped as the API is (``mailset.domains.add``,
40
+ ``mailset.threads.list``). Nothing is sent until you call a method.
41
+
42
+ With nothing given, it reads ``MAILSET_KEY``, else ``MAILSET_TOKEN``,
43
+ from the environment::
44
+
45
+ mailset = Mailset()
46
+ mailset.send({"from": "Acme <hello@example.com>", "to": "ana@example.com",
47
+ "subject": "Your code", "text": "Your code is 123456."})
48
+
49
+ One client serves a whole server, threads included. ``close()`` it (or
50
+ use it as a context manager) when you're done with it.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ key: Optional[str] = None,
56
+ token: Optional[str] = None,
57
+ *,
58
+ base_url: Optional[str] = None,
59
+ org: Optional[str] = None,
60
+ timeout: Optional[float] = None,
61
+ max_retries: Optional[int] = None,
62
+ on_approval: Optional[Callable[[Approval], None]] = None,
63
+ http_client: Optional[httpx.Client] = None,
64
+ clock: Optional[Callable[[], float]] = None,
65
+ ) -> None:
66
+ """
67
+ Args:
68
+ key: ``MAILSET_KEY`` (``msk1_…``), an app key, from ``mailset keys
69
+ create --send --mailbox <address>``: sends as the mailboxes its
70
+ grant names. An API token works here too.
71
+ token: ``MAILSET_TOKEN`` (``mst_…``), an API token, from ``mailset
72
+ tokens create``: a person's, for the commands no app key can
73
+ run, such as ``domains.add``.
74
+ base_url: Where Mailset is. Else ``MAILSET_API``, else the key's
75
+ own, else ``https://mailset.app``.
76
+ org: The org a command is about, for a person in more than one.
77
+ Each call may name another.
78
+ timeout: Seconds one try of a call may take, 30 unless told. A
79
+ try that runs out is tried again; when the last one does,
80
+ the call raises ``APITimeoutError``.
81
+ max_retries: How many times a call is tried again after a network
82
+ failure (no answer, a dropped connection, a reset), a timeout
83
+ or a 5xx, waiting ``min(8, 0.5 * 2**try)`` seconds with jitter,
84
+ or what ``Retry-After`` asks (20 at most). 2 unless told; 0
85
+ never. A 4xx is never tried again. Each try sends the same
86
+ bytes, so a send keeps its Message-ID and Mailset sends it
87
+ once, even with no ``idempotency_key``.
88
+ on_approval: Called when a command needs a passkey, with the
89
+ ``Approval`` to hand to whoever approves (its ``"url"``). The
90
+ call goes on once they do. Without it, such a command raises
91
+ ``PasskeyRequiredError`` with the ``purpose`` to approve.
92
+ http_client: Your own ``httpx.Client``, for a proxy or tests. Yours
93
+ to close.
94
+ clock: The clock every call is signed with, as ``time.time``.
95
+ Only tests change it.
96
+ """
97
+ core = SyncCore(
98
+ credential_from(key, token),
99
+ http_client=http_client,
100
+ base_url=base_url,
101
+ org=org,
102
+ timeout=timeout,
103
+ max_retries=max_retries,
104
+ on_approval=on_approval,
105
+ clock=clock,
106
+ )
107
+ super().__init__(core)
108
+ self.key = Key(core)
109
+ """This client's key: ``mailset.key.check()`` keeps it alive."""
110
+ self.approvals = Approvals(core)
111
+ """Approvals for commands that need a passkey."""
112
+ self.webhooks = Webhooks()
113
+ """Events from your org's hook: the same ``verify`` as ``mailset.webhooks``."""
114
+
115
+ def __repr__(self) -> str:
116
+ return f"Mailset({self._core.credential.name}, base_url={self._core.base_url!r})"
117
+
118
+ def close(self) -> None:
119
+ """Closes its connections (unless the ``http_client`` was yours)."""
120
+ self._core.close()
121
+
122
+ def __enter__(self) -> Mailset:
123
+ return self
124
+
125
+ def __exit__(
126
+ self,
127
+ kind: Optional[Type[BaseException]],
128
+ value: Optional[BaseException],
129
+ traceback: Optional[TracebackType],
130
+ ) -> None:
131
+ self.close()
132
+
133
+ @overload
134
+ def send(self, message: SendInput, /) -> Sent: ...
135
+
136
+ @overload
137
+ def send(self, message: Sequence[SendInput], /) -> List[SendResult]: ...
138
+
139
+ def send(
140
+ self, message: Union[SendInput, Sequence[SendInput]], /
141
+ ) -> Union[Sent, List[SendResult]]:
142
+ """Sends mail from a mailbox this key may send as.
143
+
144
+ One message, a ``SendInput`` dict, answers its ``Sent`` receipt, or
145
+ raises the ``MailsetError`` Mailset refused it with. A list of them
146
+ answers one ``Sent`` or ``NotSent`` each, in the same order, with
147
+ ``ok`` saying which went: a refusal is that message's ``error`` and
148
+ never stops the rest. A list raises only when the key is refused,
149
+ Mailset can't be reached before anything was taken, or two messages
150
+ carry the same ``idempotency_key`` from the same address
151
+ (``invalid_input``, before anything is sent). Any number goes: past
152
+ 100, or 48 MB, they go in several calls.
153
+
154
+ Mail to an Apple Hide My Email address or a temporary inbox, and
155
+ promotional mail to someone who unsubscribed, isn't refused: the
156
+ receipt's ``skipped`` names each one, and it goes to everyone else.
157
+
158
+ Args:
159
+ message: ``{"from": …, "to": …, "subject": …, "text": …}``, and
160
+ any other key of ``SendInput``; or a list of them.
161
+ """
162
+ if _many(message):
163
+ return self._send_many(message) # type: ignore[arg-type]
164
+ return one(self._send_many([message], single=True))
165
+
166
+
167
+ def _send_many(self, messages: Sequence[Any], single: bool = False) -> List[SendResult]:
168
+ batch = Batch(messages, self._core.now_ms())
169
+ first = batch.results[0] if single and batch.results else None
170
+ if first is not None and first["ok"] is False:
171
+ raise first["error"]
172
+ for chunk in batch.chunks:
173
+ built = [item for _index, item in chunk]
174
+ try:
175
+ data = self._core.call("messages.submitMany", submit_input(built))
176
+ batch.took(chunk, results_of(data, built))
177
+ except MailsetError as failure:
178
+ if single:
179
+ raise
180
+ batch.failed(chunk, failure)
181
+ return batch.answer()
182
+
183
+ def request(
184
+ self,
185
+ command: str,
186
+ input: Optional[Mapping[str, Any]] = None,
187
+ *,
188
+ org: Optional[str] = None,
189
+ approval: Optional[str] = None,
190
+ timeout: Optional[float] = None,
191
+ ) -> Any:
192
+ """Any command by its id, with its input as Mailset takes it
193
+ (camelCase): for one this SDK has no method for yet. Answers its
194
+ ``data``, as plain JSON."""
195
+ return self._core.call(
196
+ command, to_wire("", dict(input or {})), org=org, approval=approval, timeout=timeout
197
+ )
198
+
199
+
200
+ class AsyncMailset(AsyncMailsetCommands):
201
+ """``Mailset`` for asyncio: the same groups and methods, each one a
202
+ coroutine. With nothing given, it reads ``MAILSET_KEY``, else
203
+ ``MAILSET_TOKEN``, from the environment::
204
+
205
+ mailset = AsyncMailset()
206
+ await mailset.send({"from": "Acme <hello@example.com>", "to": "ana@example.com",
207
+ "subject": "Your code", "text": "Your code is 123456."})
208
+
209
+ ``await mailset.aclose()`` (or ``async with``) when you're done with it.
210
+ """
211
+
212
+ def __init__(
213
+ self,
214
+ key: Optional[str] = None,
215
+ token: Optional[str] = None,
216
+ *,
217
+ base_url: Optional[str] = None,
218
+ org: Optional[str] = None,
219
+ timeout: Optional[float] = None,
220
+ max_retries: Optional[int] = None,
221
+ on_approval: Optional[Callable[[Approval], Union[None, Awaitable[None]]]] = None,
222
+ http_client: Optional[httpx.AsyncClient] = None,
223
+ clock: Optional[Callable[[], float]] = None,
224
+ ) -> None:
225
+ """Takes what ``Mailset`` takes; ``http_client`` is an
226
+ ``httpx.AsyncClient``, and ``on_approval`` may be a coroutine."""
227
+ core = AsyncCore(
228
+ credential_from(key, token),
229
+ http_client=http_client,
230
+ base_url=base_url,
231
+ org=org,
232
+ timeout=timeout,
233
+ max_retries=max_retries,
234
+ on_approval=on_approval,
235
+ clock=clock,
236
+ )
237
+ super().__init__(core)
238
+ self.key = AsyncKey(core)
239
+ """This client's key: ``await mailset.key.check()`` keeps it alive."""
240
+ self.approvals = AsyncApprovals(core)
241
+ """Approvals for commands that need a passkey."""
242
+ self.webhooks = Webhooks()
243
+ """Events from your org's hook: the same ``verify`` as ``mailset.webhooks``."""
244
+
245
+ def __repr__(self) -> str:
246
+ return f"AsyncMailset({self._core.credential.name}, base_url={self._core.base_url!r})"
247
+
248
+ async def aclose(self) -> None:
249
+ """Closes its connections (unless the ``http_client`` was yours)."""
250
+ await self._core.close()
251
+
252
+ async def __aenter__(self) -> AsyncMailset:
253
+ return self
254
+
255
+ async def __aexit__(
256
+ self,
257
+ kind: Optional[Type[BaseException]],
258
+ value: Optional[BaseException],
259
+ traceback: Optional[TracebackType],
260
+ ) -> None:
261
+ await self.aclose()
262
+
263
+ @overload
264
+ async def send(self, message: SendInput, /) -> Sent: ...
265
+
266
+ @overload
267
+ async def send(self, message: Sequence[SendInput], /) -> List[SendResult]: ...
268
+
269
+ async def send(
270
+ self, message: Union[SendInput, Sequence[SendInput]], /
271
+ ) -> Union[Sent, List[SendResult]]:
272
+ """Sends mail from a mailbox this key may send as: one ``SendInput``
273
+ dict answers its ``Sent`` receipt, a list of them a result each. See
274
+ ``Mailset.send``."""
275
+ if _many(message):
276
+ return await self._send_many(message) # type: ignore[arg-type]
277
+ return one(await self._send_many([message], single=True))
278
+
279
+
280
+ async def _send_many(self, messages: Sequence[Any], single: bool = False) -> List[SendResult]:
281
+ batch = Batch(messages, self._core.now_ms())
282
+ first = batch.results[0] if single and batch.results else None
283
+ if first is not None and first["ok"] is False:
284
+ raise first["error"]
285
+ for chunk in batch.chunks:
286
+ built = [item for _index, item in chunk]
287
+ try:
288
+ data = await self._core.call("messages.submitMany", submit_input(built))
289
+ batch.took(chunk, results_of(data, built))
290
+ except MailsetError as failure:
291
+ if single:
292
+ raise
293
+ batch.failed(chunk, failure)
294
+ return batch.answer()
295
+
296
+ async def request(
297
+ self,
298
+ command: str,
299
+ input: Optional[Mapping[str, Any]] = None,
300
+ *,
301
+ org: Optional[str] = None,
302
+ approval: Optional[str] = None,
303
+ timeout: Optional[float] = None,
304
+ ) -> Any:
305
+ """Any command by its id, with its input as Mailset takes it
306
+ (camelCase). Answers its ``data``, as plain JSON."""
307
+ return await self._core.call(
308
+ command, to_wire("", dict(input or {})), org=org, approval=approval, timeout=timeout
309
+ )
mailset/_convert.py ADDED
@@ -0,0 +1,195 @@
1
+ """Mailset's camelCase JSON to the SDK's snake_case dicts, and back.
2
+
3
+ An object's keys are field names: ``messageId`` becomes ``message_id`` and
4
+ back, one capital at a time, and ``from`` stays ``from``. A map's keys are
5
+ data (an email address, a mailbox) and are never touched. The generated
6
+ ``_schema`` says which is which, type by type, and what a field an answer
7
+ left out reads as; the hand-written types say it here. ``to_api`` and
8
+ ``from_api`` are the same conversion, for your own use.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import collections.abc as abc
14
+ import copy
15
+ import re
16
+ import typing
17
+ from datetime import datetime
18
+ from functools import lru_cache
19
+ from typing import Any, Dict, FrozenSet, Mapping, Optional, Tuple
20
+
21
+ from ._errors import MailsetError
22
+ from ._schema import DEFAULTS, SCHEMA
23
+
24
+ __all__ = ["from_api", "to_api"]
25
+
26
+ _capital = re.compile(r"[A-Z]")
27
+ _underscored = re.compile(r"_([a-z])")
28
+
29
+
30
+ def snake(name: str) -> str:
31
+ """``messageId`` as ``message_id``; a name with no capital stays as it is."""
32
+ return _capital.sub(lambda match: "_" + match.group(0).lower(), name)
33
+
34
+
35
+ def camel(name: str) -> str:
36
+ """``message_id`` as ``messageId``; a camelCase name stays as it is."""
37
+ return _underscored.sub(lambda match: match.group(1).upper(), name)
38
+
39
+
40
+ HAND: Dict[str, Dict[str, str]] = {}
41
+ """The hand-written types' fields that hold objects, in the shape of ``SCHEMA``."""
42
+
43
+ _named: Dict[int, Tuple[Any, str]] = {}
44
+
45
+
46
+ def register(tp: Any, name: str, fields: Optional[Dict[str, str]] = None) -> None:
47
+ """Names a hand-written type for ``to_api`` and ``from_api``, and says
48
+ which of its fields hold objects (camelCase field: spec)."""
49
+ HAND[name] = fields or {}
50
+ _named[id(tp)] = (tp, name)
51
+
52
+
53
+ def _fields(name: str) -> Dict[str, str]:
54
+ return HAND.get(name) or SCHEMA.get(name) or {}
55
+
56
+
57
+ @lru_cache(maxsize=None)
58
+ def _parsed(spec: str) -> Tuple[str, str]:
59
+ """A spec as its kind (``object``, ``list``, ``map``, ``plain``) and what's inside."""
60
+ spec = spec.lstrip("?")
61
+ if not spec:
62
+ return ("plain", "")
63
+ if spec.startswith("["):
64
+ return ("list", spec[1:-1])
65
+ if spec.startswith("{"):
66
+ return ("map", spec[1:-1])
67
+ return ("object", spec)
68
+
69
+
70
+ def _plain(value: Any) -> Any:
71
+ """A value the types say nothing about, as JSON takes it: datetimes as ms."""
72
+ if isinstance(value, datetime):
73
+ return round(value.timestamp() * 1000)
74
+ if isinstance(value, MailsetError):
75
+ return value.to_dict()
76
+ if isinstance(value, Mapping):
77
+ return {key: _plain(inner) for key, inner in value.items()}
78
+ if isinstance(value, (list, tuple)):
79
+ return [_plain(inner) for inner in value]
80
+ return value
81
+
82
+
83
+ def from_wire(spec: str, value: Any) -> Any:
84
+ """Mailset's JSON as the SDK's dicts, the spec saying where keys are names."""
85
+ kind, inner = _parsed(spec)
86
+ if kind == "plain" or value is None:
87
+ return value
88
+ if kind == "list":
89
+ return [from_wire(inner, item) for item in value] if isinstance(value, list) else value
90
+ if kind == "map":
91
+ if not isinstance(value, dict):
92
+ return value
93
+ return {key: from_wire(inner, item) for key, item in value.items()}
94
+ if not isinstance(value, dict):
95
+ return value
96
+ fields = _fields(inner)
97
+ out = {snake(key): from_wire(fields.get(key, ""), item) for key, item in value.items()}
98
+ # A field Mailset left out (a server from before it) reads as its default.
99
+ for key, default in DEFAULTS.get(inner, {}).items():
100
+ if key not in value:
101
+ out[snake(key)] = copy.deepcopy(default)
102
+ return out
103
+
104
+
105
+ def to_wire(spec: str, value: Any, *, given: bool = False) -> Any:
106
+ """The SDK's dicts as Mailset's JSON. ``given``: an input, whose ``None``
107
+ is left out unless its field takes null."""
108
+ kind, inner = _parsed(spec)
109
+ if value is None:
110
+ return None
111
+ if kind == "plain":
112
+ return _plain(value)
113
+ if kind == "list":
114
+ if isinstance(value, (list, tuple)):
115
+ return [to_wire(inner, item, given=given) for item in value]
116
+ return _plain(value)
117
+ if kind == "map":
118
+ if not isinstance(value, Mapping):
119
+ return _plain(value)
120
+ return {key: to_wire(inner, item, given=given) for key, item in value.items()}
121
+ if isinstance(value, MailsetError):
122
+ return value.to_dict()
123
+ if not isinstance(value, Mapping):
124
+ return _plain(value)
125
+ fields = _fields(inner)
126
+ out: Dict[str, Any] = {}
127
+ for key, item in value.items():
128
+ name = camel(str(key))
129
+ field = fields.get(name, "")
130
+ if item is None and given and not field.startswith("?"):
131
+ continue
132
+ out[name] = to_wire(field, item, given=given)
133
+ return out
134
+
135
+
136
+ def _is_typed_dict(tp: Any) -> bool:
137
+ return isinstance(tp, type) and issubclass(tp, dict) and hasattr(tp, "__total__")
138
+
139
+
140
+ def _spec_of(tp: Any) -> str:
141
+ """The spec of a type: a generated or registered TypedDict, a ``List``
142
+ or ``Dict`` of one, or a ``Union`` of them (their fields together)."""
143
+ if tp is None or tp is Any:
144
+ return ""
145
+ if isinstance(tp, str):
146
+ return tp
147
+ found = _named.get(id(tp))
148
+ if found is not None and found[0] is tp:
149
+ return found[1]
150
+ if _is_typed_dict(tp):
151
+ name = tp.__name__
152
+ return name if name in SCHEMA or name in _generated_names() else ""
153
+ origin = typing.get_origin(tp)
154
+ args = typing.get_args(tp)
155
+ if origin in (list, tuple, abc.Sequence):
156
+ inner = _spec_of(args[0]) if args else ""
157
+ return f"[{inner}]" if inner else ""
158
+ if origin in (dict, abc.Mapping):
159
+ inner = _spec_of(args[1]) if len(args) == 2 else ""
160
+ return f"{{{inner}}}" if inner else ""
161
+ if origin is typing.Union:
162
+ members = [_spec_of(arg) for arg in args if arg is not type(None)]
163
+ objects = [member for member in members if member and _parsed(member)[0] == "object"]
164
+ if len(objects) > 1:
165
+ merged = "|".join(objects)
166
+ if merged not in HAND:
167
+ HAND[merged] = {}
168
+ for member in objects:
169
+ for field, spec in _fields(member).items():
170
+ HAND[merged].setdefault(field, spec)
171
+ return merged
172
+ return next((member for member in members if member), "")
173
+ return ""
174
+
175
+
176
+ @lru_cache(maxsize=1)
177
+ def _generated_names() -> FrozenSet[str]:
178
+ from . import types
179
+
180
+ return frozenset(types.__all__)
181
+
182
+
183
+ def to_api(value: Any, tp: Any) -> Any:
184
+ """An answer (or an input) of the type ``tp`` as Mailset's JSON:
185
+ camelCase names, a map's own keys untouched. ``tp`` is one of
186
+ ``mailset.types``, a ``List[…]`` or ``Dict[str, …]`` of one, or a
187
+ hand-written type such as ``mailset.Sent``. Useful to store an answer
188
+ as Mailset sent it."""
189
+ return to_wire(_spec_of(tp), value)
190
+
191
+
192
+ def from_api(value: Any, tp: Any) -> Any:
193
+ """Mailset's JSON as the SDK's dicts of the type ``tp``: what every
194
+ method does to its answer, for JSON you kept."""
195
+ return from_wire(_spec_of(tp), value)