@yolk-sdk/emulators 0.1.0-canary.100 → 0.1.0-canary.101

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.
package/README.md CHANGED
@@ -1599,10 +1599,10 @@ GitHub case, only to prove that case catches it.
1599
1599
 
1600
1600
  `await makeGoogleEmulator(options?)` returns
1601
1601
  `{ fetch, fetchOn, ledger, faults, reset, seed, snapshot, coverage, close }`. Each call has its own
1602
- state; `await close()` when done. It emulates only the Gmail, Calendar, and Drive routes the
1603
- thirteen Google conformance cases (with their cleanup) send, so the Google connector actions and the
1604
- cases run unchanged against it, the irreversible practice send included. Each route answers only on
1605
- the origin its fixtures record: Gmail (the API and the multipart send upload) on
1602
+ state; `await close()` when done. It emulates only the Gmail, Calendar, and Drive routes the fifteen
1603
+ Google conformance cases (with their cleanup) send, so the Google connector actions and the cases
1604
+ run unchanged against it, the irreversible practice send included. Each route answers only on the
1605
+ origin its fixtures record: Gmail (the API and the multipart send upload) on
1606
1606
  `https://gmail.googleapis.com` (`googleEmulatorGmailOrigin`), Calendar and Drive on
1607
1607
  `https://www.googleapis.com` (`googleEmulatorApisOrigin`). `fetch` takes the origin from the request
1608
1608
  URL (in-process routing keeps it); behind a loopback rewrite, which loses it, serve
@@ -1636,23 +1636,24 @@ the live runner turns that into its lookup-failed `WARN`.
1636
1636
  Routes (every request needs `Authorization: Bearer <token>`, a recognisable bearer; bodies are
1637
1637
  JSON unless noted; Drive requests also send `accept: application/json`, as recorded):
1638
1638
 
