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.
@@ -0,0 +1,609 @@
1
+ """The commands every SDK writes by hand, natively, instead of generating
2
+ them: ``delivery.search`` (dates as Python has them, its lines), and
3
+ ``campaigns.submit`` and ``sending.submit`` (messages built from their
4
+ fields, never base64 from the caller). The generated groups of
5
+ ``_resources`` take these methods from the classes here; ``key`` and
6
+ ``approvals`` sit on the client itself."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ from datetime import date, datetime, timezone
12
+ from typing import (
13
+ TYPE_CHECKING,
14
+ AbstractSet,
15
+ Any,
16
+ Dict,
17
+ List,
18
+ Literal,
19
+ Mapping,
20
+ Optional,
21
+ Sequence,
22
+ Union,
23
+ )
24
+
25
+ from . import types as _t
26
+ from ._base import AsyncGroup, SyncGroup
27
+ from ._convert import camel, from_wire, register
28
+ from ._errors import PasskeyPurpose, malformed, refused
29
+ from ._message import (
30
+ MESSAGE_KEYS,
31
+ Address,
32
+ Attachment,
33
+ Recipients,
34
+ build_message,
35
+ fields_of,
36
+ keys_of,
37
+ )
38
+ from ._typing import NotRequired, Required, TypedDict
39
+
40
+ if TYPE_CHECKING:
41
+ from ._core import Approval, AsyncCore, SyncCore
42
+
43
+ __all__ = [
44
+ "CampaignMessage",
45
+ "CampaignSubmitInput",
46
+ "DeliveryLine",
47
+ "DeliveryPage",
48
+ "DeliverySearchInput",
49
+ "DeliveryStatus",
50
+ "SendingSubmitInput",
51
+ "Track",
52
+ ]
53
+
54
+ DeliveryStatus = Literal[
55
+ "sent", "delivered", "delayed", "bounced", "complained", "rejected", "expired", "skipped"
56
+ ]
57
+ """What became of a message for one recipient. ``sent``: Mailset handed it
58
+ on. ``delivered``: the recipient's server took it. ``delayed``: that server
59
+ asked to try later, and it will be. ``bounced``: it came back.
60
+ ``complained``: the recipient marked it as spam. ``rejected``: it was refused
61
+ before it left. ``expired``: its ``deliver_by`` came while it waited.
62
+ ``skipped``: Mailset left the address out on purpose (see ``Sent``'s
63
+ ``skipped``)."""
64
+
65
+ Moment = Union[datetime, date, int, str]
66
+ """A ``datetime``, a ``date`` (a whole day in UTC), ms since the epoch, or
67
+ text Mailset reads: an ISO time, or a day as ``2026-11-30``."""
68
+
69
+
70
+ class DeliverySearchInput(TypedDict, total=False):
71
+ """Which lines of the delivery log to find. Every key narrows the
72
+ search; with none, you get the newest lines."""
73
+
74
+ id: str
75
+ """Only the lines of one send: the ``id`` its receipt answered."""
76
+
77
+ message_id: str
78
+ """Only the lines of the message with this Message-ID, the ``message_id``
79
+ its receipt answered."""
80
+
81
+ recipient: str
82
+ """A recipient's whole address, or part of one, such as ``@example.org``."""
83
+
84
+ sender: str
85
+ """One of the addresses this key sends as, or part of one."""
86
+
87
+ status: DeliveryStatus
88
+ """Only lines with this status."""
89
+
90
+ since: Moment
91
+ """From this moment on. A day counts from its start in UTC."""
92
+
93
+ until: Moment
94
+ """Up to this moment. A day counts to its end in UTC."""
95
+
96
+ limit: int
97
+ """How many lines a page holds, 1 to 200. 50 unless told."""
98
+
99
+ cursor: str
100
+ """The ``next`` of the page before, for the page after it."""
101
+
102
+
103
+ class DeliveryLine(TypedDict):
104
+ """One recipient's line in the delivery log: a message to three people
105
+ has three. Addresses and outcomes only, never a subject or anything from
106
+ the body."""
107
+
108
+ id: str
109
+ at: int
110
+ """When it happened, in ms since the epoch."""
111
+
112
+ sender: Optional[str]
113
+ """Who sent it: for a mailbox key, the mailbox it left from, whichever of
114
+ its addresses was in From; for a domain key, the From address."""
115
+
116
+ recipient: str
117
+ status: Union[DeliveryStatus, str]
118
+ reason: Optional[str]
119
+ """Why, in words for people, when the status needs saying why."""
120
+
121
+ message: NotRequired[str]
122
+ """The send this line is about: the ``id`` its receipt answered."""
123
+
124
+ message_id: NotRequired[str]
125
+ """Its Message-ID header, without the angle brackets: ``message_id`` from
126
+ ``send``."""
127
+
128
+ client: Optional[_t.DeliveryClient]
129
+ """Which client sent it, from the ``Mailset-Client`` header its request
130
+ carried: ``name`` is one of Mailset's SDKs by its language, ``cli``,
131
+ ``web``, ``ios`` or ``other``, and ``version`` its version. None when its
132
+ request named none."""
133
+
134
+
135
+ class DeliveryPage(TypedDict):
136
+ """One page of the delivery log, newest first."""
137
+
138
+ lines: List[DeliveryLine]
139
+ next: Optional[str]
140
+ """Pass it back as ``cursor`` for the next page. None on the last one."""
141
+
142
+
143
+ register(DeliveryLine, "_DeliveryLine", {"client": "DeliveryClient"})
144
+ register(DeliveryPage, "_DeliveryPage", {"lines": "[_DeliveryLine]"})
145
+ register(DeliverySearchInput, "_DeliverySearchInput")
146
+
147
+
148
+ def _moment(value: Any, what: str) -> Union[int, str, None]:
149
+ if value is None or isinstance(value, (int, str)) and not isinstance(value, bool):
150
+ return value
151
+ if isinstance(value, datetime):
152
+ return round(value.timestamp() * 1000)
153
+ if isinstance(value, date):
154
+ return value.isoformat()
155
+ raise refused(f"{what} takes a datetime, a date, ms, or text like 2026-11-30.")
156
+
157
+
158
+ _SEARCH_KEYS = ("id", "message_id", "recipient", "sender", "status", "since", "until", "limit", "cursor")
159
+
160
+
161
+ def _search_input(params: Optional[Mapping[str, Any]]) -> Dict[str, Any]:
162
+ given = keys_of(params or {})
163
+ unknown = set(given) - set(_SEARCH_KEYS)
164
+ if unknown:
165
+ raise refused(f"delivery.search takes no {', '.join(sorted(unknown))}.")
166
+ search = {name: given.get(name) for name in _SEARCH_KEYS}
167
+ search["since"] = _moment(search["since"], "since")
168
+ search["until"] = _moment(search["until"], "until")
169
+ return {camel(name): value for name, value in search.items() if value is not None}
170
+
171
+
172
+ def _line_of(value: Any) -> DeliveryLine:
173
+ if (
174
+ not isinstance(value, dict)
175
+ or not isinstance(value.get("id"), str)
176
+ or not isinstance(value.get("at"), (int, float))
177
+ or not isinstance(value.get("recipient"), str)
178
+ or not isinstance(value.get("status"), str)
179
+ ):
180
+ raise malformed(command="delivery.search")
181
+ sender, reason = value.get("sender"), value.get("reason")
182
+ line = DeliveryLine(
183
+ id=value["id"],
184
+ at=int(value["at"]),
185
+ sender=sender if isinstance(sender, str) else None,
186
+ recipient=value["recipient"],
187
+ # A status this version doesn't know still shows, as Mailset names it.
188
+ status=value["status"],
189
+ reason=reason if isinstance(reason, str) else None,
190
+ client=_client_of(value.get("client")),
191
+ )
192
+ if isinstance(value.get("message"), str):
193
+ line["message"] = value["message"]
194
+ if isinstance(value.get("messageId"), str):
195
+ line["message_id"] = value["messageId"]
196
+ return line
197
+
198
+
199
+ def _client_of(value: Any) -> Optional[_t.DeliveryClient]:
200
+ """A line's client, or None for none, or for one that doesn't read."""
201
+ if not isinstance(value, dict) or not isinstance(value.get("name"), str):
202
+ return None
203
+ version = value.get("version")
204
+ # A name this version doesn't know still shows, as Mailset names it.
205
+ return _t.DeliveryClient(name=value["name"], version=version if isinstance(version, str) else None)
206
+
207
+
208
+ def _page_of(data: Any) -> DeliveryPage:
209
+ if not isinstance(data, dict) or not isinstance(data.get("events"), list):
210
+ raise malformed(command="delivery.search")
211
+ following = data.get("next")
212
+ return DeliveryPage(
213
+ lines=[_line_of(line) for line in data["events"]],
214
+ next=following if isinstance(following, str) else None,
215
+ )
216
+
217
+
218
+ class DeliveryHand(SyncGroup):
219
+ """``mailset.delivery``: what became of the mail this key sent."""
220
+
221
+ def search(
222
+ self,
223
+ params: Optional[DeliverySearchInput] = None,
224
+ *,
225
+ org: Optional[str] = None,
226
+ timeout: Optional[float] = None,
227
+ ) -> DeliveryPage:
228
+ """Finds what became of the mail this key sent (``delivery.search``),
229
+ one line per recipient, newest first.
230
+
231
+ A key sees only what left the mailbox it sends as, or for a domain
232
+ key the addresses it sends as, so a search by ``recipient`` answers
233
+ "did Ana get her receipt?" and nothing about anyone else's mail. For each change as it happens, use the hook
234
+ instead: see ``webhooks``.
235
+
236
+ Args:
237
+ params: A ``DeliverySearchInput`` dict (``id``, ``message_id``,
238
+ ``recipient``, ``sender``, ``status``, ``since``, ``until``,
239
+ ``limit``, ``cursor``). Each key narrows the search; with
240
+ none, the newest lines. ``id`` or ``message_id`` from a
241
+ receipt finds that send's lines.
242
+ org: The org it is about, for a person in more than one.
243
+ timeout: Seconds one try may take, for this call alone.
244
+
245
+ Returns:
246
+ A ``DeliveryPage``: its ``lines``, and ``next``, the ``cursor``
247
+ of the page after it.
248
+ """
249
+ data = self._core.call(
250
+ "delivery.search", _search_input(params), org=org, timeout=timeout
251
+ )
252
+ return _page_of(data)
253
+
254
+
255
+ class AsyncDeliveryHand(AsyncGroup):
256
+ """``mailset.delivery``: what became of the mail this key sent."""
257
+
258
+ async def search(
259
+ self,
260
+ params: Optional[DeliverySearchInput] = None,
261
+ *,
262
+ org: Optional[str] = None,
263
+ timeout: Optional[float] = None,
264
+ ) -> DeliveryPage:
265
+ """Finds what became of the mail this key sent (``delivery.search``),
266
+ one line per recipient, newest first. See ``Mailset.delivery.search``."""
267
+ data = await self._core.call(
268
+ "delivery.search", _search_input(params), org=org, timeout=timeout
269
+ )
270
+ return _page_of(data)
271
+
272
+
273
+ class Track(TypedDict, total=False):
274
+ """What to track on a campaign's message. Only a domain with a tracking
275
+ domain can. Nothing unless told."""
276
+
277
+ opens: bool
278
+ clicks: bool
279
+
280
+
281
+ CampaignMessage = TypedDict(
282
+ "CampaignMessage",
283
+ {
284
+ "campaign": Required[str],
285
+ "recipient": Required[str],
286
+ "from": Address,
287
+ "to": Recipients,
288
+ "subject": str,
289
+ "text": str,
290
+ "cc": Recipients,
291
+ "bcc": Recipients,
292
+ "reply_to": Recipients,
293
+ "html": str,
294
+ "attachments": Sequence[Attachment],
295
+ "headers": Mapping[str, str],
296
+ "raw": Union[str, bytes],
297
+ "track": Track,
298
+ },
299
+ total=False,
300
+ )
301
+ """One recipient's message of a campaign: its fields, which the SDK builds
302
+ into the message (as ``send`` does), or ``raw``, a whole message you built
303
+ yourself, as text or bytes, never base64.
304
+
305
+ Keys:
306
+ campaign: Your own id for the campaign: 1 to 64 letters, digits, - or _.
307
+ It comes back on every event.
308
+ recipient: Your own id for the recipient, in the same form. It comes back
309
+ on every event.
310
+ from: An address at the sending domain.
311
+ to, subject, text, cc, bcc, reply_to, html, attachments, headers: As in
312
+ ``SendInput``.
313
+ raw: A whole RFC 5322 message, instead of the fields.
314
+ track: What to track: ``{"opens": True, "clicks": True}``. Nothing unless told.
315
+ """
316
+
317
+
318
+ class CampaignSubmitInput(TypedDict):
319
+ """What ``campaigns.submit`` takes: a sending domain and its messages."""
320
+
321
+ domain: str
322
+ """The sending domain the messages go from."""
323
+
324
+ messages: Sequence[CampaignMessage]
325
+ """Any number: past 100 they go in several calls, and the results stay in order."""
326
+
327
+
328
+ SendingSubmitInput = TypedDict(
329
+ "SendingSubmitInput",
330
+ {
331
+ "domain": Required[str],
332
+ "ref": Required[str],
333
+ "recipients": Sequence[str],
334
+ "from": Address,
335
+ "to": Recipients,
336
+ "subject": str,
337
+ "text": str,
338
+ "cc": Recipients,
339
+ "bcc": Recipients,
340
+ "reply_to": Recipients,
341
+ "html": str,
342
+ "attachments": Sequence[Attachment],
343
+ "headers": Mapping[str, str],
344
+ "raw": Union[str, bytes],
345
+ },
346
+ total=False,
347
+ )
348
+ """What ``sending.submit`` takes: one message from a sending domain, such as
349
+ a support reply, built from its fields (as ``send`` does) or ``raw``.
350
+
351
+ Keys:
352
+ domain: The sending domain the message goes from.
353
+ ref: Your own id for the message: 1 to 64 letters, digits, - or _. It
354
+ comes back on its events.
355
+ recipients: Who it goes to. Left out, everyone it names in To, Cc and Bcc.
356
+ from: An address at the sending domain.
357
+ to, subject, text, cc, bcc, reply_to, html, attachments, headers: As in
358
+ ``SendInput``.
359
+ raw: A whole RFC 5322 message, as text or bytes, instead of the fields.
360
+ """
361
+
362
+ register(CampaignMessage, "_CampaignMessage")
363
+ register(CampaignSubmitInput, "_CampaignSubmitInput")
364
+ register(SendingSubmitInput, "_SendingSubmitInput")
365
+
366
+ MAX_CAMPAIGN_MESSAGES = 100
367
+ """The most messages one ``campaigns.submit`` takes."""
368
+
369
+ _CAMPAIGN_KEYS = MESSAGE_KEYS | {"campaign", "recipient", "raw", "track"}
370
+ _SENDING_KEYS = MESSAGE_KEYS | {"domain", "ref", "recipients", "raw"}
371
+
372
+
373
+ def _raw_of(given: Mapping[str, Any], now_ms: int) -> str:
374
+ """A message as ``campaigns.submit`` and ``sending.submit`` take it:
375
+ base64 of the whole message, built from its fields unless it came whole."""
376
+ raw = given.get("raw")
377
+ if raw is not None:
378
+ data = raw.encode("utf-8") if isinstance(raw, str) else bytes(raw)
379
+ return base64.b64encode(data).decode("ascii")
380
+ fields = {name: value for name, value in given.items() if name in MESSAGE_KEYS}
381
+ built = build_message(
382
+ fields_of(fields, MESSAGE_KEYS), # type: ignore[arg-type]
383
+ now=datetime.fromtimestamp(now_ms / 1000, timezone.utc),
384
+ )
385
+ return base64.b64encode(built["raw"]).decode("ascii")
386
+
387
+
388
+ def _checked(value: Any, keys: AbstractSet[str], what: str) -> Dict[str, Any]:
389
+ if not isinstance(value, Mapping):
390
+ raise refused(f"{what} is a dict of its fields.")
391
+ given = {key: inner for key, inner in keys_of(value).items() if inner is not None}
392
+ unknown = set(given) - keys
393
+ if unknown:
394
+ raise refused(f"{what} has no {', '.join(sorted(unknown))}.")
395
+ return given
396
+
397
+
398
+ def _campaign_input(message: Any, now_ms: int) -> Dict[str, Any]:
399
+ given = _checked(message, _CAMPAIGN_KEYS, "A campaign message")
400
+ track = given.get("track")
401
+ track = track if isinstance(track, Mapping) else {}
402
+ return {
403
+ "raw": _raw_of(given, now_ms),
404
+ "campaign": given.get("campaign"),
405
+ "recipient": given.get("recipient"),
406
+ "track": {"opens": bool(track.get("opens")), "clicks": bool(track.get("clicks"))},
407
+ }
408
+
409
+
410
+ def _sending_input(params: Any, now_ms: int) -> Dict[str, Any]:
411
+ given = _checked(params, _SENDING_KEYS, "sending.submit's input")
412
+ body: Dict[str, Any] = {
413
+ "domain": given.get("domain"),
414
+ "ref": given.get("ref"),
415
+ "raw": _raw_of(given, now_ms),
416
+ }
417
+ if given.get("recipients") is not None:
418
+ body["recipients"] = list(given["recipients"])
419
+ return body
420
+
421
+
422
+ def _campaign_calls(params: Any, now_ms: int) -> List[Dict[str, Any]]:
423
+ given = _checked(params, frozenset({"domain", "messages"}), "campaigns.submit's input")
424
+ messages = [_campaign_input(message, now_ms) for message in given.get("messages") or []]
425
+ return [
426
+ {"domain": given.get("domain"), "messages": messages[start : start + MAX_CAMPAIGN_MESSAGES]}
427
+ for start in range(0, len(messages), MAX_CAMPAIGN_MESSAGES)
428
+ ]
429
+
430
+
431
+ def _results(answer: Any) -> List[Any]:
432
+ if not isinstance(answer, dict) or not isinstance(answer.get("results"), list):
433
+ raise malformed(command="campaigns.submit")
434
+ return list(answer["results"])
435
+
436
+
437
+ class CampaignsHand(SyncGroup):
438
+ """``mailset.campaigns``: campaign mail, from a campaigns key."""
439
+
440
+ def submit(
441
+ self,
442
+ params: CampaignSubmitInput,
443
+ *,
444
+ org: Optional[str] = None,
445
+ timeout: Optional[float] = None,
446
+ ) -> _t.CampaignSubmitted:
447
+ """Sends a campaign's messages, one per recipient, from a sending
448
+ domain (``campaigns.submit``). Each message is built from its fields
449
+ here. Any number: past 100 they go in several calls, and the results
450
+ stay in order: ``queued``, or ``refused`` with why. It needs a
451
+ campaigns key (``mailset keys create --campaigns``).
452
+
453
+ Args:
454
+ params: A ``CampaignSubmitInput``: ``domain``, the sending domain,
455
+ and ``messages``, ``CampaignMessage`` dicts.
456
+ org: The org it is about, for a person in more than one.
457
+ timeout: Seconds one try may take, for each call.
458
+ """
459
+ results: List[Any] = []
460
+ for call in _campaign_calls(params, self._core.now_ms()):
461
+ answer = self._core.call("campaigns.submit", call, org=org, timeout=timeout)
462
+ results.extend(_results(answer))
463
+ submitted: _t.CampaignSubmitted = from_wire("CampaignSubmitted", {"results": results})
464
+ return submitted
465
+
466
+
467
+ class AsyncCampaignsHand(AsyncGroup):
468
+ """``mailset.campaigns``: campaign mail, from a campaigns key."""
469
+
470
+ async def submit(
471
+ self,
472
+ params: CampaignSubmitInput,
473
+ *,
474
+ org: Optional[str] = None,
475
+ timeout: Optional[float] = None,
476
+ ) -> _t.CampaignSubmitted:
477
+ """Sends a campaign's messages, one per recipient, from a sending
478
+ domain (``campaigns.submit``). See ``Mailset.campaigns.submit``."""
479
+ results: List[Any] = []
480
+ for call in _campaign_calls(params, self._core.now_ms()):
481
+ answer = await self._core.call("campaigns.submit", call, org=org, timeout=timeout)
482
+ results.extend(_results(answer))
483
+ submitted: _t.CampaignSubmitted = from_wire("CampaignSubmitted", {"results": results})
484
+ return submitted
485
+
486
+
487
+ class SendingHand(SyncGroup):
488
+ """``mailset.sending``: sending domains, and one message from one."""
489
+
490
+ def submit(
491
+ self,
492
+ params: SendingSubmitInput,
493
+ *,
494
+ org: Optional[str] = None,
495
+ timeout: Optional[float] = None,
496
+ ) -> _t.SendingSubmitted:
497
+ """Sends one message from a sending domain, the way a reply goes,
498
+ never tracked (``sending.submit``). The message is built from its
499
+ fields here, or ``raw`` is one built elsewhere. Answers each envelope
500
+ address: ``queued`` or ``refused``.
501
+
502
+ Args:
503
+ params: A ``SendingSubmitInput``: ``domain``, ``ref``, maybe
504
+ ``recipients``, and the message's fields or ``raw``.
505
+ org: The org it is about, for a person in more than one.
506
+ timeout: Seconds one try may take, for this call alone.
507
+ """
508
+ answer = self._core.call(
509
+ "sending.submit",
510
+ _sending_input(params, self._core.now_ms()),
511
+ org=org,
512
+ timeout=timeout,
513
+ )
514
+ submitted: _t.SendingSubmitted = from_wire("SendingSubmitted", answer)
515
+ return submitted
516
+
517
+
518
+ class AsyncSendingHand(AsyncGroup):
519
+ """``mailset.sending``: sending domains, and one message from one."""
520
+
521
+ async def submit(
522
+ self,
523
+ params: SendingSubmitInput,
524
+ *,
525
+ org: Optional[str] = None,
526
+ timeout: Optional[float] = None,
527
+ ) -> _t.SendingSubmitted:
528
+ """Sends one message from a sending domain, the way a reply goes
529
+ (``sending.submit``). See ``Mailset.sending.submit``."""
530
+ answer = await self._core.call(
531
+ "sending.submit",
532
+ _sending_input(params, self._core.now_ms()),
533
+ org=org,
534
+ timeout=timeout,
535
+ )
536
+ submitted: _t.SendingSubmitted = from_wire("SendingSubmitted", answer)
537
+ return submitted
538
+
539
+
540
+ class Key:
541
+ """``mailset.key``: this client's ``MAILSET_KEY``."""
542
+
543
+ def __init__(self, core: SyncCore) -> None:
544
+ self._core = core
545
+
546
+ def check(self, *, timeout: Optional[float] = None) -> _t.KeyStatus:
547
+ """Proves the key still works and keeps it alive (``grants.current``):
548
+ a key unused for 90 days stops. Call it when your server starts and
549
+ once a day, so a product that sends rarely never loses its key, and a
550
+ revoked one shows up in your logs before a customer misses an email."""
551
+ status: _t.KeyStatus = self._core.command(
552
+ "grants.current", None, "", "KeyStatus", None, None, timeout
553
+ )
554
+ return status
555
+
556
+
557
+ class AsyncKey:
558
+ """``mailset.key``: this client's ``MAILSET_KEY``."""
559
+
560
+ def __init__(self, core: AsyncCore) -> None:
561
+ self._core = core
562
+
563
+ async def check(self, *, timeout: Optional[float] = None) -> _t.KeyStatus:
564
+ """Proves the key still works and keeps it alive (``grants.current``).
565
+ See ``Mailset.key.check``."""
566
+ status: _t.KeyStatus = await self._core.command(
567
+ "grants.current", None, "", "KeyStatus", None, None, timeout
568
+ )
569
+ return status
570
+
571
+
572
+ class Approvals:
573
+ """``mailset.approvals``: for commands that need a passkey. Only an API
574
+ token can ask for one, since a person approves it."""
575
+
576
+ def __init__(self, core: SyncCore) -> None:
577
+ self._core = core
578
+
579
+ def request(self, purpose: PasskeyPurpose) -> Approval:
580
+ """Opens an approval for what a ``step_up_required`` error named:
581
+ pass its ``purpose``. Hand the answer's ``url`` to whoever approves."""
582
+ return self._core.request_approval(purpose)
583
+
584
+ def wait(
585
+ self, approval: Union[Approval, str], *, timeout: float = 600.0, every: float = 2.0
586
+ ) -> str:
587
+ """Waits until it's approved, asking every ``every`` seconds, and
588
+ answers the id to pass as ``approval``. Raises
589
+ ``PermissionDeniedError`` when it's refused or expires, and
590
+ ``MailsetError`` (``expired``) after ``timeout`` seconds."""
591
+ return self._core.wait_approval(approval, timeout=timeout, every=every)
592
+
593
+
594
+ class AsyncApprovals:
595
+ """``mailset.approvals``: for commands that need a passkey."""
596
+
597
+ def __init__(self, core: AsyncCore) -> None:
598
+ self._core = core
599
+
600
+ async def request(self, purpose: PasskeyPurpose) -> Approval:
601
+ """Opens an approval for what a ``step_up_required`` error named."""
602
+ return await self._core.request_approval(purpose)
603
+
604
+ async def wait(
605
+ self, approval: Union[Approval, str], *, timeout: float = 600.0, every: float = 2.0
606
+ ) -> str:
607
+ """Waits until it's approved, and answers the id to pass as ``approval``."""
608
+ return await self._core.wait_approval(approval, timeout=timeout, every=every)
609
+