1639
- | Route | Behavior |
1640
- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
1641
- | `GET /gmail/v1/users/me/messages` | `labelIds`, `maxResults`, `pageToken`: `{ messages: [{ id, threadId }], nextPageToken? }` |
1642
- | `GET /gmail/v1/users/me/messages/{messageId}` | `format=minimal`, `metadata`, or `full`, as recorded for that message; the recorded 404 |
1643
- | `GET /gmail/v1/users/me/messages/{messageId}/attachments/{id}` | `{ size, data }` (base64url) of a seeded attachment |
1644
- | `POST /gmail/v1/users/me/messages/{messageId}/modify` | `{ addLabelIds: [<created label>] }`: `{ id, threadId, labelIds }` |
1645
- | `POST /gmail/v1/users/me/messages/{messageId}/trash`, `/untrash` | No body: adds or removes `TRASH`, answering `{ id, threadId, labelIds }` |
1646
- | `POST /gmail/v1/users/me/labels` | `{ name: "yolk-conformance <runId> label" }`: the created user label (`Label_9101` first) |
1647
- | `GET`, `DELETE /gmail/v1/users/me/labels/{labelId}` | Delete a created label (204; it leaves every message); a read of an absent label answers 404 |
1648
- | `POST /gmail/v1/users/me/drafts`, `PUT .../drafts/{draftId}` | The recorded run draft without recipients: `{ id, message: { id, threadId, labelIds } }` |
1649
- | `DELETE /gmail/v1/users/me/drafts/{draftId}` | 204 (the draft and its message go); an absent draft answers the recorded 404 |
1650
- | `GET /gmail/v1/users/me/threads/{threadId}` | `format=full`: a draft thread created here |
1651
- | `POST /upload/gmail/v1/users/me/messages/send` | `uploadType=multipart`, `multipart/related`: the practice message only (see below) |
1652
- | `GET`, `POST /calendar/v3/calendars/{calendarId}/events` | Range listing (`singleEvents=true`, `orderBy=startTime`) with page tokens; the run event |
1653
- | `GET`, `PATCH`, `DELETE .../events/{eventId}` | Read (cancelled too), the recorded rename, delete to `cancelled` (204), then the recorded 410 |
1654
- | `GET`, `POST /drive/v3/files` | Folder listing (`'<folder>' in parents and trashed = false`) with page tokens; the run folder |
1655
- | `GET`, `PATCH`, `DELETE /drive/v3/files/{fileId}` | Read with the connector `fields` (absent: the recorded 404), `{ trashed: true }`, delete 204 |
1639
+ | Route | Behavior |
1640
+ | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
1641
+ | `GET /gmail/v1/users/me/messages` | `labelIds`, `maxResults`, `pageToken`: `{ messages: [{ id, threadId }], nextPageToken? }` |
1642
+ | `GET /gmail/v1/users/me/threads` | `labelIds`, `maxResults`, `pageToken`: `{ threads: [{ id, snippet, historyId }], nextPageToken? }` |
1643
+ | `GET /gmail/v1/users/me/messages/{messageId}` | `format=minimal`, `metadata` (optional `metadataHeaders`), or `full`, as recorded; the recorded 404 |
1644
+ | `GET /gmail/v1/users/me/messages/{messageId}/attachments/{id}` | `{ size, data }` (base64url) of a seeded attachment |
1645
+ | `POST /gmail/v1/users/me/messages/{messageId}/modify` | `{ addLabelIds: [<created label>] }`: `{ id, threadId, labelIds }` |
1646
+ | `POST /gmail/v1/users/me/messages/{messageId}/trash`, `/untrash` | No body: adds or removes `TRASH`, answering `{ id, threadId, labelIds }` |
1647
+ | `POST /gmail/v1/users/me/labels` | `{ name: "yolk-conformance <runId> label" }`: the created user label (`Label_9101` first) |
1648
+ | `GET`, `DELETE /gmail/v1/users/me/labels/{labelId}` | Delete a created label (204; it leaves every message); a read of an absent label answers 404 |
1649
+ | `POST /gmail/v1/users/me/drafts`, `PUT .../drafts/{draftId}` | The recorded run draft without recipients: `{ id, message: { id, threadId, labelIds } }` |
1650
+ | `DELETE /gmail/v1/users/me/drafts/{draftId}` | 204 (the draft and its message go); an absent draft answers the recorded 404 |
1651
+ | `GET /gmail/v1/users/me/threads/{threadId}` | `format=full`: a draft thread created here; `format=metadata` with `metadataHeaders`: a stored thread |
1652
+ | `POST /upload/gmail/v1/users/me/messages/send` | `uploadType=multipart`, `multipart/related`: the practice message only (see below) |
1653
+ | `GET`, `POST /calendar/v3/calendars/{calendarId}/events` | Range listing (`singleEvents=true`, `orderBy=startTime`) with page tokens; the run event |
1654
+ | `GET`, `PATCH`, `DELETE .../events/{eventId}` | Read (cancelled too), the recorded rename, delete to `cancelled` (204), then the recorded 410 |
1655
+ | `GET`, `POST /drive/v3/files` | Folder listing (`'<folder>' in parents and trashed = false`) with page tokens; the run folder |
1656
+ | `GET`, `PATCH`, `DELETE /drive/v3/files/{fileId}` | Read with the connector `fields` (absent: the recorded 404), `{ trashed: true }`, delete 204 |
1656
1657
 
1657
1658
  **The practice send is recorded, never delivered.** `google.gmail.send-practice-address` is
1658
1659
  irreversible on Gmail. The emulator accepts only the recorded 7-bit message whose sole recipient
@@ -1702,23 +1703,27 @@ emulator mints (it never mints anything else):
1702
1703
  forms no seeded id or thread id may use. All come from counters in the state that only advance.
1703
1704
  Event `created` / `updated`, folder `createdTime` / `modifiedTime` / `trashedTime`, and the sent
1704
1705
  `Date` header come from the injectable `now` clock. Page tokens are the fixtures' values
1705
- (`synthetic-gmail-page-2`, ...) in the generation that first issued them, and
1706
- `<token>.g<generation>` after a reset or seed (each starts a generation); a token is never
1707
- rebound: token values are globally unique, so another list or page size, or a changed list, gets a
1708
- distinct `<token>.v<k>`.
1706
+ (`synthetic-gmail-page-2`, `synthetic-gmail-threads-page-2`, ...) in the generation that first
1707
+ issued them, and `<token>.g<generation>` after a reset or seed (each starts a generation); a token
1708
+ is never rebound: token values are globally unique, so another list or page size, or a changed
1709
+ list, gets a distinct `<token>.v<k>`.
1709
1710
  - **Implied entities.** The paging label (`impliedLabelIds`), the five messages its listing names
1710
- (`impliedMessages`, rendered only as `{ id, threadId }` list entries), and the practice Drive
1711
- folder (`impliedFolderIds`) are only named by the fixtures: references resolve through them (a
1712
- label listing, a folder parent), but an answer that would render one is not emulated.
1711
+ (`impliedMessages`, rendered only as `{ id, threadId }` list entries), their five threads
1712
+ (`impliedThreads`, rendered only as `{ id, snippet, historyId }` thread listing entries), and the
1713
+ practice Drive folder (`impliedFolderIds`) are only named by the fixtures: references resolve
1714
+ through them (a label listing, a folder parent), but an answer that would render one is not
1715
+ emulated.
1713
1716
  - **Recorded renderings.** A Gmail message answers only the formats a fixture records for it (the
1714
- work message `minimal`, the attachment message `full`, a composed draft `metadata` and `full`, an
1715
- updated draft `full`, a sent message `metadata`); another format is not emulated.
1717
+ work message `minimal`, the attachment message `metadata` and `full`, a composed draft `metadata`
1718
+ and `full`, an updated draft `full`, a sent message `metadata`); another format is not emulated. A
1719
+ `metadataHeaders` selection (only with `format=metadata`) answers the recorded metadata rendering
1720
+ with only the selected headers, in recorded order.
1716
1721
  - **What writes leave.** A reversible case ends at the seed except the counters, plus each event
1717
1722
  case's own event, which Calendar keeps readable as `cancelled` (the fixtures read it back); the
1718
1723
  send leaves its sent message. Deleting a label removes it from every message.
1719
1724
  - **Page tokens.** A token is accepted only when this emulator issued it for the same list (label
1720
- and `maxResults`; calendar, range, and `maxResults`; folder and `pageSize`) since the last reset
1721
- or seed, and the list renders exactly as when it was issued.
1725
+ and `maxResults` for messages and for threads; calendar, range, and `maxResults`; folder and
1726
+ `pageSize`) since the last reset or seed, and the list renders exactly as when it was issued.
1722
1727
  - **Request-shape latitude (`/google`, the only accepted deviations).** Any bearer value in the RFC
1723
1728
  6750 `b64token` syntax (`[A-Za-z0-9\-._~+/]+=*`) of at least 8 characters, starting with a
1724
1729
  character in `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u`, with at least one outside
@@ -1731,22 +1736,26 @@ emulator mints (it never mints anything else):
1731
1736
  fixtures' `run-synthetic`, because the recorded `sizeEstimate` of the draft and sent messages
1732
1737
  (answered by their message reads and the draft thread) covers the subject; on the practice send, a
1733
1738
  `content-type` of exactly `multipart/related; boundary=<b>` with any one unquoted boundary of 1 to
1734
- 70 `[A-Za-z0-9_]` characters and no other parameter; a `gmail.list` `maxResults` from 1 to 500, a
1735
- `calendar.list_events` `maxResults` from 1 to 2500, and a `drive.list_files` `pageSize` from 1 to
1736
- 1000; any `timeMin` before `timeMax` (RFC 3339 instants with a real calendar date, hour 0 to 23,
1737
- minute and second 0 to 59, and a `Z` or in-range numeric offset); any id of an item the state
1738
- holds where a fixture has an id (writes: only items created here, plus label changes, trash, and
1739
- untrash of a stored non-draft message); and, for an id the state does not hold, only the recorded
1740
- not-found answers (a `format=minimal` read of a 16-hex-digit message id, a read of a
1741
- `Label_<1 to 999999999>` label, a delete of an `r-<digits>` draft, and a Drive file read). A seed
1742
- may set another `practiceAddress`, but then every send is refused, since the recorded
1743
- `sizeEstimate` of the sent message also covers the address: the send answers only while the seeded
1744
- address is the recorded `practice@example.test`. On the draft compose and update routes,
1745
- `message.raw` must be canonical unpadded base64url of exactly the recorded draft MIME of that
1746
- route, the run id aside; any other `message.raw` (line-wrapped, the standard alphabet, padded,
1747
- with a stray character, or with MIME-level encodings such as RFC 2047 encoded-words,
1748
- quoted-printable, or UTF-16) is refused before anything is recorded or a fault is decided, as a
1749
- constant entry with the route's own declared reason
1739
+ 70 `[A-Za-z0-9_]` characters and no other parameter; a `gmail.list` or `gmail.list_threads`
1740
+ `maxResults` from 1 to 500, a `calendar.list_events` `maxResults` from 1 to 2500, and a
1741
+ `drive.list_files` `pageSize` from 1 to 1000; any `timeMin` before `timeMax` (RFC 3339 instants
1742
+ with a real calendar date, hour 0 to 23, minute and second 0 to 59, and a `Z` or in-range numeric
1743
+ offset); any id of an item the state holds where a fixture has an id (writes: only items created
1744
+ here, plus label changes, trash, and untrash of a stored non-draft message); and, for an id the
1745
+ state does not hold, only the recorded not-found answers (a `format=minimal` read of a
1746
+ 16-hex-digit message id, a read of a `Label_<1 to 999999999>` label, a delete of an `r-<digits>`
1747
+ draft, and a Drive file read); on a `format=metadata` message read, and on a `format=metadata`
1748
+ read of a thread of stored non-draft messages (a thread read in that format takes a selection), a
1749
+ `metadataHeaders` selection, repeated in any order, of 1 to 50 distinct header names each spelled
1750
+ exactly as a header of the recorded metadata rendering, answered as that rendering with only the
1751
+ selected headers, in recorded order. A seed may set another `practiceAddress`, but then every send
1752
+ is refused, since the recorded `sizeEstimate` of the sent message also covers the address: the
1753
+ send answers only while the seeded address is the recorded `practice@example.test`. On the draft
1754
+ compose and update routes, `message.raw` must be canonical unpadded base64url of exactly the
1755
+ recorded draft MIME of that route, the run id aside; any other `message.raw` (line-wrapped, the
1756
+ standard alphabet, padded, with a stray character, or with MIME-level encodings such as RFC 2047
1757
+ encoded-words, quoted-printable, or UTF-16) is refused before anything is recorded or a fault is
1758
+ decided, as a constant entry with the route's own declared reason
1750
1759
  (`message.raw must be canonical base64url UTF-8 MIME`,
1751
1760
  `a draft compose other than the recorded run draft is not emulated` or its `update` form, the
1752
1761
  13-character run-id reason, or `message has a key this route does not take`), or
@@ -1773,22 +1782,21 @@ answers an evidence-tagged 500 `{ error: { type: 'emulator_error', message } }`
1773
1782
  reads the clock.
1774
1783
 
1775
1784
  State and seeds: `practiceAddress`, Gmail `messages` (with their recorded renderings),
1776
- `impliedMessages`, `impliedLabelIds`, created `labels`, `attachments`, `drafts`, Calendar
1777
- `calendars` and `events`, Drive `files` and `impliedFolderIds`, and the counters. The default seed
1778
- is the synthetic fixture entities with the ids of `googleConformanceFixtureSeeds`. Pass
1779
- `seed: { profile?, practiceAddress?, messages?, impliedMessages?, impliedLabelIds?, attachments?,
1780
- calendars?, events?, files?, impliedFolderIds? }` (lists replace the profile's; labels and drafts
1781
- are never seeded) with profiles `'default'` or `'empty'`. `reset()`, `seed(next)`, and
1782
- `snapshot()` behave as in the Dropbox emulator; reset and seed also clear issued page tokens.
1785
+ `impliedMessages`, `impliedThreads`, `impliedLabelIds`, created `labels`, `attachments`, `drafts`,
1786
+ Calendar `calendars` and `events`, Drive `files` and `impliedFolderIds`, and the counters. The
1787
+ default seed is the synthetic fixture entities with the ids of `googleConformanceFixtureSeeds`.
1788
+ Pass `seed: { profile?, practiceAddress?, messages?, impliedMessages?, impliedThreads?,
1789
+ impliedLabelIds?, attachments?, calendars?, events?, files?, impliedFolderIds? }` (lists replace
1790
+ the profile's; labels and drafts are never seeded) with profiles `'default'` or `'empty'`.
1791
+ `reset()`, `seed(next)`, and `snapshot()` behave as in the Dropbox emulator; reset and seed also
1792
+ clear issued page tokens.
1783
1793
 
1784
1794
  Faults and the control plane behave as in the Dropbox emulator (the ledger records only the
1785
1795
  `content-type` request header); a 429 fault with `retry-after` reaches the connector as
1786
1796
  `google_rate_limited` with `retryAfterMs`.
1787
1797
 
1788
- **Drill knobs (tests only).** `drills: { gmailPageRepeats, attachmentStandardBase64,
1789
- notFoundWithoutMessage, labelDeleteKeepsOnMessages, draftUpdateKeepsContent,
1790
- trashAnswerOmitsTrash, sentMessageWithoutTo, calendarPageRepeats, eventPatchKeepsSummary,
1791
- repeatedEventDeleteConflict, drivePageRepeats, getFileWithoutParents, listIncludesTrashed }`
1798
+ **Drill knobs (tests only).**
1799
+ `drills: { gmailPageRepeats, attachmentStandardBase64, notFoundWithoutMessage, gmailThreadPageRepeats, metadataHeadersIgnored, labelDeleteKeepsOnMessages, draftUpdateKeepsContent, trashAnswerOmitsTrash, sentMessageWithoutTo, calendarPageRepeats, eventPatchKeepsSummary, repeatedEventDeleteConflict, drivePageRepeats, getFileWithoutParents, listIncludesTrashed }`
1792
1800
  (booleans) each make the emulator disagree with exactly one Google case, only to prove that case
1793
1801
  catches it.
1794
1802
 
@@ -1 +1 @@
1
- {"version":3,"file":"gmail.d.mts","names":[],"sources":["../../src/google/gmail.ts"],"mappings":";;;;cA4Da,YAAA;AAAb;AAAA,cAu6Ba,WAAA,EAAa,aAAa,CAAC,WAAA"}
1
+ {"version":3,"file":"gmail.d.mts","names":[],"sources":["../../src/google/gmail.ts"],"mappings":";;;;cA8Da,YAAA;AAAb;AAAA,cA4oCa,WAAA,EAAa,aAAa,CAAC,WAAA"}
@@ -4,8 +4,9 @@ import { base64UrlOfText, mintedDraftId, mintedLabelIdPattern, mintedMessageId,
4
4
  import { Predicate } from "effect";
5
5
  //#region src/google/gmail.ts
6
6
  /**
7
- * Gmail routes of the Google emulator (internal): message listing by label with page tokens,
8
- * message reads in the recorded formats, attachments, the label lifecycle, label changes, trash and
7
+ * Gmail routes of the Google emulator (internal): message and thread listing by label with page
8
+ * tokens, message and thread reads in the recorded formats (a `metadataHeaders` selection keeps
9
+ * only the selected recorded headers), attachments, the label lifecycle, label changes, trash and
9
10
  * untrash, the draft lifecycle with its thread, and the multipart practice send.
10
11
  *
11
12
  * Every answer comes from the Gmail fixtures, through the seed or the request, or is minted. The
@@ -20,6 +21,8 @@ const gmailApiPath = "/gmail/v1/users/me";
20
21
  const listCase = "google.gmail.list-page-token";
21
22
  const attachmentCase = "google.gmail.attachment-base64url";
22
23
  const notFoundCase = "google.gmail.not-found-envelope";
24
+ const listThreadsCase = "google.gmail.list-threads-page-token";
25
+ const metadataHeadersCase = "google.gmail.metadata-headers";
23
26
  const labelCase = "google.gmail.label-create-apply-delete";
24
27
  const draftCase = "google.gmail.draft-compose-update-delete";
25
28
  const trashCase = "google.gmail.trash-untrash";
@@ -97,7 +100,7 @@ const findMessage = (state, id) => state.messages.find((message) => message.id =
97
100
  const isImpliedMessage = (state, id) => state.impliedMessages.some((message) => message.id === id);
98
101
  const isDraftMessage = (message) => message.labelIds.includes("DRAFT");
99
102
  const replaceMessage = (state, next) => state.messages.map((message) => message.id === next.id ? next : message);
100
- const listMessages = statefulRoute(gmail("GET", "/messages", false, [listCase]), "none", (request) => {
103
+ const listMessages = statefulRoute(gmail("GET", "/messages", false, [listCase, listThreadsCase]), "none", (request) => {
101
104
  const query = exactQuery(request, ["labelIds", "maxResults"], ["pageToken"]);
102
105
  if (isNotEmulated(query)) return query;
103
106
  const labelId = query["labelIds"] ?? "";
@@ -127,35 +130,117 @@ const listMessages = statefulRoute(gmail("GET", "/messages", false, [listCase]),
127
130
  });
128
131
  });
129
132
  });
133
+ const listThreads = statefulRoute(gmail("GET", "/threads", false, [listThreadsCase]), "none", (request) => {
134
+ const query = exactQuery(request, ["labelIds", "maxResults"], ["pageToken"]);
135
+ if (isNotEmulated(query)) return query;
136
+ const labelId = query["labelIds"] ?? "";
137
+ if (!gmailIdSegment.test(labelId)) return notEmulated("labelIds must be one label id");
138
+ const maxResults = pageSize(query["maxResults"], "maxResults", 1, 500);
139
+ if (isNotEmulated(maxResults)) return maxResults;
140
+ const pageToken = query["pageToken"];
141
+ return pageToken === "" ? notEmulated("an empty pageToken is not emulated") : {
142
+ labelId,
143
+ maxResults,
144
+ pageToken
145
+ };
146
+ }, (state, input, { env }) => {
147
+ if (!(state.impliedLabelIds.includes(input.labelId) || state.labels.some((label) => label.id === input.labelId))) return notEmulated("listing a label the state does not hold is not emulated");
148
+ const messages = [...state.messages, ...state.impliedMessages];
149
+ const matches = messages.filter((message) => message.labelIds.includes(input.labelId));
150
+ if (matches.length === 0) return notEmulated("a listing without threads is not emulated (no fixture records one)");
151
+ const threadIds = [...new Set(matches.map((message) => message.threadId))];
152
+ if (messages.some((message) => threadIds.includes(message.threadId) && message.labelIds.some((id) => id === "TRASH" || id === "SPAM"))) return notEmulated("a listing that would leave out threads in Trash or Spam is not emulated");
153
+ const threads = threadIds.map((id) => state.impliedThreads.find((thread) => thread.id === id));
154
+ if (threads.some((thread) => thread === void 0)) return notEmulated("listing a thread no thread listing fixture names is not emulated");
155
+ return listPage(env, "gmail-threads", `gmail-threads\u0000${input.labelId}\u0000${input.maxResults}`, threads.flatMap((thread) => thread === void 0 ? [] : [{
156
+ id: thread.id,
157
+ snippet: thread.snippet,
158
+ historyId: thread.historyId
159
+ }]), input.maxResults, input.pageToken, env.drills.gmailThreadPageRepeats, (page, nextPageToken) => {
160
+ const head = { threads: [...page] };
161
+ if (nextPageToken !== void 0) head.nextPageToken = nextPageToken;
162
+ return googleJson(200, {
163
+ ...head,
164
+ resultSizeEstimate: threads.length
165
+ });
166
+ });
167
+ });
130
168
  const formats = [
131
169
  "minimal",
132
170
  "metadata",
133
171
  "full"
134
172
  ];
135
173
  const isFormat = (value) => value !== void 0 && formats.includes(value);
174
+ /** The connector's bound on one selection (`gmailMetadataHeadersMaxItems`), copied as data. */
175
+ const metadataHeadersMaxItems = 50;
176
+ /** One RFC 5322 header field name, as the connector sends it. */
177
+ const headerNamePattern = /^[!-9;-~]{1,128}$/;
178
+ /**
179
+ * The `format` and the `metadataHeaders` selection of a read: the selection only with
180
+ * `format=metadata`, 1 to 50 distinct header names; not emulated otherwise.
181
+ */
182
+ const readFormat = (request) => {
183
+ const query = exactQuery(request, ["format"], ["metadataHeaders"], { repeatable: ["metadataHeaders"] });
184
+ if (isNotEmulated(query)) return query;
185
+ const format = query["format"];
186
+ if (!isFormat(format)) return notEmulated("format must be minimal, metadata, or full");
187
+ const names = request.query.getAll("metadataHeaders");
188
+ if (names.length === 0) return {
189
+ format,
190
+ metadataHeaders: void 0
191
+ };
192
+ if (format !== "metadata") return notEmulated("metadataHeaders with a format other than metadata is not emulated");
193
+ return names.length <= metadataHeadersMaxItems && new Set(names).size === names.length && names.every((name) => headerNamePattern.test(name)) ? {
194
+ format,
195
+ metadataHeaders: names
196
+ } : notEmulated("metadataHeaders must be 1 to 50 distinct header names");
197
+ };
198
+ const isHeader = (value) => isJsonObject(value) && Predicate.isString(value.name);
199
+ /**
200
+ * `rendered` (a metadata rendering) keeping only the recorded top-level headers the selection
201
+ * names, in recorded order; not emulated when a selected name is not exactly the name of one of its
202
+ * recorded headers (no fixture records a selection of an absent header or in another case).
203
+ * `ignore` (a drill) answers the rendering unchanged.
204
+ */
205
+ const selectHeaders = (rendered, selection, ignore) => {
206
+ if (selection === void 0) return rendered;
207
+ const payload = rendered.payload;
208
+ const headers = isJsonObject(payload) && Array.isArray(payload.headers) ? payload.headers : [];
209
+ const recorded = headers.filter(isHeader);
210
+ if (!isJsonObject(payload) || recorded.length !== headers.length || !selection.every((name) => recorded.some((header) => header.name === name))) return notEmulated("a metadataHeaders selection naming a header the recorded rendering lacks is not emulated");
211
+ if (ignore) return rendered;
212
+ return {
213
+ ...rendered,
214
+ payload: {
215
+ ...payload,
216
+ headers: recorded.filter((header) => selection.includes(header.name))
217
+ }
218
+ };
219
+ };
136
220
  const getMessage = statefulRoute(gmail("GET", "/messages/{messageId}", false, [
137
221
  attachmentCase,
138
222
  notFoundCase,
223
+ metadataHeadersCase,
139
224
  labelCase,
140
225
  draftCase,
141
226
  trashCase,
142
227
  sendCase
143
228
  ], ["messageId"]), "none", (request) => {
144
- const query = exactQuery(request, ["format"]);
145
- if (isNotEmulated(query)) return query;
146
- const format = query["format"];
147
- return isFormat(format) ? {
229
+ const read = readFormat(request);
230
+ return isNotEmulated(read) ? read : {
148
231
  id: param(request, "messageId"),
149
- format
150
- } : notEmulated("format must be minimal, metadata, or full");
232
+ ...read
233
+ };
151
234
  }, (state, input, { env }) => {
152
235
  const message = findMessage(state, input.id);
153
236
  if (message !== void 0) {
154
237
  const rendered = renderMessage(message, input.format);
155
- return rendered === void 0 ? notEmulated(`no fixture records this message with format=${input.format}`) : answer(() => googleJson(200, rendered));
238
+ if (rendered === void 0) return notEmulated(`no fixture records this message with format=${input.format}`);
239
+ const selected = selectHeaders(rendered, input.metadataHeaders, env.drills.metadataHeadersIgnored);
240
+ return isNotEmulated(selected) ? selected : answer(() => googleJson(200, selected));
156
241
  }
157
242
  if (isImpliedMessage(state, input.id)) return notEmulated("reading a message a fixture only names in a listing is not emulated");
158
- return input.format === "minimal" && absentMessageIdPattern.test(input.id) ? answer(() => notFound(env)) : notEmulated("only a format=minimal read of an absent 16-hex-digit id is recorded");
243
+ return input.format === "minimal" && input.metadataHeaders === void 0 && absentMessageIdPattern.test(input.id) ? answer(() => notFound(env)) : notEmulated("only a format=minimal read of an absent 16-hex-digit id is recorded");
159
244
  });
160
245
  const getAttachment = statefulRoute(gmail("GET", "/messages/{messageId}/attachments/{attachmentId}", false, [attachmentCase], ["messageId", "attachmentId"]), "none", (request) => withoutQuery(request) ?? {
161
246
  messageId: param(request, "messageId"),
@@ -439,20 +524,31 @@ const deleteDraft = statefulRoute(gmail("DELETE", "/drafts/{draftId}", true, [dr
439
524
  return googleNoContent();
440
525
  };
441
526
  });
442
- const getThread = statefulRoute(gmail("GET", "/threads/{threadId}", false, [draftCase], ["threadId"]), "none", (request) => {
443
- const query = exactQuery(request, ["format"]);
444
- if (isNotEmulated(query)) return query;
445
- return recordedValue(query, "format", "full") ?? param(request, "threadId");
446
- }, (state, threadId) => {
447
- const messages = state.messages.filter((message) => message.threadId === threadId);
527
+ const getThread = statefulRoute(gmail("GET", "/threads/{threadId}", false, [draftCase, metadataHeadersCase], ["threadId"]), "none", (request) => {
528
+ const read = readFormat(request);
529
+ if (isNotEmulated(read)) return read;
530
+ if (read.format === "minimal" || read.format === "metadata" !== (read.metadataHeaders !== void 0)) return notEmulated("a thread read other than format=full, or format=metadata with metadataHeaders, is not emulated");
531
+ return {
532
+ threadId: param(request, "threadId"),
533
+ ...read
534
+ };
535
+ }, (state, input, { env }) => {
536
+ const messages = state.messages.filter((message) => message.threadId === input.threadId);
537
+ if (state.impliedMessages.some((message) => message.threadId === input.threadId)) return notEmulated("a thread holding a message a fixture only names is not emulated");
448
538
  const createdDrafts = messages.every((message) => isDraftMessage(message) && mintedMessageIdPattern.test(message.id));
449
- if (messages.length === 0 || !createdDrafts) return notEmulated("a thread other than a draft thread created here is not emulated");
450
- const rendered = messages.map((message) => renderMessage(message, "full"));
451
- if (rendered.some((item) => item === void 0)) return notEmulated("a thread with a message without a full rendering is not emulated");
539
+ if (!(messages.length > 0 && (input.format === "full" ? createdDrafts : !messages.some(isDraftMessage)))) return notEmulated(input.format === "full" ? "a thread other than a draft thread created here is not emulated" : "a metadata read of a thread holding a draft is not emulated");
540
+ const rendered = [];
541
+ for (const message of messages) {
542
+ const rendering = renderMessage(message, input.format);
543
+ if (rendering === void 0) return notEmulated(`a thread with a message without a ${input.format} rendering is not emulated`);
544
+ const selected = selectHeaders(rendering, input.metadataHeaders, env.drills.metadataHeadersIgnored);
545
+ if (isNotEmulated(selected)) return selected;
546
+ rendered.push(selected);
547
+ }
452
548
  return answer(() => googleJson(200, {
453
- id: threadId,
549
+ id: input.threadId,
454
550
  historyId: messages.at(-1)?.historyId ?? "",
455
- messages: rendered.flatMap((item) => item === void 0 ? [] : [item])
551
+ messages: rendered
456
552
  }));
457
553
  });
458
554
  const boundaryPattern = /^[A-Za-z0-9_]{1,70}$/;
@@ -571,6 +667,7 @@ const sendMessage = statefulRoute(evidence(googleEmulatorGmailOrigin, "POST", "/
571
667
  /** The Gmail routes, in manifest order. */
572
668
  const gmailRoutes = [
573
669
  listMessages,
670
+ listThreads,
574
671
  getMessage,
575
672
  getAttachment,
576
673
  modifyMessage,