@yolk-sdk/emulators 0.1.0-canary.101 → 0.1.0-canary.102
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 +6 -4
- package/dist/google/gmail.d.mts.map +1 -1
- package/dist/google/gmail.mjs +57 -13
- package/dist/google/gmail.mjs.map +1 -1
- package/dist/google.d.mts.map +1 -1
- package/dist/google.mjs +3 -2
- package/dist/google.mjs.map +1 -1
- package/package.json +5 -5
- package/src/google/gmail.ts +78 -15
- package/src/google.ts +3 -2
package/README.md
CHANGED
|
@@ -1664,8 +1664,9 @@ a minted `Message-ID`), and delivers nothing anywhere; only `reset` or `seed` dr
|
|
|
1664
1664
|
set another `practiceAddress`, but then every send answers 400 not-emulated (the reason names the
|
|
1665
1665
|
recorded `practice@example.test`): the recorded `sizeEstimate` of the sent message covers its
|
|
1666
1666
|
address, as it covers its subject, so draft and send subjects need a run id of the fixtures' length
|
|
1667
|
-
(13 characters; see the latitude below). The draft
|
|
1668
|
-
`body.size` (88) are the fixtures' recorded values,
|
|
1667
|
+
(13 characters; see the latitude below). The draft payload `body.size` (0, the draft is
|
|
1668
|
+
`multipart/alternative`) and the sent message `body.size` (88) are the fixtures' recorded values,
|
|
1669
|
+
answered as recorded.
|
|
1669
1670
|
|
|
1670
1671
|
**Fail closed: the shared rule.** Google follows the shared fail-closed rule of the stateful
|
|
1671
1672
|
wrapper, exactly as the GitHub emulator states it above: every route parameter has a raw pattern
|
|
@@ -1754,8 +1755,9 @@ emulator mints (it never mints anything else):
|
|
|
1754
1755
|
compose and update routes, `message.raw` must be canonical unpadded base64url of exactly the
|
|
1755
1756
|
recorded draft MIME of that route, the run id aside; any other `message.raw` (line-wrapped, the
|
|
1756
1757
|
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
|
|
1758
|
-
decided, as a constant entry with the route's own declared
|
|
1758
|
+
encoded-words, quoted-printable other than the recorded parts, or UTF-16) is refused before
|
|
1759
|
+
anything is recorded or a fault is decided, as a constant entry with the route's own declared
|
|
1760
|
+
reason
|
|
1759
1761
|
(`message.raw must be canonical base64url UTF-8 MIME`,
|
|
1760
1762
|
`a draft compose other than the recorded run draft is not emulated` or its `update` form, the
|
|
1761
1763
|
13-character run-id reason, or `message has a key this route does not take`), or
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gmail.d.mts","names":[],"sources":["../../src/google/gmail.ts"],"mappings":";;;;cA8Da,YAAA;AAAb;AAAA,
|
|
1
|
+
{"version":3,"file":"gmail.d.mts","names":[],"sources":["../../src/google/gmail.ts"],"mappings":";;;;cA8Da,YAAA;AAAb;AAAA,cA2sCa,WAAA,EAAa,aAAa,CAAC,WAAA"}
|
package/dist/google/gmail.mjs
CHANGED
|
@@ -348,7 +348,32 @@ const decodeBase64UrlText = (raw) => {
|
|
|
348
348
|
return;
|
|
349
349
|
}
|
|
350
350
|
};
|
|
351
|
-
const
|
|
351
|
+
const draftBoundary = "=_yolk-draft-alternative";
|
|
352
|
+
const draftContentType = `multipart/alternative; boundary="${draftBoundary}"`;
|
|
353
|
+
/** The quoted-printable part of the recorded draft MIME. */
|
|
354
|
+
const recordedDraftPart = (type, encoded) => `Content-Type: text/${type}; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n${encoded}`;
|
|
355
|
+
/** The draft MIME the draft fixture records after the `Subject` line, for each draft kind. */
|
|
356
|
+
const recordedDraftMime = (plain, html) => [
|
|
357
|
+
"MIME-Version: 1.0",
|
|
358
|
+
`Content-Type: ${draftContentType}`,
|
|
359
|
+
"",
|
|
360
|
+
`--${draftBoundary}`,
|
|
361
|
+
recordedDraftPart("plain", plain),
|
|
362
|
+
`--${draftBoundary}`,
|
|
363
|
+
recordedDraftPart("html", html),
|
|
364
|
+
`--${draftBoundary}--`
|
|
365
|
+
].join("\r\n");
|
|
366
|
+
const recordedDrafts = {
|
|
367
|
+
compose: {
|
|
368
|
+
text: draftText,
|
|
369
|
+
mime: recordedDraftMime("Synthetic conformance draft, safe to delete: gr=C3=BC=C3=9Fe =E2=9C=93", "<div dir=3D\"ltr\">Synthetic conformance draft, safe to delete: gr=C3=BC=\r\n=C3=9Fe =E2=9C=93</div>")
|
|
370
|
+
},
|
|
371
|
+
update: {
|
|
372
|
+
text: updatedDraftText,
|
|
373
|
+
mime: recordedDraftMime("Updated synthetic conformance draft: =C2=A1hola! =E2=9C=93", "<div dir=3D\"ltr\">Updated synthetic conformance draft: =C2=A1hola! =E2=9C=93=\r\n</div>")
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
const draftMimePattern = /^Subject: ([^\r\n]*)\r\n([\s\S]*)$/;
|
|
352
377
|
/** The reasons a draft `message.raw` is refused with (constants; never derived from a request). */
|
|
353
378
|
const draftKeysReason = "message has a key this route does not take";
|
|
354
379
|
const canonicalRawReason = "message.raw must be canonical base64url UTF-8 MIME";
|
|
@@ -378,9 +403,10 @@ const readDraftRaw = (message, kind) => {
|
|
|
378
403
|
};
|
|
379
404
|
const parts = draftMimePattern.exec(decoded);
|
|
380
405
|
const subject = parts?.[1] ?? "";
|
|
381
|
-
const
|
|
406
|
+
const rest = parts?.[2] ?? "";
|
|
382
407
|
const runId = kind === "compose" ? runIdOf(subject, "draft", draftSubjectRest) : runIdOf(subject, "draft updated", draftSubjectRest);
|
|
383
|
-
|
|
408
|
+
const recorded = recordedDrafts[kind];
|
|
409
|
+
if (parts === null || runId === void 0 || rest !== recorded.mime) return {
|
|
384
410
|
decoded,
|
|
385
411
|
content: notEmulated(otherDraftReason(kind))
|
|
386
412
|
};
|
|
@@ -388,7 +414,7 @@ const readDraftRaw = (message, kind) => {
|
|
|
388
414
|
decoded,
|
|
389
415
|
content: runId.length === 13 ? {
|
|
390
416
|
subject,
|
|
391
|
-
body
|
|
417
|
+
body: recorded.text
|
|
392
418
|
} : notEmulated(sizedRunIdReason("draft"))
|
|
393
419
|
};
|
|
394
420
|
};
|
|
@@ -415,18 +441,36 @@ const draftRawViews = (kind) => (body) => {
|
|
|
415
441
|
});
|
|
416
442
|
return decoded === void 0 ? [] : [decoded];
|
|
417
443
|
};
|
|
418
|
-
|
|
444
|
+
/** A draft's `multipart/alternative` payload as the draft fixture's metadata read records it. */
|
|
445
|
+
const draftPayload = (subject) => ({
|
|
419
446
|
partId: "",
|
|
420
|
-
mimeType: "
|
|
447
|
+
mimeType: "multipart/alternative",
|
|
421
448
|
filename: "",
|
|
422
449
|
headers: [{
|
|
423
450
|
name: "Subject",
|
|
424
451
|
value: subject
|
|
425
452
|
}, {
|
|
426
453
|
name: "Content-Type",
|
|
427
|
-
value:
|
|
454
|
+
value: draftContentType
|
|
428
455
|
}],
|
|
429
|
-
body
|
|
456
|
+
body: { size: 0 }
|
|
457
|
+
});
|
|
458
|
+
/** A `format=full` text part, its `body.data` transfer-decoded as the draft fixture records it. */
|
|
459
|
+
const draftTextPart = (partId, type, content) => ({
|
|
460
|
+
partId,
|
|
461
|
+
mimeType: `text/${type}`,
|
|
462
|
+
filename: "",
|
|
463
|
+
headers: [{
|
|
464
|
+
name: "Content-Type",
|
|
465
|
+
value: `text/${type}; charset=UTF-8`
|
|
466
|
+
}, {
|
|
467
|
+
name: "Content-Transfer-Encoding",
|
|
468
|
+
value: "quoted-printable"
|
|
469
|
+
}],
|
|
470
|
+
body: {
|
|
471
|
+
size: new TextEncoder().encode(content).byteLength,
|
|
472
|
+
data: base64UrlOfText(content)
|
|
473
|
+
}
|
|
430
474
|
});
|
|
431
475
|
/** A draft message as the draft fixture records it (the metadata rendering only on compose). */
|
|
432
476
|
const draftMessage = (id, threadId, content, withMetadata) => ({
|
|
@@ -438,11 +482,11 @@ const draftMessage = (id, threadId, content, withMetadata) => ({
|
|
|
438
482
|
historyId: "900020",
|
|
439
483
|
internalDate: recordedInternalDate,
|
|
440
484
|
minimal: false,
|
|
441
|
-
metadataPayload: withMetadata ?
|
|
442
|
-
fullPayload:
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
}
|
|
485
|
+
metadataPayload: withMetadata ? draftPayload(content.subject) : null,
|
|
486
|
+
fullPayload: {
|
|
487
|
+
...draftPayload(content.subject),
|
|
488
|
+
parts: [draftTextPart("0", "plain", content.body), draftTextPart("1", "html", `<div dir="ltr">${content.body}</div>`)]
|
|
489
|
+
}
|
|
446
490
|
});
|
|
447
491
|
const draftAnswer = (draftId, message) => googleJson(200, {
|
|
448
492
|
id: draftId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gmail.mjs","names":[],"sources":["../../src/google/gmail.ts"],"sourcesContent":["/**\n * Gmail routes of the Google emulator (internal): message and thread listing by label with page\n * tokens, message and thread reads in the recorded formats (a `metadataHeaders` selection keeps\n * only the selected recorded headers), attachments, the label lifecycle, label changes, trash and\n * untrash, the draft lifecycle with its thread, and the multipart practice send.\n *\n * Every answer comes from the Gmail fixtures, through the seed or the request, or is minted. The\n * practice send is irreversible on the real service: here it only records the sent message in the\n * state (nothing is delivered anywhere), and only a message whose sole recipient is the seeded\n * practice address, exactly as the send fixture records it, is accepted.\n *\n * @experimental\n */\nimport { Predicate } from 'effect'\nimport type * as Schema from 'effect/Schema'\nimport {\n DecodedViewRefusal,\n exactBodyKeys,\n exactQuery,\n isJsonObject,\n isNotEmulated,\n mediaType,\n type EmulatedRequest,\n notEmulated,\n parseJsonText,\n statefulRoute,\n type NotEmulated\n} from '../stateful-emulator.ts'\nimport {\n answer,\n evidence,\n gmailIdSegment,\n googleEmulatorGmailOrigin,\n googleErrorBody,\n googleJson,\n googleNoContent,\n isRunText,\n listPage,\n pageSize,\n param,\n recordedInternalDate,\n recordedRunIdLength,\n recordedValue,\n runIdOf,\n withoutQuery,\n type GoogleApiEnv,\n type GoogleRoute\n} from './shared.ts'\nimport {\n base64UrlOfText,\n lastLabelNumber,\n mintedLabelIdPattern,\n mintedDraftId,\n mintedMessageId,\n mintedMessageIdPattern,\n pad,\n type GoogleEmulatorGmailMessage,\n type GoogleEmulatorImpliedMessage,\n type GoogleEmulatorState\n} from './state.ts'\n\n/** Path prefix of every Gmail API route (`/gmail/v1/users/me`). */\nexport const gmailApiPath = '/gmail/v1/users/me'\n\nconst listCase = 'google.gmail.list-page-token'\n\nconst attachmentCase = 'google.gmail.attachment-base64url'\n\nconst notFoundCase = 'google.gmail.not-found-envelope'\n\nconst listThreadsCase = 'google.gmail.list-threads-page-token'\n\nconst metadataHeadersCase = 'google.gmail.metadata-headers'\n\nconst labelCase = 'google.gmail.label-create-apply-delete'\n\nconst draftCase = 'google.gmail.draft-compose-update-delete'\n\nconst trashCase = 'google.gmail.trash-untrash'\n\nconst sendCase = 'google.gmail.send-practice-address'\n\nconst gmail = (\n method: string,\n path: string,\n write: boolean,\n caseIds: ReadonlyArray<string>,\n params: ReadonlyArray<string> = []\n) =>\n evidence(\n googleEmulatorGmailOrigin,\n method,\n `${gmailApiPath}${path}`,\n write,\n caseIds,\n Object.fromEntries(params.map(name => [name, gmailIdSegment]))\n )\n\n// Recorded constants and renderings.\n\n/** The Gmail not-found envelope (`messages`, `labels`, and `drafts` reads and deletes). */\nconst notFound = (env: GoogleApiEnv): Response =>\n googleJson(\n 404,\n env.drills.notFoundWithoutMessage\n ? { error: { code: 404, status: 'NOT_FOUND' } }\n : googleErrorBody(404, 'Requested entity was not found.', 'notFound', 'NOT_FOUND')\n )\n\n/** A message id of the recorded absent form (16 lower-case hex digits). */\nconst absentMessageIdPattern = /^[0-9a-f]{16}$/\n\nconst draftIdPattern = /^r-\\d{1,20}$/\n\n/** The draft texts the draft fixture records (non-ASCII on purpose). */\nconst draftText = 'Synthetic conformance draft, safe to delete: grüße ✓'\n\nconst updatedDraftText = 'Updated synthetic conformance draft: ¡hola! ✓'\n\nconst draftSubjectRest = 'synthetic conformance draft, safe to delete'\n\nconst sendSubjectRest = 'synthetic conformance message, safe to delete'\n\n/** The practice address the send fixture records (the sender and the only recipient). */\nconst recordedPracticeAddress = 'practice@example.test'\n\n/** Why a draft or send subject with a run id of another length is not emulated. */\nconst sizedRunIdReason = (what: 'draft' | 'send'): string =>\n `a ${what} subject whose run id is not ${recordedRunIdLength} characters long (the fixtures' run-synthetic) is not emulated: the recorded sizeEstimate covers the subject`\n\n/** The 7-bit MIME the send fixture records for `practiceAddress` and `subject`. */\nconst practiceMime = (practiceAddress: string, subject: string): string =>\n [\n `To: ${practiceAddress}`,\n `Subject: ${subject}`,\n 'MIME-Version: 1.0',\n 'Content-Type: text/plain; charset=us-ascii',\n '',\n 'Synthetic conformance message sent to the seeded practice address only. Safe to delete.',\n ''\n ].join('\\r\\n')\n\n/** The `multipart/related` upload body the send fixture records. */\nconst uploadBody = (boundary: string, mime: string): string =>\n [\n `--${boundary}`,\n 'Content-Type: application/json; charset=UTF-8',\n '',\n '{}',\n `--${boundary}`,\n 'Content-Type: message/rfc822',\n '',\n mime,\n `--${boundary}--`\n ].join('\\r\\n')\n\ntype MessageFormat = 'minimal' | 'metadata' | 'full'\n\nconst head = (message: GoogleEmulatorGmailMessage): Schema.JsonObject => ({\n id: message.id,\n threadId: message.threadId,\n labelIds: [...message.labelIds],\n snippet: message.snippet,\n sizeEstimate: message.sizeEstimate,\n historyId: message.historyId,\n internalDate: message.internalDate\n})\n\n/** The recorded rendering of `message` in `format`, or `undefined` when none is recorded. */\nconst renderMessage = (\n message: GoogleEmulatorGmailMessage,\n format: MessageFormat\n): Schema.JsonObject | undefined => {\n switch (format) {\n case 'minimal':\n return message.minimal ? head(message) : undefined\n case 'metadata':\n return message.metadataPayload === null\n ? undefined\n : { ...head(message), payload: message.metadataPayload }\n case 'full':\n return message.fullPayload === null\n ? undefined\n : { ...head(message), payload: message.fullPayload }\n }\n}\n\n/** The `{ id, threadId, labelIds }` answer of a label change, trash, or untrash. */\nconst labelsAnswer = (\n message: GoogleEmulatorGmailMessage,\n labelIds: ReadonlyArray<string>\n): Response =>\n googleJson(200, { id: message.id, threadId: message.threadId, labelIds: [...labelIds] })\n\nconst findMessage = (state: GoogleEmulatorState, id: string) =>\n state.messages.find(message => message.id === id)\n\nconst isImpliedMessage = (state: GoogleEmulatorState, id: string): boolean =>\n state.impliedMessages.some(message => message.id === id)\n\nconst isDraftMessage = (message: GoogleEmulatorGmailMessage): boolean =>\n message.labelIds.includes('DRAFT')\n\nconst replaceMessage = (\n state: GoogleEmulatorState,\n next: GoogleEmulatorGmailMessage\n): ReadonlyArray<GoogleEmulatorGmailMessage> =>\n state.messages.map(message => (message.id === next.id ? next : message))\n\n// Listing by label.\n\ntype MessagesPageHead = {\n readonly messages: ReadonlyArray<Schema.Json>\n nextPageToken?: string\n}\n\ntype ListInput = {\n readonly labelId: string\n readonly maxResults: number\n readonly pageToken: string | undefined\n}\n\nconst listMessages: GoogleRoute = statefulRoute(\n gmail('GET', '/messages', false, [listCase, listThreadsCase]),\n 'none',\n (request): ListInput | NotEmulated => {\n const query = exactQuery(request, ['labelIds', 'maxResults'], ['pageToken'])\n\n if (isNotEmulated(query)) return query\n\n const labelId = query['labelIds'] ?? ''\n\n if (!gmailIdSegment.test(labelId)) return notEmulated('labelIds must be one label id')\n\n const maxResults = pageSize(query['maxResults'], 'maxResults', 1, 500)\n\n if (isNotEmulated(maxResults)) return maxResults\n\n const pageToken = query['pageToken']\n\n return pageToken === ''\n ? notEmulated('an empty pageToken is not emulated')\n : { labelId, maxResults, pageToken }\n },\n (state, input, { env }) => {\n const known =\n state.impliedLabelIds.includes(input.labelId) ||\n state.labels.some(label => label.id === input.labelId)\n\n if (!known) return notEmulated('listing a label the state does not hold is not emulated')\n\n const matches: ReadonlyArray<GoogleEmulatorGmailMessage | GoogleEmulatorImpliedMessage> = [\n ...state.messages,\n ...state.impliedMessages\n ].filter(message => message.labelIds.includes(input.labelId))\n\n // Every recorded listing has results; an empty one is no fixture's answer.\n if (matches.length === 0) {\n return notEmulated('a listing without messages is not emulated (no fixture records one)')\n }\n\n if (matches.some(message => message.labelIds.some(id => id === 'TRASH' || id === 'SPAM'))) {\n return notEmulated('a listing that would leave out messages in Trash or Spam is not emulated')\n }\n\n return listPage(\n env,\n 'gmail',\n `gmail\\u0000${input.labelId}\\u0000${input.maxResults}`,\n matches.map(message => ({ id: message.id, threadId: message.threadId })),\n input.maxResults,\n input.pageToken,\n env.drills.gmailPageRepeats,\n (page, nextPageToken) => {\n const head: MessagesPageHead = { messages: [...page] }\n\n // The last page carries no `nextPageToken`.\n if (nextPageToken !== undefined) head.nextPageToken = nextPageToken\n\n return googleJson(200, { ...head, resultSizeEstimate: matches.length })\n }\n )\n }\n)\n\n// Thread listing by label.\n\ntype ThreadsPageHead = {\n readonly threads: ReadonlyArray<Schema.Json>\n nextPageToken?: string\n}\n\nconst listThreads: GoogleRoute = statefulRoute(\n gmail('GET', '/threads', false, [listThreadsCase]),\n 'none',\n (request): ListInput | NotEmulated => {\n const query = exactQuery(request, ['labelIds', 'maxResults'], ['pageToken'])\n\n if (isNotEmulated(query)) return query\n\n const labelId = query['labelIds'] ?? ''\n\n if (!gmailIdSegment.test(labelId)) return notEmulated('labelIds must be one label id')\n\n const maxResults = pageSize(query['maxResults'], 'maxResults', 1, 500)\n\n if (isNotEmulated(maxResults)) return maxResults\n\n const pageToken = query['pageToken']\n\n return pageToken === ''\n ? notEmulated('an empty pageToken is not emulated')\n : { labelId, maxResults, pageToken }\n },\n (state, input, { env }) => {\n const known =\n state.impliedLabelIds.includes(input.labelId) ||\n state.labels.some(label => label.id === input.labelId)\n\n if (!known) return notEmulated('listing a label the state does not hold is not emulated')\n\n const messages: ReadonlyArray<GoogleEmulatorGmailMessage | GoogleEmulatorImpliedMessage> = [\n ...state.messages,\n ...state.impliedMessages\n ]\n\n const matches = messages.filter(message => message.labelIds.includes(input.labelId))\n\n if (matches.length === 0) {\n return notEmulated('a listing without threads is not emulated (no fixture records one)')\n }\n\n const threadIds = [...new Set(matches.map(message => message.threadId))]\n\n // Gmail leaves out threads in Trash or Spam; no fixture records that, so refuse it.\n const hidden = messages.some(\n message =>\n threadIds.includes(message.threadId) &&\n message.labelIds.some(id => id === 'TRASH' || id === 'SPAM')\n )\n\n if (hidden) {\n return notEmulated('a listing that would leave out threads in Trash or Spam is not emulated')\n }\n\n const threads = threadIds.map(id => state.impliedThreads.find(thread => thread.id === id))\n\n if (threads.some(thread => thread === undefined)) {\n return notEmulated('listing a thread no thread listing fixture names is not emulated')\n }\n\n return listPage(\n env,\n 'gmail-threads',\n `gmail-threads\\u0000${input.labelId}\\u0000${input.maxResults}`,\n threads.flatMap(thread =>\n thread === undefined\n ? []\n : [{ id: thread.id, snippet: thread.snippet, historyId: thread.historyId }]\n ),\n input.maxResults,\n input.pageToken,\n env.drills.gmailThreadPageRepeats,\n (page, nextPageToken) => {\n const head: ThreadsPageHead = { threads: [...page] }\n\n // The last page carries no `nextPageToken`.\n if (nextPageToken !== undefined) head.nextPageToken = nextPageToken\n\n return googleJson(200, { ...head, resultSizeEstimate: threads.length })\n }\n )\n }\n)\n\n// Message reads.\n\n/** Header names of one `metadataHeaders` selection, in request order (`undefined`: none sent). */\ntype HeaderSelection = ReadonlyArray<string> | undefined\n\ntype MessageRead = {\n readonly id: string\n readonly format: MessageFormat\n readonly metadataHeaders: HeaderSelection\n}\n\nconst formats: ReadonlyArray<string> = ['minimal', 'metadata', 'full']\n\nconst isFormat = (value: string | undefined): value is MessageFormat =>\n value !== undefined && formats.includes(value)\n\n/** The connector's bound on one selection (`gmailMetadataHeadersMaxItems`), copied as data. */\nconst metadataHeadersMaxItems = 50\n\n/** One RFC 5322 header field name, as the connector sends it. */\nconst headerNamePattern = /^[!-9;-~]{1,128}$/\n\n/**\n * The `format` and the `metadataHeaders` selection of a read: the selection only with\n * `format=metadata`, 1 to 50 distinct header names; not emulated otherwise.\n */\nconst readFormat = (\n request: EmulatedRequest\n): { readonly format: MessageFormat; readonly metadataHeaders: HeaderSelection } | NotEmulated => {\n const query = exactQuery(request, ['format'], ['metadataHeaders'], {\n repeatable: ['metadataHeaders']\n })\n\n if (isNotEmulated(query)) return query\n\n const format = query['format']\n\n if (!isFormat(format)) return notEmulated('format must be minimal, metadata, or full')\n\n const names = request.query.getAll('metadataHeaders')\n\n if (names.length === 0) return { format, metadataHeaders: undefined }\n\n if (format !== 'metadata') {\n return notEmulated('metadataHeaders with a format other than metadata is not emulated')\n }\n\n const valid =\n names.length <= metadataHeadersMaxItems &&\n new Set(names).size === names.length &&\n names.every(name => headerNamePattern.test(name))\n\n return valid\n ? { format, metadataHeaders: names }\n : notEmulated('metadataHeaders must be 1 to 50 distinct header names')\n}\n\nconst isHeader = (value: Schema.Json): value is Schema.JsonObject & { readonly name: string } =>\n isJsonObject(value) && Predicate.isString(value.name)\n\n/**\n * `rendered` (a metadata rendering) keeping only the recorded top-level headers the selection\n * names, in recorded order; not emulated when a selected name is not exactly the name of one of its\n * recorded headers (no fixture records a selection of an absent header or in another case).\n * `ignore` (a drill) answers the rendering unchanged.\n */\nconst selectHeaders = (\n rendered: Schema.JsonObject,\n selection: HeaderSelection,\n ignore: boolean\n): Schema.JsonObject | NotEmulated => {\n if (selection === undefined) return rendered\n\n const payload = rendered.payload\n const headers = isJsonObject(payload) && Array.isArray(payload.headers) ? payload.headers : []\n const recorded = headers.filter(isHeader)\n\n if (\n !isJsonObject(payload) ||\n recorded.length !== headers.length ||\n !selection.every(name => recorded.some(header => header.name === name))\n ) {\n return notEmulated(\n 'a metadataHeaders selection naming a header the recorded rendering lacks is not emulated'\n )\n }\n\n if (ignore) return rendered\n\n return {\n ...rendered,\n payload: { ...payload, headers: recorded.filter(header => selection.includes(header.name)) }\n }\n}\n\nconst getMessage: GoogleRoute = statefulRoute(\n gmail(\n 'GET',\n '/messages/{messageId}',\n false,\n [attachmentCase, notFoundCase, metadataHeadersCase, labelCase, draftCase, trashCase, sendCase],\n ['messageId']\n ),\n 'none',\n (request): MessageRead | NotEmulated => {\n const read = readFormat(request)\n\n return isNotEmulated(read) ? read : { id: param(request, 'messageId'), ...read }\n },\n (state, input, { env }) => {\n const message = findMessage(state, input.id)\n\n if (message !== undefined) {\n const rendered = renderMessage(message, input.format)\n\n if (rendered === undefined) {\n return notEmulated(`no fixture records this message with format=${input.format}`)\n }\n\n const selected = selectHeaders(\n rendered,\n input.metadataHeaders,\n env.drills.metadataHeadersIgnored\n )\n\n return isNotEmulated(selected) ? selected : answer(() => googleJson(200, selected))\n }\n\n if (isImpliedMessage(state, input.id)) {\n return notEmulated('reading a message a fixture only names in a listing is not emulated')\n }\n\n // The recorded not-found answer: a minimal read of an id the mailbox does not hold.\n return input.format === 'minimal' &&\n input.metadataHeaders === undefined &&\n absentMessageIdPattern.test(input.id)\n ? answer(() => notFound(env))\n : notEmulated('only a format=minimal read of an absent 16-hex-digit id is recorded')\n }\n)\n\ntype AttachmentRead = { readonly messageId: string; readonly attachmentId: string }\n\nconst getAttachment: GoogleRoute = statefulRoute(\n gmail(\n 'GET',\n '/messages/{messageId}/attachments/{attachmentId}',\n false,\n [attachmentCase],\n ['messageId', 'attachmentId']\n ),\n 'none',\n (request): AttachmentRead | NotEmulated =>\n withoutQuery(request) ?? {\n messageId: param(request, 'messageId'),\n attachmentId: param(request, 'attachmentId')\n },\n (state, input, { env }) => {\n const attachment = state.attachments.find(\n item => item.messageId === input.messageId && item.attachmentId === input.attachmentId\n )\n\n if (attachment === undefined || findMessage(state, input.messageId) === undefined) {\n return notEmulated('an attachment the state does not hold is not emulated')\n }\n\n const data = env.drills.attachmentStandardBase64\n ? attachment.data.replaceAll('-', '+').replaceAll('_', '/')\n : attachment.data\n\n return answer(() => googleJson(200, { size: attachment.size, data }))\n }\n)\n\n// Labels.\n\nconst createLabel: GoogleRoute = statefulRoute(\n gmail('POST', '/labels', true, [labelCase]),\n 'json',\n (request): string | NotEmulated => {\n const body = withoutQuery(request) ?? exactBodyKeys(request.json, 'the label body', ['name'])\n\n if (isNotEmulated(body)) return body\n\n return Predicate.isString(body.name) && isRunText(body.name, 'label')\n ? body.name\n : notEmulated('a label name other than \"yolk-conformance <runId> label\" is not emulated')\n },\n (state, name) => {\n if (state.labels.some(label => label.name === name)) {\n return notEmulated('creating a label whose name exists is not emulated')\n }\n\n // Refused before any fault: no minted label id is left.\n if (state.counters.nextLabelNumber > lastLabelNumber) {\n return notEmulated('creating a label when no Label_<n> id is left is not emulated')\n }\n\n return () => {\n const number = state.counters.nextLabelNumber\n\n const label = {\n id: `Label_${number}`,\n name,\n messageListVisibility: 'show',\n labelListVisibility: 'labelShow',\n type: 'user'\n }\n\n state.counters = { ...state.counters, nextLabelNumber: number + 1 }\n state.labels = [...state.labels, label]\n\n return googleJson(200, { ...label })\n }\n }\n)\n\nconst getLabel: GoogleRoute = statefulRoute(\n gmail('GET', '/labels/{labelId}', false, [labelCase], ['labelId']),\n 'none',\n request => withoutQuery(request) ?? param(request, 'labelId'),\n (state, id, { env }) => {\n if (state.labels.some(label => label.id === id) || state.impliedLabelIds.includes(id)) {\n return notEmulated('no fixture records a label read of an existing label')\n }\n\n return mintedLabelIdPattern.test(id)\n ? answer(() => notFound(env))\n : notEmulated('only a read of an absent Label_<n> id is recorded')\n }\n)\n\nconst deleteLabel: GoogleRoute = statefulRoute(\n gmail('DELETE', '/labels/{labelId}', true, [labelCase], ['labelId']),\n 'none',\n request => withoutQuery(request) ?? param(request, 'labelId'),\n (state, id, { env }) => {\n if (!state.labels.some(label => label.id === id)) {\n return notEmulated('only deleting a label created here is recorded')\n }\n\n return () => {\n const without = <M extends { readonly labelIds: ReadonlyArray<string> }>(message: M): M =>\n message.labelIds.includes(id)\n ? { ...message, labelIds: message.labelIds.filter(label => label !== id) }\n : message\n\n state.labels = state.labels.filter(label => label.id !== id)\n\n // Deleting a label removes it from every message (the label fixture's last read).\n if (!env.drills.labelDeleteKeepsOnMessages) {\n state.messages = state.messages.map(without)\n state.impliedMessages = state.impliedMessages.map(without)\n }\n\n return googleNoContent()\n }\n }\n)\n\n// Label changes, trash, and untrash.\n\ntype ModifyInput = { readonly messageId: string; readonly labelId: string }\n\nconst modifyMessage: GoogleRoute = statefulRoute(\n gmail('POST', '/messages/{messageId}/modify', true, [labelCase], ['messageId']),\n 'json',\n (request): ModifyInput | NotEmulated => {\n const body =\n withoutQuery(request) ?? exactBodyKeys(request.json, 'the modify body', ['addLabelIds'])\n\n if (isNotEmulated(body)) return body\n\n const added = body.addLabelIds\n\n if (!Array.isArray(added) || added.length !== 1 || !Predicate.isString(added[0])) {\n return notEmulated('a modify adding other than one label is not emulated')\n }\n\n return { messageId: param(request, 'messageId'), labelId: added[0] }\n },\n (state, input) => {\n const message = findMessage(state, input.messageId)\n\n if (message === undefined || isDraftMessage(message)) {\n return notEmulated('changing the labels of a message the state does not hold is not emulated')\n }\n\n if (!state.labels.some(label => label.id === input.labelId)) {\n return notEmulated('adding a label other than one created here is not emulated')\n }\n\n if (message.labelIds.includes(input.labelId)) {\n return notEmulated('adding a label the message carries already is not emulated')\n }\n\n return () => {\n const next = { ...message, labelIds: [...message.labelIds, input.labelId] }\n\n state.messages = replaceMessage(state, next)\n\n return labelsAnswer(next, next.labelIds)\n }\n }\n)\n\nconst trashRoute = (action: 'trash' | 'untrash'): GoogleRoute =>\n statefulRoute(\n gmail('POST', `/messages/{messageId}/${action}`, true, [trashCase], ['messageId']),\n 'none',\n request => withoutQuery(request) ?? param(request, 'messageId'),\n (state, id, { env }) => {\n const message = findMessage(state, id)\n\n if (message === undefined || isDraftMessage(message)) {\n return notEmulated(`${action} of a message the state does not hold is not emulated`)\n }\n\n const inTrash = message.labelIds.includes('TRASH')\n\n if (action === 'trash' ? inTrash : !inTrash) {\n return notEmulated(\n action === 'trash'\n ? 'trashing a message already in Trash is not emulated'\n : 'untrashing a message not in Trash is not emulated'\n )\n }\n\n return () => {\n const labelIds =\n action === 'trash'\n ? [...message.labelIds, 'TRASH']\n : message.labelIds.filter(label => label !== 'TRASH')\n\n const next = { ...message, labelIds }\n\n state.messages = replaceMessage(state, next)\n\n return labelsAnswer(\n next,\n action === 'trash' && env.drills.trashAnswerOmitsTrash\n ? labelIds.filter(label => label !== 'TRASH')\n : labelIds\n )\n }\n }\n )\n\n// Drafts.\n\nconst base64UrlPattern = /^[A-Za-z0-9_-]*$/\n\n/** The UTF-8 text of canonical unpadded base64url, or `undefined`. */\nconst decodeBase64UrlText = (raw: string): string | undefined => {\n if (!base64UrlPattern.test(raw) || raw.length % 4 === 1) return undefined\n\n try {\n const binary = atob(raw.replaceAll('-', '+').replaceAll('_', '/'))\n const bytes = Uint8Array.from(binary, char => char.charCodeAt(0))\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\n // Canonical only: the encoding the connector writes, byte for byte.\n return base64UrlOfText(text) === raw ? text : undefined\n } catch {\n return undefined\n }\n}\n\nconst draftMimePattern =\n /^Subject: ([^\\r\\n]*)\\r\\nContent-Type: text\\/plain; charset=utf-8\\r\\n\\r\\n([\\s\\S]*)$/\n\ntype DraftContent = { readonly subject: string; readonly body: string }\n\n/** The reasons a draft `message.raw` is refused with (constants; never derived from a request). */\nconst draftKeysReason = 'message has a key this route does not take'\n\nconst canonicalRawReason = 'message.raw must be canonical base64url UTF-8 MIME'\n\nconst otherDraftReason = (kind: 'compose' | 'update'): string =>\n `a draft ${kind} other than the recorded run draft is not emulated`\n\n/**\n * Every reason `readDraftRaw` refuses a draft of `kind` with: the route's declared\n * `viewRefusalReasons`, so the wrapper ledgers exactly these (and nothing derived from a request).\n */\nconst draftRefusalReasons = (kind: 'compose' | 'update'): ReadonlyArray<string> => [\n draftKeysReason,\n canonicalRawReason,\n otherDraftReason(kind),\n sizedRunIdReason('draft')\n]\n\ntype DraftRaw = {\n /** The decoded MIME when `message.raw` is canonical base64url UTF-8 (decoded once). */\n readonly decoded: string | undefined\n readonly content: DraftContent | NotEmulated\n}\n\n/** The recorded draft MIME (no recipient) of a compose or an update, decoded once. */\nconst readDraftRaw = (message: Schema.Json | undefined, kind: 'compose' | 'update'): DraftRaw => {\n // Decode `raw` before the key check, so a cleanly decoded raw is always available to the\n // credential guard (a bearer inside it is a repeat, whatever else is wrong with `message`).\n const raw =\n Predicate.hasProperty(message, 'raw') && !Array.isArray(message) ? message.raw : undefined\n\n const decoded = Predicate.isString(raw) ? decodeBase64UrlText(raw) : undefined\n\n const fields = exactBodyKeys(message, 'message', ['raw'])\n\n if (isNotEmulated(fields)) return { decoded, content: fields }\n\n if (decoded === undefined) return { decoded, content: notEmulated(canonicalRawReason) }\n\n const parts = draftMimePattern.exec(decoded)\n const subject = parts?.[1] ?? ''\n const body = parts?.[2] ?? ''\n\n const runId =\n kind === 'compose'\n ? runIdOf(subject, 'draft', draftSubjectRest)\n : runIdOf(subject, 'draft updated', draftSubjectRest)\n\n const recordedBody = kind === 'compose' ? draftText : updatedDraftText\n\n if (parts === null || runId === undefined || body !== recordedBody) {\n return { decoded, content: notEmulated(otherDraftReason(kind)) }\n }\n\n return {\n decoded,\n content:\n runId.length === recordedRunIdLength\n ? { subject, body }\n : notEmulated(sizedRunIdReason('draft'))\n }\n}\n\n/**\n * The decoded view of a draft body for the credential guard (Gmail's own wire format wraps the\n * draft MIME in base64url `message.raw`). Fail closed: when the body is a JSON object whose\n * `message` object carries `raw`, the view returns the decoded MIME only when it is exactly the\n * recorded draft MIME of this route (`kind`), the run id aside. Any other raw makes it throw a\n * `DecodedViewRefusal` with the route's own constant reason (one of `draftRefusalReasons`) and\n * whatever it decoded cleanly: the wrapper ledgers a repeat when that text holds the bearer, and\n * the declared reason otherwise, before anything is recorded, so a refused raw (line-wrapped, the\n * standard alphabet, a stray character, RFC 2047 words, quoted-printable, UTF-16, a 12-character\n * run id, ...) never reaches the ledger. A body without `message.raw` yields no view (the route's\n * own shape check refuses it).\n */\nconst draftRawViews =\n (kind: 'compose' | 'update') =>\n (body: string): ReadonlyArray<string> => {\n const parsed = parseJsonText(body)\n const message = isJsonObject(parsed) ? parsed.message : undefined\n\n if (!isJsonObject(message) || !('raw' in message)) return []\n\n const { decoded, content } = readDraftRaw(message, kind)\n\n if (isNotEmulated(content)) {\n throw new DecodedViewRefusal({\n reason: content.reason,\n decoded: decoded === undefined ? [] : [decoded]\n })\n }\n\n return decoded === undefined ? [] : [decoded]\n }\n\nconst textPayload = (subject: string, body: Schema.JsonObject): Schema.JsonObject => ({\n partId: '',\n mimeType: 'text/plain',\n filename: '',\n headers: [\n { name: 'Subject', value: subject },\n { name: 'Content-Type', value: 'text/plain; charset=utf-8' }\n ],\n body\n})\n\n/** A draft message as the draft fixture records it (the metadata rendering only on compose). */\nconst draftMessage = (\n id: string,\n threadId: string,\n content: DraftContent,\n withMetadata: boolean\n): GoogleEmulatorGmailMessage => ({\n id,\n threadId,\n labelIds: ['DRAFT'],\n snippet: content.body,\n sizeEstimate: 512,\n historyId: '900020',\n internalDate: recordedInternalDate,\n minimal: false,\n metadataPayload: withMetadata ? textPayload(content.subject, { size: 64 }) : null,\n fullPayload: textPayload(content.subject, {\n size: new TextEncoder().encode(content.body).byteLength,\n data: base64UrlOfText(content.body)\n })\n})\n\nconst draftAnswer = (draftId: string, message: GoogleEmulatorGmailMessage): Response =>\n googleJson(200, {\n id: draftId,\n message: { id: message.id, threadId: message.threadId, labelIds: [...message.labelIds] }\n })\n\nconst composeDraft: GoogleRoute = statefulRoute(\n {\n ...gmail('POST', '/drafts', true, [draftCase]),\n decodedViews: draftRawViews('compose'),\n viewRefusalReasons: draftRefusalReasons('compose')\n },\n 'json',\n (request): DraftContent | NotEmulated => {\n const body = withoutQuery(request) ?? exactBodyKeys(request.json, 'the draft body', ['message'])\n\n return isNotEmulated(body) ? body : readDraftRaw(body.message, 'compose').content\n },\n (state, content) => () => {\n const draftNumber = state.counters.nextDraftNumber\n const messageNumber = state.counters.nextDraftMessageNumber\n const id = mintedMessageId('d', messageNumber)\n const message = draftMessage(id, id, content, true)\n const draftId = mintedDraftId(draftNumber)\n\n state.counters = {\n ...state.counters,\n nextDraftNumber: draftNumber + 1,\n nextDraftMessageNumber: messageNumber + 1\n }\n state.messages = [...state.messages, message]\n state.drafts = [...state.drafts, { id: draftId, messageId: id }]\n\n return draftAnswer(draftId, message)\n }\n)\n\ntype UpdateInput = { readonly draftId: string; readonly content: DraftContent }\n\nconst updateDraft: GoogleRoute = statefulRoute(\n {\n ...gmail('PUT', '/drafts/{draftId}', true, [draftCase], ['draftId']),\n decodedViews: draftRawViews('update'),\n viewRefusalReasons: draftRefusalReasons('update')\n },\n 'json',\n (request): UpdateInput | NotEmulated => {\n const draftId = param(request, 'draftId')\n\n const body =\n withoutQuery(request) ?? exactBodyKeys(request.json, 'the draft body', ['id', 'message'])\n\n if (isNotEmulated(body)) return body\n\n if (body.id !== draftId) return notEmulated('a body id other than the path draft id')\n\n const content = readDraftRaw(body.message, 'update').content\n\n return isNotEmulated(content) ? content : { draftId, content }\n },\n (state, input, { env }) => {\n const draft = state.drafts.find(candidate => candidate.id === input.draftId)\n const previous = draft === undefined ? undefined : findMessage(state, draft.messageId)\n\n if (draft === undefined || previous === undefined) {\n return notEmulated('updating a draft the state does not hold is not emulated')\n }\n\n return () => {\n const number = state.counters.nextDraftMessageNumber\n const id = mintedMessageId('d', number)\n\n const message: GoogleEmulatorGmailMessage = env.drills.draftUpdateKeepsContent\n ? { ...previous, id, metadataPayload: null }\n : draftMessage(id, previous.threadId, input.content, false)\n\n state.counters = { ...state.counters, nextDraftMessageNumber: number + 1 }\n state.messages = [\n ...state.messages.filter(candidate => candidate.id !== previous.id),\n message\n ]\n state.drafts = state.drafts.map(candidate =>\n candidate.id === draft.id ? { ...candidate, messageId: id } : candidate\n )\n\n return draftAnswer(draft.id, message)\n }\n }\n)\n\nconst deleteDraft: GoogleRoute = statefulRoute(\n gmail('DELETE', '/drafts/{draftId}', true, [draftCase], ['draftId']),\n 'none',\n request => withoutQuery(request) ?? param(request, 'draftId'),\n (state, id, { env }) => {\n const draft = state.drafts.find(candidate => candidate.id === id)\n\n if (draft === undefined) {\n // The recorded repeated delete: an absent draft answers the not-found envelope.\n return draftIdPattern.test(id)\n ? answer(() => notFound(env))\n : notEmulated('only deleting an absent r-<digits> draft id is recorded')\n }\n\n return () => {\n state.drafts = state.drafts.filter(candidate => candidate.id !== id)\n state.messages = state.messages.filter(message => message.id !== draft.messageId)\n\n return googleNoContent()\n }\n }\n)\n\ntype ThreadRead = {\n readonly threadId: string\n readonly format: MessageFormat\n readonly metadataHeaders: HeaderSelection\n}\n\nconst getThread: GoogleRoute = statefulRoute(\n gmail('GET', '/threads/{threadId}', false, [draftCase, metadataHeadersCase], ['threadId']),\n 'none',\n (request): ThreadRead | NotEmulated => {\n const read = readFormat(request)\n\n if (isNotEmulated(read)) return read\n\n // Recorded: a full read of a draft thread, and a metadata read with a metadataHeaders selection.\n if (\n read.format === 'minimal' ||\n (read.format === 'metadata') !== (read.metadataHeaders !== undefined)\n ) {\n return notEmulated(\n 'a thread read other than format=full, or format=metadata with metadataHeaders, is not emulated'\n )\n }\n\n return { threadId: param(request, 'threadId'), ...read }\n },\n (state, input, { env }) => {\n const messages = state.messages.filter(message => message.threadId === input.threadId)\n\n if (state.impliedMessages.some(message => message.threadId === input.threadId)) {\n return notEmulated('a thread holding a message a fixture only names is not emulated')\n }\n\n const createdDrafts = messages.every(\n message => isDraftMessage(message) && mintedMessageIdPattern.test(message.id)\n )\n\n // Full: only draft threads created here are recorded (a seeded message's thread is not).\n // Metadata: only threads of stored messages that are not drafts are recorded.\n const recorded =\n messages.length > 0 &&\n (input.format === 'full' ? createdDrafts : !messages.some(isDraftMessage))\n\n if (!recorded) {\n return notEmulated(\n input.format === 'full'\n ? 'a thread other than a draft thread created here is not emulated'\n : 'a metadata read of a thread holding a draft is not emulated'\n )\n }\n\n const rendered: Array<Schema.JsonObject> = []\n\n for (const message of messages) {\n const rendering = renderMessage(message, input.format)\n\n if (rendering === undefined) {\n return notEmulated(\n `a thread with a message without a ${input.format} rendering is not emulated`\n )\n }\n\n const selected = selectHeaders(\n rendering,\n input.metadataHeaders,\n env.drills.metadataHeadersIgnored\n )\n\n if (isNotEmulated(selected)) return selected\n\n rendered.push(selected)\n }\n\n return answer(() =>\n googleJson(200, {\n id: input.threadId,\n historyId: messages.at(-1)?.historyId ?? '',\n messages: rendered\n })\n )\n }\n)\n\n// The practice send (upload endpoint).\n\nconst boundaryPattern = /^[A-Za-z0-9_]{1,70}$/\n\ntype SendInput = { readonly boundary: string; readonly subject: string; readonly text: string }\n\n/**\n * The boundary of `multipart/related; boundary=<b>`, or `undefined`. The parameter list is parsed\n * whole: each parameter is split on its first `=`, and the content type must carry exactly one\n * parameter, `boundary`, whose whole value is 1 to 70 of `[A-Za-z0-9_]` (unquoted). Any other,\n * repeated, empty, or malformed parameter is refused (the send records no other parameter).\n */\nconst multipartBoundary = (contentType: string | undefined): string | undefined => {\n if (mediaType(contentType) !== 'multipart/related') return undefined\n\n const params = (contentType ?? '')\n .split(';')\n .slice(1)\n .map(param => {\n const separator = param.indexOf('=')\n\n return separator === -1\n ? undefined\n : {\n name: param.slice(0, separator).trim().toLowerCase(),\n value: param.slice(separator + 1)\n }\n })\n\n const [only] = params\n\n return params.length === 1 &&\n only !== undefined &&\n only.name === 'boundary' &&\n boundaryPattern.test(only.value)\n ? only.value\n : undefined\n}\n\nconst sendMessage: GoogleRoute = statefulRoute(\n evidence(googleEmulatorGmailOrigin, 'POST', '/upload/gmail/v1/users/me/messages/send', true, [\n sendCase\n ]),\n 'bytes',\n (request): SendInput | NotEmulated => {\n const query = exactQuery(request, ['uploadType'])\n\n if (isNotEmulated(query)) return query\n\n const problem = recordedValue(query, 'uploadType', 'multipart')\n\n if (problem !== undefined) return problem\n\n const boundary = multipartBoundary(request.header('content-type'))\n\n if (boundary === undefined) {\n return notEmulated(\n 'a content-type other than multipart/related; boundary=<b> is not emulated'\n )\n }\n\n let text: string\n\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(request.bytes)\n } catch {\n return notEmulated('an upload body that is not 7-bit text is not emulated')\n }\n\n const subject = /\\r\\nSubject: ([^\\r\\n]*)\\r\\n/.exec(text)?.[1] ?? ''\n\n const runId = runIdOf(subject, 'send', sendSubjectRest)\n\n if (runId === undefined) {\n return notEmulated(\n 'a send other than the recorded run-scoped practice message is not emulated'\n )\n }\n\n return runId.length === recordedRunIdLength\n ? { boundary, subject, text }\n : notEmulated(sizedRunIdReason('send'))\n },\n (state, input, { env }) => {\n // The recorded sizeEstimate covers the To and From headers: only the recorded address.\n if (state.practiceAddress !== recordedPracticeAddress) {\n return notEmulated(\n `a send while the seeded practiceAddress is not the recorded ${recordedPracticeAddress} is not emulated (the recorded sizeEstimate covers the address)`\n )\n }\n\n // Only the recorded message, whose ONLY recipient is the seeded practice address.\n if (\n input.text !== uploadBody(input.boundary, practiceMime(state.practiceAddress, input.subject))\n ) {\n return notEmulated(\n 'a send other than the recorded 7-bit message to the seeded practice address only is not emulated'\n )\n }\n\n return () => {\n // Read the clock before any write: a failing clock, or one answering an instant outside the\n // Date range (non-finite or not), writes nothing.\n const instant = new Date(env.now())\n\n if (!Number.isFinite(instant.getTime())) {\n throw new Error('the clock answered an instant outside the Date range')\n }\n\n const date = instant.toUTCString().replace(/GMT$/, '+0000')\n const number = state.counters.nextSentNumber\n const id = mintedMessageId('e', number)\n const address = state.practiceAddress\n\n const headers = [\n { name: 'MIME-Version', value: '1.0' },\n { name: 'Date', value: date },\n { name: 'Message-ID', value: `<synthetic-send-${pad(number, 4)}@example.test>` },\n { name: 'Subject', value: input.subject },\n { name: 'From', value: address },\n { name: 'To', value: address },\n { name: 'Content-Type', value: 'text/plain; charset=us-ascii' }\n ].filter(header => !(env.drills.sentMessageWithoutTo && header.name === 'To'))\n\n // Recorded in the state only: nothing is delivered anywhere.\n const sent: GoogleEmulatorGmailMessage = {\n id,\n threadId: id,\n labelIds: ['SENT', 'INBOX', 'UNREAD'],\n snippet: 'Synthetic conformance message sent to the seeded practice address only.',\n sizeEstimate: 640,\n historyId: '900030',\n internalDate: recordedInternalDate,\n minimal: false,\n metadataPayload: {\n partId: '',\n mimeType: 'text/plain',\n filename: '',\n headers,\n body: { size: 88 }\n },\n fullPayload: null\n }\n\n state.counters = { ...state.counters, nextSentNumber: number + 1 }\n state.messages = [...state.messages, sent]\n\n return googleJson(200, { id, threadId: id, labelIds: ['SENT'] })\n }\n }\n)\n\n/** The Gmail routes, in manifest order. */\nexport const gmailRoutes: ReadonlyArray<GoogleRoute> = [\n listMessages,\n listThreads,\n getMessage,\n getAttachment,\n modifyMessage,\n trashRoute('trash'),\n trashRoute('untrash'),\n createLabel,\n getLabel,\n deleteLabel,\n composeDraft,\n updateDraft,\n deleteDraft,\n getThread,\n sendMessage\n]\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8DA,MAAa,eAAe;AAE5B,MAAM,WAAW;AAEjB,MAAM,iBAAiB;AAEvB,MAAM,eAAe;AAErB,MAAM,kBAAkB;AAExB,MAAM,sBAAsB;AAE5B,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,WAAW;AAEjB,MAAM,SACJ,QACA,MACA,OACA,SACA,SAAgC,CAAC,MAEjC,SACE,2BACA,QACA,GAAG,eAAe,QAClB,OACA,SACA,OAAO,YAAY,OAAO,KAAI,SAAQ,CAAC,MAAM,cAAc,CAAC,CAAC,CAC/D;;AAKF,MAAM,YAAY,QAChB,WACE,KACA,IAAI,OAAO,yBACP,EAAE,OAAO;CAAE,MAAM;CAAK,QAAQ;AAAY,EAAE,IAC5C,gBAAgB,KAAK,mCAAmC,YAAY,WAAW,CACrF;;AAGF,MAAM,yBAAyB;AAE/B,MAAM,iBAAiB;;AAGvB,MAAM,YAAY;AAElB,MAAM,mBAAmB;AAEzB,MAAM,mBAAmB;AAEzB,MAAM,kBAAkB;;AAGxB,MAAM,0BAA0B;;AAGhC,MAAM,oBAAoB,SACxB,KAAK,KAAK;;AAGZ,MAAM,gBAAgB,iBAAyB,YAC7C;CACE,OAAO;CACP,YAAY;CACZ;CACA;CACA;CACA;CACA;AACF,EAAE,KAAK,MAAM;;AAGf,MAAM,cAAc,UAAkB,SACpC;CACE,KAAK;CACL;CACA;CACA;CACA,KAAK;CACL;CACA;CACA;CACA,KAAK,SAAS;AAChB,EAAE,KAAK,MAAM;AAIf,MAAM,QAAQ,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C;MAAE,MAAM;MAAQ,OAAO;KAAK;KAC5B;MAAE,MAAM;MAAc,OAAO,mBAAmB,IAAI,QAAQ,CAAC,EAAE;KAAgB;KAC/E;MAAE,MAAM;MAAW,OAAO,MAAM;KAAQ;KACxC;MAAE,MAAM;MAAQ,OAAO;KAAQ;KAC/B;MAAE,MAAM;MAAM,OAAO;KAAQ;KAC7B;MAAE,MAAM;MAAgB,OAAO;KAA+B;IAChE,EAAE,QAAO,WAAU,EAAE,IAAI,OAAO,wBAAwB,OAAO,SAAS,KAgB9D;IACN,MAAM,EAAE,MAAM,GAAG;GACnB;GACA,aAAa;EACf;EAEA,MAAM,WAAW;GAAE,GAAG,MAAM;GAAU,gBAAgB,SAAS;EAAE;EACjE,MAAM,WAAW,CAAC,GAAG,MAAM,UAAU,IAAI;EAEzC,OAAO,WAAW,KAAK;GAAE;GAAI,UAAU;GAAI,UAAU,CAAC,MAAM;EAAE,CAAC;CACjE;AACF,CACF;;AAGA,MAAa,cAA0C;CACrD;CACA;CACA;CACA;CACA;CACA,WAAW,OAAO;CAClB,WAAW,SAAS;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
1
|
+
{"version":3,"file":"gmail.mjs","names":[],"sources":["../../src/google/gmail.ts"],"sourcesContent":["/**\n * Gmail routes of the Google emulator (internal): message and thread listing by label with page\n * tokens, message and thread reads in the recorded formats (a `metadataHeaders` selection keeps\n * only the selected recorded headers), attachments, the label lifecycle, label changes, trash and\n * untrash, the draft lifecycle with its thread, and the multipart practice send.\n *\n * Every answer comes from the Gmail fixtures, through the seed or the request, or is minted. The\n * practice send is irreversible on the real service: here it only records the sent message in the\n * state (nothing is delivered anywhere), and only a message whose sole recipient is the seeded\n * practice address, exactly as the send fixture records it, is accepted.\n *\n * @experimental\n */\nimport { Predicate } from 'effect'\nimport type * as Schema from 'effect/Schema'\nimport {\n DecodedViewRefusal,\n exactBodyKeys,\n exactQuery,\n isJsonObject,\n isNotEmulated,\n mediaType,\n type EmulatedRequest,\n notEmulated,\n parseJsonText,\n statefulRoute,\n type NotEmulated\n} from '../stateful-emulator.ts'\nimport {\n answer,\n evidence,\n gmailIdSegment,\n googleEmulatorGmailOrigin,\n googleErrorBody,\n googleJson,\n googleNoContent,\n isRunText,\n listPage,\n pageSize,\n param,\n recordedInternalDate,\n recordedRunIdLength,\n recordedValue,\n runIdOf,\n withoutQuery,\n type GoogleApiEnv,\n type GoogleRoute\n} from './shared.ts'\nimport {\n base64UrlOfText,\n lastLabelNumber,\n mintedLabelIdPattern,\n mintedDraftId,\n mintedMessageId,\n mintedMessageIdPattern,\n pad,\n type GoogleEmulatorGmailMessage,\n type GoogleEmulatorImpliedMessage,\n type GoogleEmulatorState\n} from './state.ts'\n\n/** Path prefix of every Gmail API route (`/gmail/v1/users/me`). */\nexport const gmailApiPath = '/gmail/v1/users/me'\n\nconst listCase = 'google.gmail.list-page-token'\n\nconst attachmentCase = 'google.gmail.attachment-base64url'\n\nconst notFoundCase = 'google.gmail.not-found-envelope'\n\nconst listThreadsCase = 'google.gmail.list-threads-page-token'\n\nconst metadataHeadersCase = 'google.gmail.metadata-headers'\n\nconst labelCase = 'google.gmail.label-create-apply-delete'\n\nconst draftCase = 'google.gmail.draft-compose-update-delete'\n\nconst trashCase = 'google.gmail.trash-untrash'\n\nconst sendCase = 'google.gmail.send-practice-address'\n\nconst gmail = (\n method: string,\n path: string,\n write: boolean,\n caseIds: ReadonlyArray<string>,\n params: ReadonlyArray<string> = []\n) =>\n evidence(\n googleEmulatorGmailOrigin,\n method,\n `${gmailApiPath}${path}`,\n write,\n caseIds,\n Object.fromEntries(params.map(name => [name, gmailIdSegment]))\n )\n\n// Recorded constants and renderings.\n\n/** The Gmail not-found envelope (`messages`, `labels`, and `drafts` reads and deletes). */\nconst notFound = (env: GoogleApiEnv): Response =>\n googleJson(\n 404,\n env.drills.notFoundWithoutMessage\n ? { error: { code: 404, status: 'NOT_FOUND' } }\n : googleErrorBody(404, 'Requested entity was not found.', 'notFound', 'NOT_FOUND')\n )\n\n/** A message id of the recorded absent form (16 lower-case hex digits). */\nconst absentMessageIdPattern = /^[0-9a-f]{16}$/\n\nconst draftIdPattern = /^r-\\d{1,20}$/\n\n/** The draft texts the draft fixture records (non-ASCII on purpose). */\nconst draftText = 'Synthetic conformance draft, safe to delete: grüße ✓'\n\nconst updatedDraftText = 'Updated synthetic conformance draft: ¡hola! ✓'\n\nconst draftSubjectRest = 'synthetic conformance draft, safe to delete'\n\nconst sendSubjectRest = 'synthetic conformance message, safe to delete'\n\n/** The practice address the send fixture records (the sender and the only recipient). */\nconst recordedPracticeAddress = 'practice@example.test'\n\n/** Why a draft or send subject with a run id of another length is not emulated. */\nconst sizedRunIdReason = (what: 'draft' | 'send'): string =>\n `a ${what} subject whose run id is not ${recordedRunIdLength} characters long (the fixtures' run-synthetic) is not emulated: the recorded sizeEstimate covers the subject`\n\n/** The 7-bit MIME the send fixture records for `practiceAddress` and `subject`. */\nconst practiceMime = (practiceAddress: string, subject: string): string =>\n [\n `To: ${practiceAddress}`,\n `Subject: ${subject}`,\n 'MIME-Version: 1.0',\n 'Content-Type: text/plain; charset=us-ascii',\n '',\n 'Synthetic conformance message sent to the seeded practice address only. Safe to delete.',\n ''\n ].join('\\r\\n')\n\n/** The `multipart/related` upload body the send fixture records. */\nconst uploadBody = (boundary: string, mime: string): string =>\n [\n `--${boundary}`,\n 'Content-Type: application/json; charset=UTF-8',\n '',\n '{}',\n `--${boundary}`,\n 'Content-Type: message/rfc822',\n '',\n mime,\n `--${boundary}--`\n ].join('\\r\\n')\n\ntype MessageFormat = 'minimal' | 'metadata' | 'full'\n\nconst head = (message: GoogleEmulatorGmailMessage): Schema.JsonObject => ({\n id: message.id,\n threadId: message.threadId,\n labelIds: [...message.labelIds],\n snippet: message.snippet,\n sizeEstimate: message.sizeEstimate,\n historyId: message.historyId,\n internalDate: message.internalDate\n})\n\n/** The recorded rendering of `message` in `format`, or `undefined` when none is recorded. */\nconst renderMessage = (\n message: GoogleEmulatorGmailMessage,\n format: MessageFormat\n): Schema.JsonObject | undefined => {\n switch (format) {\n case 'minimal':\n return message.minimal ? head(message) : undefined\n case 'metadata':\n return message.metadataPayload === null\n ? undefined\n : { ...head(message), payload: message.metadataPayload }\n case 'full':\n return message.fullPayload === null\n ? undefined\n : { ...head(message), payload: message.fullPayload }\n }\n}\n\n/** The `{ id, threadId, labelIds }` answer of a label change, trash, or untrash. */\nconst labelsAnswer = (\n message: GoogleEmulatorGmailMessage,\n labelIds: ReadonlyArray<string>\n): Response =>\n googleJson(200, { id: message.id, threadId: message.threadId, labelIds: [...labelIds] })\n\nconst findMessage = (state: GoogleEmulatorState, id: string) =>\n state.messages.find(message => message.id === id)\n\nconst isImpliedMessage = (state: GoogleEmulatorState, id: string): boolean =>\n state.impliedMessages.some(message => message.id === id)\n\nconst isDraftMessage = (message: GoogleEmulatorGmailMessage): boolean =>\n message.labelIds.includes('DRAFT')\n\nconst replaceMessage = (\n state: GoogleEmulatorState,\n next: GoogleEmulatorGmailMessage\n): ReadonlyArray<GoogleEmulatorGmailMessage> =>\n state.messages.map(message => (message.id === next.id ? next : message))\n\n// Listing by label.\n\ntype MessagesPageHead = {\n readonly messages: ReadonlyArray<Schema.Json>\n nextPageToken?: string\n}\n\ntype ListInput = {\n readonly labelId: string\n readonly maxResults: number\n readonly pageToken: string | undefined\n}\n\nconst listMessages: GoogleRoute = statefulRoute(\n gmail('GET', '/messages', false, [listCase, listThreadsCase]),\n 'none',\n (request): ListInput | NotEmulated => {\n const query = exactQuery(request, ['labelIds', 'maxResults'], ['pageToken'])\n\n if (isNotEmulated(query)) return query\n\n const labelId = query['labelIds'] ?? ''\n\n if (!gmailIdSegment.test(labelId)) return notEmulated('labelIds must be one label id')\n\n const maxResults = pageSize(query['maxResults'], 'maxResults', 1, 500)\n\n if (isNotEmulated(maxResults)) return maxResults\n\n const pageToken = query['pageToken']\n\n return pageToken === ''\n ? notEmulated('an empty pageToken is not emulated')\n : { labelId, maxResults, pageToken }\n },\n (state, input, { env }) => {\n const known =\n state.impliedLabelIds.includes(input.labelId) ||\n state.labels.some(label => label.id === input.labelId)\n\n if (!known) return notEmulated('listing a label the state does not hold is not emulated')\n\n const matches: ReadonlyArray<GoogleEmulatorGmailMessage | GoogleEmulatorImpliedMessage> = [\n ...state.messages,\n ...state.impliedMessages\n ].filter(message => message.labelIds.includes(input.labelId))\n\n // Every recorded listing has results; an empty one is no fixture's answer.\n if (matches.length === 0) {\n return notEmulated('a listing without messages is not emulated (no fixture records one)')\n }\n\n if (matches.some(message => message.labelIds.some(id => id === 'TRASH' || id === 'SPAM'))) {\n return notEmulated('a listing that would leave out messages in Trash or Spam is not emulated')\n }\n\n return listPage(\n env,\n 'gmail',\n `gmail\\u0000${input.labelId}\\u0000${input.maxResults}`,\n matches.map(message => ({ id: message.id, threadId: message.threadId })),\n input.maxResults,\n input.pageToken,\n env.drills.gmailPageRepeats,\n (page, nextPageToken) => {\n const head: MessagesPageHead = { messages: [...page] }\n\n // The last page carries no `nextPageToken`.\n if (nextPageToken !== undefined) head.nextPageToken = nextPageToken\n\n return googleJson(200, { ...head, resultSizeEstimate: matches.length })\n }\n )\n }\n)\n\n// Thread listing by label.\n\ntype ThreadsPageHead = {\n readonly threads: ReadonlyArray<Schema.Json>\n nextPageToken?: string\n}\n\nconst listThreads: GoogleRoute = statefulRoute(\n gmail('GET', '/threads', false, [listThreadsCase]),\n 'none',\n (request): ListInput | NotEmulated => {\n const query = exactQuery(request, ['labelIds', 'maxResults'], ['pageToken'])\n\n if (isNotEmulated(query)) return query\n\n const labelId = query['labelIds'] ?? ''\n\n if (!gmailIdSegment.test(labelId)) return notEmulated('labelIds must be one label id')\n\n const maxResults = pageSize(query['maxResults'], 'maxResults', 1, 500)\n\n if (isNotEmulated(maxResults)) return maxResults\n\n const pageToken = query['pageToken']\n\n return pageToken === ''\n ? notEmulated('an empty pageToken is not emulated')\n : { labelId, maxResults, pageToken }\n },\n (state, input, { env }) => {\n const known =\n state.impliedLabelIds.includes(input.labelId) ||\n state.labels.some(label => label.id === input.labelId)\n\n if (!known) return notEmulated('listing a label the state does not hold is not emulated')\n\n const messages: ReadonlyArray<GoogleEmulatorGmailMessage | GoogleEmulatorImpliedMessage> = [\n ...state.messages,\n ...state.impliedMessages\n ]\n\n const matches = messages.filter(message => message.labelIds.includes(input.labelId))\n\n if (matches.length === 0) {\n return notEmulated('a listing without threads is not emulated (no fixture records one)')\n }\n\n const threadIds = [...new Set(matches.map(message => message.threadId))]\n\n // Gmail leaves out threads in Trash or Spam; no fixture records that, so refuse it.\n const hidden = messages.some(\n message =>\n threadIds.includes(message.threadId) &&\n message.labelIds.some(id => id === 'TRASH' || id === 'SPAM')\n )\n\n if (hidden) {\n return notEmulated('a listing that would leave out threads in Trash or Spam is not emulated')\n }\n\n const threads = threadIds.map(id => state.impliedThreads.find(thread => thread.id === id))\n\n if (threads.some(thread => thread === undefined)) {\n return notEmulated('listing a thread no thread listing fixture names is not emulated')\n }\n\n return listPage(\n env,\n 'gmail-threads',\n `gmail-threads\\u0000${input.labelId}\\u0000${input.maxResults}`,\n threads.flatMap(thread =>\n thread === undefined\n ? []\n : [{ id: thread.id, snippet: thread.snippet, historyId: thread.historyId }]\n ),\n input.maxResults,\n input.pageToken,\n env.drills.gmailThreadPageRepeats,\n (page, nextPageToken) => {\n const head: ThreadsPageHead = { threads: [...page] }\n\n // The last page carries no `nextPageToken`.\n if (nextPageToken !== undefined) head.nextPageToken = nextPageToken\n\n return googleJson(200, { ...head, resultSizeEstimate: threads.length })\n }\n )\n }\n)\n\n// Message reads.\n\n/** Header names of one `metadataHeaders` selection, in request order (`undefined`: none sent). */\ntype HeaderSelection = ReadonlyArray<string> | undefined\n\ntype MessageRead = {\n readonly id: string\n readonly format: MessageFormat\n readonly metadataHeaders: HeaderSelection\n}\n\nconst formats: ReadonlyArray<string> = ['minimal', 'metadata', 'full']\n\nconst isFormat = (value: string | undefined): value is MessageFormat =>\n value !== undefined && formats.includes(value)\n\n/** The connector's bound on one selection (`gmailMetadataHeadersMaxItems`), copied as data. */\nconst metadataHeadersMaxItems = 50\n\n/** One RFC 5322 header field name, as the connector sends it. */\nconst headerNamePattern = /^[!-9;-~]{1,128}$/\n\n/**\n * The `format` and the `metadataHeaders` selection of a read: the selection only with\n * `format=metadata`, 1 to 50 distinct header names; not emulated otherwise.\n */\nconst readFormat = (\n request: EmulatedRequest\n): { readonly format: MessageFormat; readonly metadataHeaders: HeaderSelection } | NotEmulated => {\n const query = exactQuery(request, ['format'], ['metadataHeaders'], {\n repeatable: ['metadataHeaders']\n })\n\n if (isNotEmulated(query)) return query\n\n const format = query['format']\n\n if (!isFormat(format)) return notEmulated('format must be minimal, metadata, or full')\n\n const names = request.query.getAll('metadataHeaders')\n\n if (names.length === 0) return { format, metadataHeaders: undefined }\n\n if (format !== 'metadata') {\n return notEmulated('metadataHeaders with a format other than metadata is not emulated')\n }\n\n const valid =\n names.length <= metadataHeadersMaxItems &&\n new Set(names).size === names.length &&\n names.every(name => headerNamePattern.test(name))\n\n return valid\n ? { format, metadataHeaders: names }\n : notEmulated('metadataHeaders must be 1 to 50 distinct header names')\n}\n\nconst isHeader = (value: Schema.Json): value is Schema.JsonObject & { readonly name: string } =>\n isJsonObject(value) && Predicate.isString(value.name)\n\n/**\n * `rendered` (a metadata rendering) keeping only the recorded top-level headers the selection\n * names, in recorded order; not emulated when a selected name is not exactly the name of one of its\n * recorded headers (no fixture records a selection of an absent header or in another case).\n * `ignore` (a drill) answers the rendering unchanged.\n */\nconst selectHeaders = (\n rendered: Schema.JsonObject,\n selection: HeaderSelection,\n ignore: boolean\n): Schema.JsonObject | NotEmulated => {\n if (selection === undefined) return rendered\n\n const payload = rendered.payload\n const headers = isJsonObject(payload) && Array.isArray(payload.headers) ? payload.headers : []\n const recorded = headers.filter(isHeader)\n\n if (\n !isJsonObject(payload) ||\n recorded.length !== headers.length ||\n !selection.every(name => recorded.some(header => header.name === name))\n ) {\n return notEmulated(\n 'a metadataHeaders selection naming a header the recorded rendering lacks is not emulated'\n )\n }\n\n if (ignore) return rendered\n\n return {\n ...rendered,\n payload: { ...payload, headers: recorded.filter(header => selection.includes(header.name)) }\n }\n}\n\nconst getMessage: GoogleRoute = statefulRoute(\n gmail(\n 'GET',\n '/messages/{messageId}',\n false,\n [attachmentCase, notFoundCase, metadataHeadersCase, labelCase, draftCase, trashCase, sendCase],\n ['messageId']\n ),\n 'none',\n (request): MessageRead | NotEmulated => {\n const read = readFormat(request)\n\n return isNotEmulated(read) ? read : { id: param(request, 'messageId'), ...read }\n },\n (state, input, { env }) => {\n const message = findMessage(state, input.id)\n\n if (message !== undefined) {\n const rendered = renderMessage(message, input.format)\n\n if (rendered === undefined) {\n return notEmulated(`no fixture records this message with format=${input.format}`)\n }\n\n const selected = selectHeaders(\n rendered,\n input.metadataHeaders,\n env.drills.metadataHeadersIgnored\n )\n\n return isNotEmulated(selected) ? selected : answer(() => googleJson(200, selected))\n }\n\n if (isImpliedMessage(state, input.id)) {\n return notEmulated('reading a message a fixture only names in a listing is not emulated')\n }\n\n // The recorded not-found answer: a minimal read of an id the mailbox does not hold.\n return input.format === 'minimal' &&\n input.metadataHeaders === undefined &&\n absentMessageIdPattern.test(input.id)\n ? answer(() => notFound(env))\n : notEmulated('only a format=minimal read of an absent 16-hex-digit id is recorded')\n }\n)\n\ntype AttachmentRead = { readonly messageId: string; readonly attachmentId: string }\n\nconst getAttachment: GoogleRoute = statefulRoute(\n gmail(\n 'GET',\n '/messages/{messageId}/attachments/{attachmentId}',\n false,\n [attachmentCase],\n ['messageId', 'attachmentId']\n ),\n 'none',\n (request): AttachmentRead | NotEmulated =>\n withoutQuery(request) ?? {\n messageId: param(request, 'messageId'),\n attachmentId: param(request, 'attachmentId')\n },\n (state, input, { env }) => {\n const attachment = state.attachments.find(\n item => item.messageId === input.messageId && item.attachmentId === input.attachmentId\n )\n\n if (attachment === undefined || findMessage(state, input.messageId) === undefined) {\n return notEmulated('an attachment the state does not hold is not emulated')\n }\n\n const data = env.drills.attachmentStandardBase64\n ? attachment.data.replaceAll('-', '+').replaceAll('_', '/')\n : attachment.data\n\n return answer(() => googleJson(200, { size: attachment.size, data }))\n }\n)\n\n// Labels.\n\nconst createLabel: GoogleRoute = statefulRoute(\n gmail('POST', '/labels', true, [labelCase]),\n 'json',\n (request): string | NotEmulated => {\n const body = withoutQuery(request) ?? exactBodyKeys(request.json, 'the label body', ['name'])\n\n if (isNotEmulated(body)) return body\n\n return Predicate.isString(body.name) && isRunText(body.name, 'label')\n ? body.name\n : notEmulated('a label name other than \"yolk-conformance <runId> label\" is not emulated')\n },\n (state, name) => {\n if (state.labels.some(label => label.name === name)) {\n return notEmulated('creating a label whose name exists is not emulated')\n }\n\n // Refused before any fault: no minted label id is left.\n if (state.counters.nextLabelNumber > lastLabelNumber) {\n return notEmulated('creating a label when no Label_<n> id is left is not emulated')\n }\n\n return () => {\n const number = state.counters.nextLabelNumber\n\n const label = {\n id: `Label_${number}`,\n name,\n messageListVisibility: 'show',\n labelListVisibility: 'labelShow',\n type: 'user'\n }\n\n state.counters = { ...state.counters, nextLabelNumber: number + 1 }\n state.labels = [...state.labels, label]\n\n return googleJson(200, { ...label })\n }\n }\n)\n\nconst getLabel: GoogleRoute = statefulRoute(\n gmail('GET', '/labels/{labelId}', false, [labelCase], ['labelId']),\n 'none',\n request => withoutQuery(request) ?? param(request, 'labelId'),\n (state, id, { env }) => {\n if (state.labels.some(label => label.id === id) || state.impliedLabelIds.includes(id)) {\n return notEmulated('no fixture records a label read of an existing label')\n }\n\n return mintedLabelIdPattern.test(id)\n ? answer(() => notFound(env))\n : notEmulated('only a read of an absent Label_<n> id is recorded')\n }\n)\n\nconst deleteLabel: GoogleRoute = statefulRoute(\n gmail('DELETE', '/labels/{labelId}', true, [labelCase], ['labelId']),\n 'none',\n request => withoutQuery(request) ?? param(request, 'labelId'),\n (state, id, { env }) => {\n if (!state.labels.some(label => label.id === id)) {\n return notEmulated('only deleting a label created here is recorded')\n }\n\n return () => {\n const without = <M extends { readonly labelIds: ReadonlyArray<string> }>(message: M): M =>\n message.labelIds.includes(id)\n ? { ...message, labelIds: message.labelIds.filter(label => label !== id) }\n : message\n\n state.labels = state.labels.filter(label => label.id !== id)\n\n // Deleting a label removes it from every message (the label fixture's last read).\n if (!env.drills.labelDeleteKeepsOnMessages) {\n state.messages = state.messages.map(without)\n state.impliedMessages = state.impliedMessages.map(without)\n }\n\n return googleNoContent()\n }\n }\n)\n\n// Label changes, trash, and untrash.\n\ntype ModifyInput = { readonly messageId: string; readonly labelId: string }\n\nconst modifyMessage: GoogleRoute = statefulRoute(\n gmail('POST', '/messages/{messageId}/modify', true, [labelCase], ['messageId']),\n 'json',\n (request): ModifyInput | NotEmulated => {\n const body =\n withoutQuery(request) ?? exactBodyKeys(request.json, 'the modify body', ['addLabelIds'])\n\n if (isNotEmulated(body)) return body\n\n const added = body.addLabelIds\n\n if (!Array.isArray(added) || added.length !== 1 || !Predicate.isString(added[0])) {\n return notEmulated('a modify adding other than one label is not emulated')\n }\n\n return { messageId: param(request, 'messageId'), labelId: added[0] }\n },\n (state, input) => {\n const message = findMessage(state, input.messageId)\n\n if (message === undefined || isDraftMessage(message)) {\n return notEmulated('changing the labels of a message the state does not hold is not emulated')\n }\n\n if (!state.labels.some(label => label.id === input.labelId)) {\n return notEmulated('adding a label other than one created here is not emulated')\n }\n\n if (message.labelIds.includes(input.labelId)) {\n return notEmulated('adding a label the message carries already is not emulated')\n }\n\n return () => {\n const next = { ...message, labelIds: [...message.labelIds, input.labelId] }\n\n state.messages = replaceMessage(state, next)\n\n return labelsAnswer(next, next.labelIds)\n }\n }\n)\n\nconst trashRoute = (action: 'trash' | 'untrash'): GoogleRoute =>\n statefulRoute(\n gmail('POST', `/messages/{messageId}/${action}`, true, [trashCase], ['messageId']),\n 'none',\n request => withoutQuery(request) ?? param(request, 'messageId'),\n (state, id, { env }) => {\n const message = findMessage(state, id)\n\n if (message === undefined || isDraftMessage(message)) {\n return notEmulated(`${action} of a message the state does not hold is not emulated`)\n }\n\n const inTrash = message.labelIds.includes('TRASH')\n\n if (action === 'trash' ? inTrash : !inTrash) {\n return notEmulated(\n action === 'trash'\n ? 'trashing a message already in Trash is not emulated'\n : 'untrashing a message not in Trash is not emulated'\n )\n }\n\n return () => {\n const labelIds =\n action === 'trash'\n ? [...message.labelIds, 'TRASH']\n : message.labelIds.filter(label => label !== 'TRASH')\n\n const next = { ...message, labelIds }\n\n state.messages = replaceMessage(state, next)\n\n return labelsAnswer(\n next,\n action === 'trash' && env.drills.trashAnswerOmitsTrash\n ? labelIds.filter(label => label !== 'TRASH')\n : labelIds\n )\n }\n }\n )\n\n// Drafts.\n\nconst base64UrlPattern = /^[A-Za-z0-9_-]*$/\n\n/** The UTF-8 text of canonical unpadded base64url, or `undefined`. */\nconst decodeBase64UrlText = (raw: string): string | undefined => {\n if (!base64UrlPattern.test(raw) || raw.length % 4 === 1) return undefined\n\n try {\n const binary = atob(raw.replaceAll('-', '+').replaceAll('_', '/'))\n const bytes = Uint8Array.from(binary, char => char.charCodeAt(0))\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\n // Canonical only: the encoding the connector writes, byte for byte.\n return base64UrlOfText(text) === raw ? text : undefined\n } catch {\n return undefined\n }\n}\n\nconst draftBoundary = '=_yolk-draft-alternative'\n\nconst draftContentType = `multipart/alternative; boundary=\"${draftBoundary}\"`\n\n/** The quoted-printable part of the recorded draft MIME. */\nconst recordedDraftPart = (type: 'plain' | 'html', encoded: string): string =>\n `Content-Type: text/${type}; charset=UTF-8\\r\\nContent-Transfer-Encoding: quoted-printable\\r\\n\\r\\n${encoded}`\n\n/** The draft MIME the draft fixture records after the `Subject` line, for each draft kind. */\nconst recordedDraftMime = (plain: string, html: string): string =>\n [\n 'MIME-Version: 1.0',\n `Content-Type: ${draftContentType}`,\n '',\n `--${draftBoundary}`,\n recordedDraftPart('plain', plain),\n `--${draftBoundary}`,\n recordedDraftPart('html', html),\n `--${draftBoundary}--`\n ].join('\\r\\n')\n\nconst recordedDrafts: Record<\n 'compose' | 'update',\n { readonly text: string; readonly mime: string }\n> = {\n compose: {\n text: draftText,\n mime: recordedDraftMime(\n 'Synthetic conformance draft, safe to delete: gr=C3=BC=C3=9Fe =E2=9C=93',\n '<div dir=3D\"ltr\">Synthetic conformance draft, safe to delete: gr=C3=BC=\\r\\n=C3=9Fe =E2=9C=93</div>'\n )\n },\n update: {\n text: updatedDraftText,\n mime: recordedDraftMime(\n 'Updated synthetic conformance draft: =C2=A1hola! =E2=9C=93',\n '<div dir=3D\"ltr\">Updated synthetic conformance draft: =C2=A1hola! =E2=9C=93=\\r\\n</div>'\n )\n }\n}\n\nconst draftMimePattern = /^Subject: ([^\\r\\n]*)\\r\\n([\\s\\S]*)$/\n\ntype DraftContent = { readonly subject: string; readonly body: string }\n\n/** The reasons a draft `message.raw` is refused with (constants; never derived from a request). */\nconst draftKeysReason = 'message has a key this route does not take'\n\nconst canonicalRawReason = 'message.raw must be canonical base64url UTF-8 MIME'\n\nconst otherDraftReason = (kind: 'compose' | 'update'): string =>\n `a draft ${kind} other than the recorded run draft is not emulated`\n\n/**\n * Every reason `readDraftRaw` refuses a draft of `kind` with: the route's declared\n * `viewRefusalReasons`, so the wrapper ledgers exactly these (and nothing derived from a request).\n */\nconst draftRefusalReasons = (kind: 'compose' | 'update'): ReadonlyArray<string> => [\n draftKeysReason,\n canonicalRawReason,\n otherDraftReason(kind),\n sizedRunIdReason('draft')\n]\n\ntype DraftRaw = {\n /** The decoded MIME when `message.raw` is canonical base64url UTF-8 (decoded once). */\n readonly decoded: string | undefined\n readonly content: DraftContent | NotEmulated\n}\n\n/** The recorded draft MIME (no recipient) of a compose or an update, decoded once. */\nconst readDraftRaw = (message: Schema.Json | undefined, kind: 'compose' | 'update'): DraftRaw => {\n // Decode `raw` before the key check, so a cleanly decoded raw is always available to the\n // credential guard (a bearer inside it is a repeat, whatever else is wrong with `message`).\n const raw =\n Predicate.hasProperty(message, 'raw') && !Array.isArray(message) ? message.raw : undefined\n\n const decoded = Predicate.isString(raw) ? decodeBase64UrlText(raw) : undefined\n\n const fields = exactBodyKeys(message, 'message', ['raw'])\n\n if (isNotEmulated(fields)) return { decoded, content: fields }\n\n if (decoded === undefined) return { decoded, content: notEmulated(canonicalRawReason) }\n\n const parts = draftMimePattern.exec(decoded)\n const subject = parts?.[1] ?? ''\n const rest = parts?.[2] ?? ''\n\n const runId =\n kind === 'compose'\n ? runIdOf(subject, 'draft', draftSubjectRest)\n : runIdOf(subject, 'draft updated', draftSubjectRest)\n\n const recorded = recordedDrafts[kind]\n\n if (parts === null || runId === undefined || rest !== recorded.mime) {\n return { decoded, content: notEmulated(otherDraftReason(kind)) }\n }\n\n return {\n decoded,\n content:\n runId.length === recordedRunIdLength\n ? { subject, body: recorded.text }\n : notEmulated(sizedRunIdReason('draft'))\n }\n}\n\n/**\n * The decoded view of a draft body for the credential guard (Gmail's own wire format wraps the\n * draft MIME in base64url `message.raw`). Fail closed: when the body is a JSON object whose\n * `message` object carries `raw`, the view returns the decoded MIME only when it is exactly the\n * recorded draft MIME of this route (`kind`), the run id aside. Any other raw makes it throw a\n * `DecodedViewRefusal` with the route's own constant reason (one of `draftRefusalReasons`) and\n * whatever it decoded cleanly: the wrapper ledgers a repeat when that text holds the bearer, and\n * the declared reason otherwise, before anything is recorded, so a refused raw (line-wrapped, the\n * standard alphabet, a stray character, RFC 2047 words, quoted-printable, UTF-16, a 12-character\n * run id, ...) never reaches the ledger. A body without `message.raw` yields no view (the route's\n * own shape check refuses it).\n */\nconst draftRawViews =\n (kind: 'compose' | 'update') =>\n (body: string): ReadonlyArray<string> => {\n const parsed = parseJsonText(body)\n const message = isJsonObject(parsed) ? parsed.message : undefined\n\n if (!isJsonObject(message) || !('raw' in message)) return []\n\n const { decoded, content } = readDraftRaw(message, kind)\n\n if (isNotEmulated(content)) {\n throw new DecodedViewRefusal({\n reason: content.reason,\n decoded: decoded === undefined ? [] : [decoded]\n })\n }\n\n return decoded === undefined ? [] : [decoded]\n }\n\n/** A draft's `multipart/alternative` payload as the draft fixture's metadata read records it. */\nconst draftPayload = (subject: string): Schema.JsonObject => ({\n partId: '',\n mimeType: 'multipart/alternative',\n filename: '',\n headers: [\n { name: 'Subject', value: subject },\n { name: 'Content-Type', value: draftContentType }\n ],\n body: { size: 0 }\n})\n\n/** A `format=full` text part, its `body.data` transfer-decoded as the draft fixture records it. */\nconst draftTextPart = (\n partId: string,\n type: 'plain' | 'html',\n content: string\n): Schema.JsonObject => ({\n partId,\n mimeType: `text/${type}`,\n filename: '',\n headers: [\n { name: 'Content-Type', value: `text/${type}; charset=UTF-8` },\n { name: 'Content-Transfer-Encoding', value: 'quoted-printable' }\n ],\n body: {\n size: new TextEncoder().encode(content).byteLength,\n data: base64UrlOfText(content)\n }\n})\n\n/** A draft message as the draft fixture records it (the metadata rendering only on compose). */\nconst draftMessage = (\n id: string,\n threadId: string,\n content: DraftContent,\n withMetadata: boolean\n): GoogleEmulatorGmailMessage => ({\n id,\n threadId,\n labelIds: ['DRAFT'],\n snippet: content.body,\n sizeEstimate: 512,\n historyId: '900020',\n internalDate: recordedInternalDate,\n minimal: false,\n metadataPayload: withMetadata ? draftPayload(content.subject) : null,\n fullPayload: {\n ...draftPayload(content.subject),\n parts: [\n draftTextPart('0', 'plain', content.body),\n draftTextPart('1', 'html', `<div dir=\"ltr\">${content.body}</div>`)\n ]\n }\n})\n\nconst draftAnswer = (draftId: string, message: GoogleEmulatorGmailMessage): Response =>\n googleJson(200, {\n id: draftId,\n message: { id: message.id, threadId: message.threadId, labelIds: [...message.labelIds] }\n })\n\nconst composeDraft: GoogleRoute = statefulRoute(\n {\n ...gmail('POST', '/drafts', true, [draftCase]),\n decodedViews: draftRawViews('compose'),\n viewRefusalReasons: draftRefusalReasons('compose')\n },\n 'json',\n (request): DraftContent | NotEmulated => {\n const body = withoutQuery(request) ?? exactBodyKeys(request.json, 'the draft body', ['message'])\n\n return isNotEmulated(body) ? body : readDraftRaw(body.message, 'compose').content\n },\n (state, content) => () => {\n const draftNumber = state.counters.nextDraftNumber\n const messageNumber = state.counters.nextDraftMessageNumber\n const id = mintedMessageId('d', messageNumber)\n const message = draftMessage(id, id, content, true)\n const draftId = mintedDraftId(draftNumber)\n\n state.counters = {\n ...state.counters,\n nextDraftNumber: draftNumber + 1,\n nextDraftMessageNumber: messageNumber + 1\n }\n state.messages = [...state.messages, message]\n state.drafts = [...state.drafts, { id: draftId, messageId: id }]\n\n return draftAnswer(draftId, message)\n }\n)\n\ntype UpdateInput = { readonly draftId: string; readonly content: DraftContent }\n\nconst updateDraft: GoogleRoute = statefulRoute(\n {\n ...gmail('PUT', '/drafts/{draftId}', true, [draftCase], ['draftId']),\n decodedViews: draftRawViews('update'),\n viewRefusalReasons: draftRefusalReasons('update')\n },\n 'json',\n (request): UpdateInput | NotEmulated => {\n const draftId = param(request, 'draftId')\n\n const body =\n withoutQuery(request) ?? exactBodyKeys(request.json, 'the draft body', ['id', 'message'])\n\n if (isNotEmulated(body)) return body\n\n if (body.id !== draftId) return notEmulated('a body id other than the path draft id')\n\n const content = readDraftRaw(body.message, 'update').content\n\n return isNotEmulated(content) ? content : { draftId, content }\n },\n (state, input, { env }) => {\n const draft = state.drafts.find(candidate => candidate.id === input.draftId)\n const previous = draft === undefined ? undefined : findMessage(state, draft.messageId)\n\n if (draft === undefined || previous === undefined) {\n return notEmulated('updating a draft the state does not hold is not emulated')\n }\n\n return () => {\n const number = state.counters.nextDraftMessageNumber\n const id = mintedMessageId('d', number)\n\n const message: GoogleEmulatorGmailMessage = env.drills.draftUpdateKeepsContent\n ? { ...previous, id, metadataPayload: null }\n : draftMessage(id, previous.threadId, input.content, false)\n\n state.counters = { ...state.counters, nextDraftMessageNumber: number + 1 }\n state.messages = [\n ...state.messages.filter(candidate => candidate.id !== previous.id),\n message\n ]\n state.drafts = state.drafts.map(candidate =>\n candidate.id === draft.id ? { ...candidate, messageId: id } : candidate\n )\n\n return draftAnswer(draft.id, message)\n }\n }\n)\n\nconst deleteDraft: GoogleRoute = statefulRoute(\n gmail('DELETE', '/drafts/{draftId}', true, [draftCase], ['draftId']),\n 'none',\n request => withoutQuery(request) ?? param(request, 'draftId'),\n (state, id, { env }) => {\n const draft = state.drafts.find(candidate => candidate.id === id)\n\n if (draft === undefined) {\n // The recorded repeated delete: an absent draft answers the not-found envelope.\n return draftIdPattern.test(id)\n ? answer(() => notFound(env))\n : notEmulated('only deleting an absent r-<digits> draft id is recorded')\n }\n\n return () => {\n state.drafts = state.drafts.filter(candidate => candidate.id !== id)\n state.messages = state.messages.filter(message => message.id !== draft.messageId)\n\n return googleNoContent()\n }\n }\n)\n\ntype ThreadRead = {\n readonly threadId: string\n readonly format: MessageFormat\n readonly metadataHeaders: HeaderSelection\n}\n\nconst getThread: GoogleRoute = statefulRoute(\n gmail('GET', '/threads/{threadId}', false, [draftCase, metadataHeadersCase], ['threadId']),\n 'none',\n (request): ThreadRead | NotEmulated => {\n const read = readFormat(request)\n\n if (isNotEmulated(read)) return read\n\n // Recorded: a full read of a draft thread, and a metadata read with a metadataHeaders selection.\n if (\n read.format === 'minimal' ||\n (read.format === 'metadata') !== (read.metadataHeaders !== undefined)\n ) {\n return notEmulated(\n 'a thread read other than format=full, or format=metadata with metadataHeaders, is not emulated'\n )\n }\n\n return { threadId: param(request, 'threadId'), ...read }\n },\n (state, input, { env }) => {\n const messages = state.messages.filter(message => message.threadId === input.threadId)\n\n if (state.impliedMessages.some(message => message.threadId === input.threadId)) {\n return notEmulated('a thread holding a message a fixture only names is not emulated')\n }\n\n const createdDrafts = messages.every(\n message => isDraftMessage(message) && mintedMessageIdPattern.test(message.id)\n )\n\n // Full: only draft threads created here are recorded (a seeded message's thread is not).\n // Metadata: only threads of stored messages that are not drafts are recorded.\n const recorded =\n messages.length > 0 &&\n (input.format === 'full' ? createdDrafts : !messages.some(isDraftMessage))\n\n if (!recorded) {\n return notEmulated(\n input.format === 'full'\n ? 'a thread other than a draft thread created here is not emulated'\n : 'a metadata read of a thread holding a draft is not emulated'\n )\n }\n\n const rendered: Array<Schema.JsonObject> = []\n\n for (const message of messages) {\n const rendering = renderMessage(message, input.format)\n\n if (rendering === undefined) {\n return notEmulated(\n `a thread with a message without a ${input.format} rendering is not emulated`\n )\n }\n\n const selected = selectHeaders(\n rendering,\n input.metadataHeaders,\n env.drills.metadataHeadersIgnored\n )\n\n if (isNotEmulated(selected)) return selected\n\n rendered.push(selected)\n }\n\n return answer(() =>\n googleJson(200, {\n id: input.threadId,\n historyId: messages.at(-1)?.historyId ?? '',\n messages: rendered\n })\n )\n }\n)\n\n// The practice send (upload endpoint).\n\nconst boundaryPattern = /^[A-Za-z0-9_]{1,70}$/\n\ntype SendInput = { readonly boundary: string; readonly subject: string; readonly text: string }\n\n/**\n * The boundary of `multipart/related; boundary=<b>`, or `undefined`. The parameter list is parsed\n * whole: each parameter is split on its first `=`, and the content type must carry exactly one\n * parameter, `boundary`, whose whole value is 1 to 70 of `[A-Za-z0-9_]` (unquoted). Any other,\n * repeated, empty, or malformed parameter is refused (the send records no other parameter).\n */\nconst multipartBoundary = (contentType: string | undefined): string | undefined => {\n if (mediaType(contentType) !== 'multipart/related') return undefined\n\n const params = (contentType ?? '')\n .split(';')\n .slice(1)\n .map(param => {\n const separator = param.indexOf('=')\n\n return separator === -1\n ? undefined\n : {\n name: param.slice(0, separator).trim().toLowerCase(),\n value: param.slice(separator + 1)\n }\n })\n\n const [only] = params\n\n return params.length === 1 &&\n only !== undefined &&\n only.name === 'boundary' &&\n boundaryPattern.test(only.value)\n ? only.value\n : undefined\n}\n\nconst sendMessage: GoogleRoute = statefulRoute(\n evidence(googleEmulatorGmailOrigin, 'POST', '/upload/gmail/v1/users/me/messages/send', true, [\n sendCase\n ]),\n 'bytes',\n (request): SendInput | NotEmulated => {\n const query = exactQuery(request, ['uploadType'])\n\n if (isNotEmulated(query)) return query\n\n const problem = recordedValue(query, 'uploadType', 'multipart')\n\n if (problem !== undefined) return problem\n\n const boundary = multipartBoundary(request.header('content-type'))\n\n if (boundary === undefined) {\n return notEmulated(\n 'a content-type other than multipart/related; boundary=<b> is not emulated'\n )\n }\n\n let text: string\n\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(request.bytes)\n } catch {\n return notEmulated('an upload body that is not 7-bit text is not emulated')\n }\n\n const subject = /\\r\\nSubject: ([^\\r\\n]*)\\r\\n/.exec(text)?.[1] ?? ''\n\n const runId = runIdOf(subject, 'send', sendSubjectRest)\n\n if (runId === undefined) {\n return notEmulated(\n 'a send other than the recorded run-scoped practice message is not emulated'\n )\n }\n\n return runId.length === recordedRunIdLength\n ? { boundary, subject, text }\n : notEmulated(sizedRunIdReason('send'))\n },\n (state, input, { env }) => {\n // The recorded sizeEstimate covers the To and From headers: only the recorded address.\n if (state.practiceAddress !== recordedPracticeAddress) {\n return notEmulated(\n `a send while the seeded practiceAddress is not the recorded ${recordedPracticeAddress} is not emulated (the recorded sizeEstimate covers the address)`\n )\n }\n\n // Only the recorded message, whose ONLY recipient is the seeded practice address.\n if (\n input.text !== uploadBody(input.boundary, practiceMime(state.practiceAddress, input.subject))\n ) {\n return notEmulated(\n 'a send other than the recorded 7-bit message to the seeded practice address only is not emulated'\n )\n }\n\n return () => {\n // Read the clock before any write: a failing clock, or one answering an instant outside the\n // Date range (non-finite or not), writes nothing.\n const instant = new Date(env.now())\n\n if (!Number.isFinite(instant.getTime())) {\n throw new Error('the clock answered an instant outside the Date range')\n }\n\n const date = instant.toUTCString().replace(/GMT$/, '+0000')\n const number = state.counters.nextSentNumber\n const id = mintedMessageId('e', number)\n const address = state.practiceAddress\n\n const headers = [\n { name: 'MIME-Version', value: '1.0' },\n { name: 'Date', value: date },\n { name: 'Message-ID', value: `<synthetic-send-${pad(number, 4)}@example.test>` },\n { name: 'Subject', value: input.subject },\n { name: 'From', value: address },\n { name: 'To', value: address },\n { name: 'Content-Type', value: 'text/plain; charset=us-ascii' }\n ].filter(header => !(env.drills.sentMessageWithoutTo && header.name === 'To'))\n\n // Recorded in the state only: nothing is delivered anywhere.\n const sent: GoogleEmulatorGmailMessage = {\n id,\n threadId: id,\n labelIds: ['SENT', 'INBOX', 'UNREAD'],\n snippet: 'Synthetic conformance message sent to the seeded practice address only.',\n sizeEstimate: 640,\n historyId: '900030',\n internalDate: recordedInternalDate,\n minimal: false,\n metadataPayload: {\n partId: '',\n mimeType: 'text/plain',\n filename: '',\n headers,\n body: { size: 88 }\n },\n fullPayload: null\n }\n\n state.counters = { ...state.counters, nextSentNumber: number + 1 }\n state.messages = [...state.messages, sent]\n\n return googleJson(200, { id, threadId: id, labelIds: ['SENT'] })\n }\n }\n)\n\n/** The Gmail routes, in manifest order. */\nexport const gmailRoutes: ReadonlyArray<GoogleRoute> = [\n listMessages,\n listThreads,\n getMessage,\n getAttachment,\n modifyMessage,\n trashRoute('trash'),\n trashRoute('untrash'),\n createLabel,\n getLabel,\n deleteLabel,\n composeDraft,\n updateDraft,\n deleteDraft,\n getThread,\n sendMessage\n]\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8DA,MAAa,eAAe;AAE5B,MAAM,WAAW;AAEjB,MAAM,iBAAiB;AAEvB,MAAM,eAAe;AAErB,MAAM,kBAAkB;AAExB,MAAM,sBAAsB;AAE5B,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,WAAW;AAEjB,MAAM,SACJ,QACA,MACA,OACA,SACA,SAAgC,CAAC,MAEjC,SACE,2BACA,QACA,GAAG,eAAe,QAClB,OACA,SACA,OAAO,YAAY,OAAO,KAAI,SAAQ,CAAC,MAAM,cAAc,CAAC,CAAC,CAC/D;;AAKF,MAAM,YAAY,QAChB,WACE,KACA,IAAI,OAAO,yBACP,EAAE,OAAO;CAAE,MAAM;CAAK,QAAQ;AAAY,EAAE,IAC5C,gBAAgB,KAAK,mCAAmC,YAAY,WAAW,CACrF;;AAGF,MAAM,yBAAyB;AAE/B,MAAM,iBAAiB;;AAGvB,MAAM,YAAY;AAElB,MAAM,mBAAmB;AAEzB,MAAM,mB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AAM;KAAQ;KACxC;MAAE,MAAM;MAAQ,OAAO;KAAQ;KAC/B;MAAE,MAAM;MAAM,OAAO;KAAQ;KAC7B;MAAE,MAAM;MAAgB,OAAO;KAA+B;IAChE,EAAE,QAAO,WAAU,EAAE,IAAI,OAAO,wBAAwB,OAAO,SAAS,KAgB9D;IACN,MAAM,EAAE,MAAM,GAAG;GACnB;GACA,aAAa;EACf;EAEA,MAAM,WAAW;GAAE,GAAG,MAAM;GAAU,gBAAgB,SAAS;EAAE;EACjE,MAAM,WAAW,CAAC,GAAG,MAAM,UAAU,IAAI;EAEzC,OAAO,WAAW,KAAK;GAAE;GAAI,UAAU;GAAI,UAAU,CAAC,MAAM;EAAE,CAAC;CACjE;AACF,CACF;;AAGA,MAAa,cAA0C;CACrD;CACA;CACA;CACA;CACA;CACA,WAAW,OAAO;CAClB,WAAW,SAAS;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
package/dist/google.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google.d.mts","names":[],"sources":["../src/google.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"google.d.mts","names":[],"sources":["../src/google.ts"],"mappings":";;;;;;;;AAwKsE;AAQtE;;cARa,oBAAA,EAAsB,aAAa,CAAC,qBAAA;;;;;;cAQpC,gBAAA,0BAAgB,MAAA;EAAA;;;;KAEjB,gBAAA,UAA0B,kBAAA,CAAmB,IAAI;;;AAA7D;;;;AAA6D;cAShD,WAAA,0BAAW,MAAA;EAAA;;;;;;;;;;;KAEZ,WAAA,GAAc,aAAa;AAAA,KAE3B,gBAAA,GAAmB,kBAAkB;AAAA,KAErC,iBAAA,GAAoB,mBAAmB;AAAA,KAEvC,cAAA,GAAiB,gBAAgB;AAAA,cAAA,+BAAA;;;;cAGhC,0BAAA,SAAmC,+BAAA;EAAA,SACrC,KAAA,EAAO,iBAAA;EAAA,SACP,MAAA;AAAA;EAAA,IAEI,OAAA,CAAA;AAAA;AAAA,KAKH,qBAAA;sFAED,IAAA,GAAO,kBAAA;;;;;WAKP,GAAA;WAEA,MAAA,GAAS,oBAAoB;AAAA;AAAA,KAG5B,cAAA,GAAiB,mBAAA,CAAoB,mBAAA,EAAqB,kBAAA;;;AA9B/B;AAEvC;;cA6Ca,kBAAA,GACX,OAAA,GAAS,qBAAA,KACR,OAAA,CAAQ,cAAA"}
|
package/dist/google.mjs
CHANGED
|
@@ -86,8 +86,9 @@ import { Data, Predicate } from "effect";
|
|
|
86
86
|
* draft compose and update routes, `message.raw` must be canonical unpadded base64url of exactly
|
|
87
87
|
* the recorded draft MIME of that route, the run id aside; any other `message.raw` (line-wrapped,
|
|
88
88
|
* the standard alphabet, padded, with a stray character, or with MIME-level encodings such as RFC
|
|
89
|
-
* 2047 encoded-words, quoted-printable, or UTF-16) is refused
|
|
90
|
-
* fault is decided, as a constant entry with the route's own
|
|
89
|
+
* 2047 encoded-words, quoted-printable other than the recorded parts, or UTF-16) is refused
|
|
90
|
+
* before anything is recorded or a fault is decided, as a constant entry with the route's own
|
|
91
|
+
* declared reason
|
|
91
92
|
* (`message.raw must be canonical base64url UTF-8 MIME`,
|
|
92
93
|
* `a draft compose other than the recorded run draft is not emulated` or its `update` form, the
|
|
93
94
|
* 13-character run-id reason, or `message has a key this route does not take`), or
|
package/dist/google.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google.mjs","names":[],"sources":["../src/google.ts"],"sourcesContent":["/**\n * Stateful Google emulator (the Gmail, Calendar, and Drive routes the Google conformance cases\n * send), built on the upstream `@emulators/core` custom runtime, with a request ledger, status\n * faults, and an `/_emulate/*` control plane.\n *\n * It never imports SDK code: its wire shapes, error envelopes, and default seed are copied as data\n * from the synthetic Google conformance fixtures, and every route names the conformance cases it\n * follows in `googleEmulatorRoutes`. Only the routes those fifteen cases (with their cleanup) send\n * are emulated: Gmail on `https://gmail.googleapis.com` (`/gmail/v1/users/me/...` and the multipart\n * send upload), Calendar and Drive on `https://www.googleapis.com` (`/calendar/v3` and\n * `/drive/v3`). Each route answers only on its recorded origin (`fetchOn(origin)` serves one origin\n * behind a loopback rewrite). Response behaviour comes only from the fixtures: anything they do not\n * show answers one ledgered 400 not-emulated, writes nothing, and uses up no fault. That includes\n * an empty listing and every read of the leftover lookup (`findGoogleConformanceLeftovers`, whose\n * label listing, draft search, and free-text event query no fixture records): the lookup fails, and\n * runners print their lookup-failed WARN.\n *\n * The practice send (`google.gmail.send-practice-address`) is irreversible on Gmail. Here it is\n * only recorded in the state (the sent message reads back; nothing is delivered anywhere), and only\n * the recorded 7-bit message whose sole recipient header is `To: <the seeded practice address>`\n * is accepted, and only while that address is the recorded `practice@example.test` (the recorded\n * `sizeEstimate` covers it, as it covers the draft and send subjects, which therefore take only a\n * run id of the fixtures' 13-character length).\n *\n * Fail closed: Google follows the shared fail-closed rule of `src/stateful-emulator.ts` (its opt-in\n * `failClosed` mode, the same rule as `/github`). Every route parameter has a raw pattern matched\n * in full, so a request is recognised only when its raw path is exactly an emulated route shape\n * under that route's method and any `Authorization` header is exactly `Bearer <token>` with a\n * recognisable bearer (below); every other request is ledgered and answered with constant text only\n * (`/<unrecognised>`, a standard method or `<other>`, an empty query, no body, a constant reason).\n * The bearer value is never compared against anything, stored, forwarded, or ledgered. A recognised\n * request that repeats it in its raw path, any path segment, the query or any query key or value,\n * the recorded `content-type` header, or its raw body (the multipart send body included), or, on\n * the draft compose and update routes, in the base64url-decoded MIME of `message.raw` (Gmail's own\n * wire format wraps the draft this way; the routes give it to the wrapper as a decoded view), is\n * ledgered as the constant credential-repeat entry, checked through the wrapper's fixpoint closure\n * of a tolerant percent-decode and a tolerant JSON-unescape; any other recognised request has the\n * bearer scrubbed from its ledgered fields and every not-emulated reason. A `message.raw` the route\n * would refuse (anything but canonical unpadded base64url of exactly the recorded draft MIME, the\n * run id aside) makes the view throw a `DecodedViewRefusal` with one of the route's declared\n * constant reasons (`viewRefusalReasons`: the canonical-base64url reason, the\n * other-than-the-recorded-run-draft reason, the 13-character run-id reason, the extra-key reason),\n * which the wrapper ledgers in the constant entry before anything is recorded (or\n * `the request body repeats the credential` when the raw decodes cleanly to text holding the\n * bearer), so a refused `message.raw` never reaches the ledger. Google refusals use the wrapper's\n * constant-reason `exactQuery` and `exactBodyKeys`, so they never echo a request's own query or\n * body keys.\n *\n * Request-shape latitude (`/google`, the only accepted deviations): any bearer value in the RFC\n * 6750 `b64token` syntax (`[A-Za-z0-9\\-._~+/]+=*`) of at least 8 characters, starting with a\n * character in `[G-Zg-z\\-._~+/]` other than `n`, `r`, `t`, `u`, with at least one outside\n * `[0-9.eE+-]` (Google's `ya29.…` access tokens qualify), that occurs nowhere else in the request\n * (never compared against anything, stored, or ledgered); extra request headers (except\n * `X-Goog-Drive-Resource-Keys`, which no fixture sends); JSON key order; `content-type` media-type\n * parameters on JSON requests; query parameters in any order; any `run-` run id (at most 40\n * characters) in a run-scoped label name, event summary, or folder name; in a draft subject\n * (compose and update) and the sent subject, only a run id of exactly 13 characters, the length of\n * the fixtures' `run-synthetic`, because the recorded `sizeEstimate` of the draft and sent messages\n * (answered by their message reads and the draft thread) covers the subject; on the practice send,\n * a `content-type` of exactly `multipart/related; boundary=<b>` with any one unquoted boundary of 1\n * to 70 `[A-Za-z0-9_]` characters and no other parameter; a `gmail.list` or `gmail.list_threads`\n * `maxResults` from 1 to 500, a `calendar.list_events` `maxResults` from 1 to 2500, and a\n * `drive.list_files` `pageSize` from 1 to 1000; any `timeMin` before `timeMax` (RFC 3339 instants\n * with a real calendar date, hour 0 to 23, minute and second 0 to 59, and a `Z` or in-range numeric\n * offset); any id of an item the state holds where a fixture has an id (writes: only items created\n * here, plus label changes, trash, and untrash of a stored non-draft message); and, for an id the\n * state does not hold, only the recorded not-found answers (a `format=minimal` read of a\n * 16-hex-digit message id, a read of a `Label_<1 to 999999999>` label, a delete of an `r-<digits>`\n * draft, and a Drive file read); on a `format=metadata` message read, and on a `format=metadata`\n * read of a thread of stored non-draft messages (a thread read in that format takes a selection), a\n * `metadataHeaders` selection, repeated in any order, of 1 to 50 distinct header names each spelled\n * exactly as a header of the recorded metadata rendering, answered as that rendering with only the\n * selected headers, in recorded order. A seed may set another `practiceAddress`, but then every\n * send is refused, since the recorded `sizeEstimate` of the sent message also covers the address:\n * the send answers only while the seeded address is the recorded `practice@example.test`. On the\n * draft compose and update routes, `message.raw` must be canonical unpadded base64url of exactly\n * the recorded draft MIME of that route, the run id aside; any other `message.raw` (line-wrapped,\n * the standard alphabet, padded, with a stray character, or with MIME-level encodings such as RFC\n * 2047 encoded-words, quoted-printable, or UTF-16) is refused before anything is recorded or a\n * fault is decided, as a constant entry with the route's own declared reason\n * (`message.raw must be canonical base64url UTF-8 MIME`,\n * `a draft compose other than the recorded run draft is not emulated` or its `update` form, the\n * 13-character run-id reason, or `message has a key this route does not take`), or\n * `the request body repeats the credential` when that raw decodes cleanly to text holding the\n * bearer, so a refused `message.raw` never reaches the ledger and an admitted one is the recorded\n * text. `Authorization` must be exactly `Bearer <token>` (that spelling, one space). Everything\n * else (other keys, values, formats, query parameters, empty query components such as a bare `?` or\n * a stray `&`, recorded headers such as Drive's `accept: application/json` missing, another origin,\n * repeated query parameters, any recipient but the seeded practice address, a draft or send run id\n * of another length, a bearer repeated anywhere in the request, including base64url-encoded inside\n * a draft's `message.raw`, and page tokens not issued for the same list since the last reset or\n * seed, or whose list changed) is not emulated.\n *\n * Node-only: `@emulators/core` imports Node builtins, so the core is loaded lazily by\n * `makeGoogleEmulator` (importing this module has no side effects).\n *\n * @experimental\n */\nimport { Data, Predicate } from 'effect'\nimport { calendarRoutes } from './google/calendar.ts'\nimport { driveRoutes } from './google/drive.ts'\nimport { gmailRoutes } from './google/gmail.ts'\nimport {\n googleEmulatorDrillKnobs,\n type GoogleApiEnv,\n type GoogleEmulatorDrills,\n type GoogleRoute\n} from './google/shared.ts'\nimport {\n buildSeedState,\n decodeState,\n type GoogleEmulatorSeed,\n type GoogleEmulatorState\n} from './google/state.ts'\nimport type { EmulatorRouteEvidence } from './route-evidence.ts'\nimport {\n StatefulFault,\n StatefulFaultMatch,\n checkBooleanDrills,\n makeStatefulEmulator,\n routeEvidence,\n type StatefulCoverage,\n type StatefulEmulatorApi,\n type StatefulFaultState,\n type StatefulInputKind,\n type StatefulLedgerEntry\n} from './stateful-emulator.ts'\nimport { statefulCoreRuntime } from './stateful-core.ts'\n\nexport type { EmulatorEvidence, EmulatorRouteEvidence } from './route-evidence.ts'\n\nexport { emulatorEvidenceHeader } from './route-evidence.ts'\n\nexport {\n googleEmulatorApisOrigin,\n googleEmulatorGmailOrigin,\n type GoogleEmulatorDrills\n} from './google/shared.ts'\n\nexport {\n GoogleEmulatorAttachment,\n GoogleEmulatorCalendar,\n GoogleEmulatorCalendarEvent,\n GoogleEmulatorDraft,\n GoogleEmulatorDriveFile,\n GoogleEmulatorEventBoundary,\n GoogleEmulatorGmailLabel,\n GoogleEmulatorGmailMessage,\n GoogleEmulatorImpliedMessage,\n GoogleEmulatorPracticeAddress,\n GoogleEmulatorProfile,\n GoogleEmulatorSeed,\n GoogleEmulatorStateSchema,\n type GoogleEmulatorState\n} from './google/state.ts'\n\nconst googleApiRoutes: ReadonlyArray<GoogleRoute> = [\n ...gmailRoutes,\n ...calendarRoutes,\n ...driveRoutes\n]\n\n/**\n * Route evidence manifest: every emulated route, whether it writes, and the conformance cases\n * whose (currently synthetic, unverified) wire claims it follows. Kept in sync with the handlers\n * by construction (both come from one route table). Every route cites at least one case.\n */\nexport const googleEmulatorRoutes: ReadonlyArray<EmulatorRouteEvidence> =\n googleApiRoutes.map(routeEvidence)\n\n/**\n * Optional fault filter; an omitted field matches every request. `method` is the HTTP method;\n * `path` is the raw request path (ending in `*`, a prefix); `route` is a route template of the\n * manifest (another value is rejected when the fault is added).\n */\nexport const GoogleFaultMatch = StatefulFaultMatch\n\nexport type GoogleFaultMatch = typeof StatefulFaultMatch.Type\n\n/**\n * A status fault (400-599): answer matching requests with this status, headers, and body instead\n * of the route's write, so nothing is written. The body defaults to\n * `{ error: { type: 'emulator_fault', message } }`; `count` limits how many requests it answers.\n * Only a request the emulator would answer reaches a fault: a request that is not emulated, by\n * its shape or by the state, never uses one up.\n */\nexport const GoogleFault = StatefulFault\n\nexport type GoogleFault = StatefulFault\n\nexport type GoogleFaultState = StatefulFaultState\n\nexport type GoogleLedgerEntry = StatefulLedgerEntry\n\nexport type GoogleCoverage = StatefulCoverage\n\n/** Invalid emulator input from the JS API: a seed, a fault, or an option. A programmer error. */\nexport class GoogleEmulatorInputInvalid extends Data.TaggedError('GoogleEmulatorInputInvalid')<{\n readonly input: StatefulInputKind\n readonly reason: string\n}> {\n override get message(): string {\n return `Invalid Google emulator ${this.input}: ${this.reason}`\n }\n}\n\nexport type GoogleEmulatorOptions = {\n /** Typed seed; defaults to the fixture entities (`profile: 'default'`). */\n readonly seed?: GoogleEmulatorSeed\n /**\n * Clock in epoch milliseconds (created and updated event times, Drive folder times, and the\n * sent message's `Date` header). Defaults to `Date.now`.\n */\n readonly now?: () => number\n /** Drill knobs (tests only): make the emulator disagree with one conformance case. */\n readonly drills?: GoogleEmulatorDrills\n}\n\nexport type GoogleEmulator = StatefulEmulatorApi<GoogleEmulatorState, GoogleEmulatorSeed>\n\n/** The constant reason of a request on no emulated route shape (nothing of it is ledgered). */\nconst googleUnrecognisedReason = 'no emulated Google route for this method and path'\n\n/** The constant reason of a request whose `Authorization` header is not one recognisable bearer. */\nconst googleUnrecognisedAuthorizationReason =\n 'an unrecognisable Authorization header is not emulated'\n\nconst inputInvalid = (input: StatefulInputKind, reason: string) =>\n new GoogleEmulatorInputInvalid({ input, reason })\n\n/**\n * Create a stateful Google emulator on the `@emulators/core` custom runtime. Each call has its\n * own state, ledger, faults, and page tokens. Rejects with `GoogleEmulatorInputInvalid` for an\n * invalid seed or option. See `src/stateful-emulator.ts` for the request precedence.\n */\nexport const makeGoogleEmulator = async (\n options: GoogleEmulatorOptions = {}\n): Promise<GoogleEmulator> => {\n const initial = buildSeedState(options.seed ?? {})\n\n if (Predicate.isString(initial)) {\n throw inputInvalid('seed', initial)\n }\n\n checkBooleanDrills(options.drills, googleEmulatorDrillKnobs, inputInvalid)\n\n const drills = options.drills ?? {}\n\n const env: GoogleApiEnv = {\n now: options.now ?? (() => Date.now()),\n drills: {\n gmailPageRepeats: drills.gmailPageRepeats === true,\n attachmentStandardBase64: drills.attachmentStandardBase64 === true,\n notFoundWithoutMessage: drills.notFoundWithoutMessage === true,\n gmailThreadPageRepeats: drills.gmailThreadPageRepeats === true,\n metadataHeadersIgnored: drills.metadataHeadersIgnored === true,\n labelDeleteKeepsOnMessages: drills.labelDeleteKeepsOnMessages === true,\n draftUpdateKeepsContent: drills.draftUpdateKeepsContent === true,\n trashAnswerOmitsTrash: drills.trashAnswerOmitsTrash === true,\n sentMessageWithoutTo: drills.sentMessageWithoutTo === true,\n calendarPageRepeats: drills.calendarPageRepeats === true,\n eventPatchKeepsSummary: drills.eventPatchKeepsSummary === true,\n repeatedEventDeleteConflict: drills.repeatedEventDeleteConflict === true,\n drivePageRepeats: drills.drivePageRepeats === true,\n getFileWithoutParents: drills.getFileWithoutParents === true,\n listIncludesTrashed: drills.listIncludesTrashed === true\n },\n pageTokens: new Map(),\n generation: { current: 0 },\n firstIssued: new Map()\n }\n\n return makeStatefulEmulator<GoogleEmulatorState, GoogleApiEnv, GoogleEmulatorSeed>(\n {\n routes: googleApiRoutes,\n env,\n initial,\n buildSeed: buildSeedState,\n requestProblem: header =>\n header('x-goog-drive-resource-keys') === undefined\n ? undefined\n : 'X-Goog-Drive-Resource-Keys is not emulated (no fixture sends it)',\n // `content-type` only (never a credential header); the bearer is checked in it too.\n recordHeaders: [{ name: 'content-type', json: false }],\n // Page token values never cross a reset or seed: the generation makes later tokens distinct.\n clearRuntime: () => {\n env.pageTokens.clear()\n env.generation.current += 1\n },\n runtimeState: () => ({ pageTokens: env.pageTokens.size }),\n seedSummary: state => ({\n messages: state.messages.length,\n events: state.events.length,\n files: state.files.length\n }),\n inputInvalid,\n failClosed: {\n unrecognised: googleUnrecognisedReason,\n unrecognisedAuthorization: googleUnrecognisedAuthorizationReason\n }\n },\n statefulCoreRuntime({ name: 'google', initial, decodeState, inputInvalid })\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4JA,MAAM,kBAA8C;CAClD,GAAG;CACH,GAAG;CACH,GAAG;AACL;;;;;;AAOA,MAAa,uBACX,gBAAgB,IAAI,aAAa;;;;;;AAOnC,MAAa,mBAAmB;;;;;;;;AAWhC,MAAa,cAAc;;AAW3B,IAAa,6BAAb,cAAgD,KAAK,YAAY,4BAA4B,EAG1F;CACD,IAAa,UAAkB;EAC7B,OAAO,2BAA2B,KAAK,MAAM,IAAI,KAAK;CACxD;AACF;;AAiBA,MAAM,2BAA2B;;AAGjC,MAAM,wCACJ;AAEF,MAAM,gBAAgB,OAA0B,WAC9C,IAAI,2BAA2B;CAAE;CAAO;AAAO,CAAC;;;;;;AAOlD,MAAa,qBAAqB,OAChC,UAAiC,CAAC,MACN;CAC5B,MAAM,UAAU,eAAe,QAAQ,QAAQ,CAAC,CAAC;CAEjD,IAAI,UAAU,SAAS,OAAO,GAC5B,MAAM,aAAa,QAAQ,OAAO;CAGpC,mBAAmB,QAAQ,QAAQ,0BAA0B,YAAY;CAEzE,MAAM,SAAS,QAAQ,UAAU,CAAC;CAElC,MAAM,MAAoB;EACxB,KAAK,QAAQ,cAAc,KAAK,IAAI;EACpC,QAAQ;GACN,kBAAkB,OAAO,qBAAqB;GAC9C,0BAA0B,OAAO,6BAA6B;GAC9D,wBAAwB,OAAO,2BAA2B;GAC1D,wBAAwB,OAAO,2BAA2B;GAC1D,wBAAwB,OAAO,2BAA2B;GAC1D,4BAA4B,OAAO,+BAA+B;GAClE,yBAAyB,OAAO,4BAA4B;GAC5D,uBAAuB,OAAO,0BAA0B;GACxD,sBAAsB,OAAO,yBAAyB;GACtD,qBAAqB,OAAO,wBAAwB;GACpD,wBAAwB,OAAO,2BAA2B;GAC1D,6BAA6B,OAAO,gCAAgC;GACpE,kBAAkB,OAAO,qBAAqB;GAC9C,uBAAuB,OAAO,0BAA0B;GACxD,qBAAqB,OAAO,wBAAwB;EACtD;EACA,4BAAY,IAAI,IAAI;EACpB,YAAY,EAAE,SAAS,EAAE;EACzB,6BAAa,IAAI,IAAI;CACvB;CAEA,OAAO,qBACL;EACE,QAAQ;EACR;EACA;EACA,WAAW;EACX,iBAAgB,WACd,OAAO,4BAA4B,MAAM,KAAA,IACrC,KAAA,IACA;EAEN,eAAe,CAAC;GAAE,MAAM;GAAgB,MAAM;EAAM,CAAC;EAErD,oBAAoB;GAClB,IAAI,WAAW,MAAM;GACrB,IAAI,WAAW,WAAW;EAC5B;EACA,qBAAqB,EAAE,YAAY,IAAI,WAAW,KAAK;EACvD,cAAa,WAAU;GACrB,UAAU,MAAM,SAAS;GACzB,QAAQ,MAAM,OAAO;GACrB,OAAO,MAAM,MAAM;EACrB;EACA;EACA,YAAY;GACV,cAAc;GACd,2BAA2B;EAC7B;CACF,GACA,oBAAoB;EAAE,MAAM;EAAU;EAAS;EAAa;CAAa,CAAC,CAC5E;AACF"}
|
|
1
|
+
{"version":3,"file":"google.mjs","names":[],"sources":["../src/google.ts"],"sourcesContent":["/**\n * Stateful Google emulator (the Gmail, Calendar, and Drive routes the Google conformance cases\n * send), built on the upstream `@emulators/core` custom runtime, with a request ledger, status\n * faults, and an `/_emulate/*` control plane.\n *\n * It never imports SDK code: its wire shapes, error envelopes, and default seed are copied as data\n * from the synthetic Google conformance fixtures, and every route names the conformance cases it\n * follows in `googleEmulatorRoutes`. Only the routes those fifteen cases (with their cleanup) send\n * are emulated: Gmail on `https://gmail.googleapis.com` (`/gmail/v1/users/me/...` and the multipart\n * send upload), Calendar and Drive on `https://www.googleapis.com` (`/calendar/v3` and\n * `/drive/v3`). Each route answers only on its recorded origin (`fetchOn(origin)` serves one origin\n * behind a loopback rewrite). Response behaviour comes only from the fixtures: anything they do not\n * show answers one ledgered 400 not-emulated, writes nothing, and uses up no fault. That includes\n * an empty listing and every read of the leftover lookup (`findGoogleConformanceLeftovers`, whose\n * label listing, draft search, and free-text event query no fixture records): the lookup fails, and\n * runners print their lookup-failed WARN.\n *\n * The practice send (`google.gmail.send-practice-address`) is irreversible on Gmail. Here it is\n * only recorded in the state (the sent message reads back; nothing is delivered anywhere), and only\n * the recorded 7-bit message whose sole recipient header is `To: <the seeded practice address>`\n * is accepted, and only while that address is the recorded `practice@example.test` (the recorded\n * `sizeEstimate` covers it, as it covers the draft and send subjects, which therefore take only a\n * run id of the fixtures' 13-character length).\n *\n * Fail closed: Google follows the shared fail-closed rule of `src/stateful-emulator.ts` (its opt-in\n * `failClosed` mode, the same rule as `/github`). Every route parameter has a raw pattern matched\n * in full, so a request is recognised only when its raw path is exactly an emulated route shape\n * under that route's method and any `Authorization` header is exactly `Bearer <token>` with a\n * recognisable bearer (below); every other request is ledgered and answered with constant text only\n * (`/<unrecognised>`, a standard method or `<other>`, an empty query, no body, a constant reason).\n * The bearer value is never compared against anything, stored, forwarded, or ledgered. A recognised\n * request that repeats it in its raw path, any path segment, the query or any query key or value,\n * the recorded `content-type` header, or its raw body (the multipart send body included), or, on\n * the draft compose and update routes, in the base64url-decoded MIME of `message.raw` (Gmail's own\n * wire format wraps the draft this way; the routes give it to the wrapper as a decoded view), is\n * ledgered as the constant credential-repeat entry, checked through the wrapper's fixpoint closure\n * of a tolerant percent-decode and a tolerant JSON-unescape; any other recognised request has the\n * bearer scrubbed from its ledgered fields and every not-emulated reason. A `message.raw` the route\n * would refuse (anything but canonical unpadded base64url of exactly the recorded draft MIME, the\n * run id aside) makes the view throw a `DecodedViewRefusal` with one of the route's declared\n * constant reasons (`viewRefusalReasons`: the canonical-base64url reason, the\n * other-than-the-recorded-run-draft reason, the 13-character run-id reason, the extra-key reason),\n * which the wrapper ledgers in the constant entry before anything is recorded (or\n * `the request body repeats the credential` when the raw decodes cleanly to text holding the\n * bearer), so a refused `message.raw` never reaches the ledger. Google refusals use the wrapper's\n * constant-reason `exactQuery` and `exactBodyKeys`, so they never echo a request's own query or\n * body keys.\n *\n * Request-shape latitude (`/google`, the only accepted deviations): any bearer value in the RFC\n * 6750 `b64token` syntax (`[A-Za-z0-9\\-._~+/]+=*`) of at least 8 characters, starting with a\n * character in `[G-Zg-z\\-._~+/]` other than `n`, `r`, `t`, `u`, with at least one outside\n * `[0-9.eE+-]` (Google's `ya29.…` access tokens qualify), that occurs nowhere else in the request\n * (never compared against anything, stored, or ledgered); extra request headers (except\n * `X-Goog-Drive-Resource-Keys`, which no fixture sends); JSON key order; `content-type` media-type\n * parameters on JSON requests; query parameters in any order; any `run-` run id (at most 40\n * characters) in a run-scoped label name, event summary, or folder name; in a draft subject\n * (compose and update) and the sent subject, only a run id of exactly 13 characters, the length of\n * the fixtures' `run-synthetic`, because the recorded `sizeEstimate` of the draft and sent messages\n * (answered by their message reads and the draft thread) covers the subject; on the practice send,\n * a `content-type` of exactly `multipart/related; boundary=<b>` with any one unquoted boundary of 1\n * to 70 `[A-Za-z0-9_]` characters and no other parameter; a `gmail.list` or `gmail.list_threads`\n * `maxResults` from 1 to 500, a `calendar.list_events` `maxResults` from 1 to 2500, and a\n * `drive.list_files` `pageSize` from 1 to 1000; any `timeMin` before `timeMax` (RFC 3339 instants\n * with a real calendar date, hour 0 to 23, minute and second 0 to 59, and a `Z` or in-range numeric\n * offset); any id of an item the state holds where a fixture has an id (writes: only items created\n * here, plus label changes, trash, and untrash of a stored non-draft message); and, for an id the\n * state does not hold, only the recorded not-found answers (a `format=minimal` read of a\n * 16-hex-digit message id, a read of a `Label_<1 to 999999999>` label, a delete of an `r-<digits>`\n * draft, and a Drive file read); on a `format=metadata` message read, and on a `format=metadata`\n * read of a thread of stored non-draft messages (a thread read in that format takes a selection), a\n * `metadataHeaders` selection, repeated in any order, of 1 to 50 distinct header names each spelled\n * exactly as a header of the recorded metadata rendering, answered as that rendering with only the\n * selected headers, in recorded order. A seed may set another `practiceAddress`, but then every\n * send is refused, since the recorded `sizeEstimate` of the sent message also covers the address:\n * the send answers only while the seeded address is the recorded `practice@example.test`. On the\n * draft compose and update routes, `message.raw` must be canonical unpadded base64url of exactly\n * the recorded draft MIME of that route, the run id aside; any other `message.raw` (line-wrapped,\n * the standard alphabet, padded, with a stray character, or with MIME-level encodings such as RFC\n * 2047 encoded-words, quoted-printable other than the recorded parts, or UTF-16) is refused\n * before anything is recorded or a fault is decided, as a constant entry with the route's own\n * declared reason\n * (`message.raw must be canonical base64url UTF-8 MIME`,\n * `a draft compose other than the recorded run draft is not emulated` or its `update` form, the\n * 13-character run-id reason, or `message has a key this route does not take`), or\n * `the request body repeats the credential` when that raw decodes cleanly to text holding the\n * bearer, so a refused `message.raw` never reaches the ledger and an admitted one is the recorded\n * text. `Authorization` must be exactly `Bearer <token>` (that spelling, one space). Everything\n * else (other keys, values, formats, query parameters, empty query components such as a bare `?` or\n * a stray `&`, recorded headers such as Drive's `accept: application/json` missing, another origin,\n * repeated query parameters, any recipient but the seeded practice address, a draft or send run id\n * of another length, a bearer repeated anywhere in the request, including base64url-encoded inside\n * a draft's `message.raw`, and page tokens not issued for the same list since the last reset or\n * seed, or whose list changed) is not emulated.\n *\n * Node-only: `@emulators/core` imports Node builtins, so the core is loaded lazily by\n * `makeGoogleEmulator` (importing this module has no side effects).\n *\n * @experimental\n */\nimport { Data, Predicate } from 'effect'\nimport { calendarRoutes } from './google/calendar.ts'\nimport { driveRoutes } from './google/drive.ts'\nimport { gmailRoutes } from './google/gmail.ts'\nimport {\n googleEmulatorDrillKnobs,\n type GoogleApiEnv,\n type GoogleEmulatorDrills,\n type GoogleRoute\n} from './google/shared.ts'\nimport {\n buildSeedState,\n decodeState,\n type GoogleEmulatorSeed,\n type GoogleEmulatorState\n} from './google/state.ts'\nimport type { EmulatorRouteEvidence } from './route-evidence.ts'\nimport {\n StatefulFault,\n StatefulFaultMatch,\n checkBooleanDrills,\n makeStatefulEmulator,\n routeEvidence,\n type StatefulCoverage,\n type StatefulEmulatorApi,\n type StatefulFaultState,\n type StatefulInputKind,\n type StatefulLedgerEntry\n} from './stateful-emulator.ts'\nimport { statefulCoreRuntime } from './stateful-core.ts'\n\nexport type { EmulatorEvidence, EmulatorRouteEvidence } from './route-evidence.ts'\n\nexport { emulatorEvidenceHeader } from './route-evidence.ts'\n\nexport {\n googleEmulatorApisOrigin,\n googleEmulatorGmailOrigin,\n type GoogleEmulatorDrills\n} from './google/shared.ts'\n\nexport {\n GoogleEmulatorAttachment,\n GoogleEmulatorCalendar,\n GoogleEmulatorCalendarEvent,\n GoogleEmulatorDraft,\n GoogleEmulatorDriveFile,\n GoogleEmulatorEventBoundary,\n GoogleEmulatorGmailLabel,\n GoogleEmulatorGmailMessage,\n GoogleEmulatorImpliedMessage,\n GoogleEmulatorPracticeAddress,\n GoogleEmulatorProfile,\n GoogleEmulatorSeed,\n GoogleEmulatorStateSchema,\n type GoogleEmulatorState\n} from './google/state.ts'\n\nconst googleApiRoutes: ReadonlyArray<GoogleRoute> = [\n ...gmailRoutes,\n ...calendarRoutes,\n ...driveRoutes\n]\n\n/**\n * Route evidence manifest: every emulated route, whether it writes, and the conformance cases\n * whose (currently synthetic, unverified) wire claims it follows. Kept in sync with the handlers\n * by construction (both come from one route table). Every route cites at least one case.\n */\nexport const googleEmulatorRoutes: ReadonlyArray<EmulatorRouteEvidence> =\n googleApiRoutes.map(routeEvidence)\n\n/**\n * Optional fault filter; an omitted field matches every request. `method` is the HTTP method;\n * `path` is the raw request path (ending in `*`, a prefix); `route` is a route template of the\n * manifest (another value is rejected when the fault is added).\n */\nexport const GoogleFaultMatch = StatefulFaultMatch\n\nexport type GoogleFaultMatch = typeof StatefulFaultMatch.Type\n\n/**\n * A status fault (400-599): answer matching requests with this status, headers, and body instead\n * of the route's write, so nothing is written. The body defaults to\n * `{ error: { type: 'emulator_fault', message } }`; `count` limits how many requests it answers.\n * Only a request the emulator would answer reaches a fault: a request that is not emulated, by\n * its shape or by the state, never uses one up.\n */\nexport const GoogleFault = StatefulFault\n\nexport type GoogleFault = StatefulFault\n\nexport type GoogleFaultState = StatefulFaultState\n\nexport type GoogleLedgerEntry = StatefulLedgerEntry\n\nexport type GoogleCoverage = StatefulCoverage\n\n/** Invalid emulator input from the JS API: a seed, a fault, or an option. A programmer error. */\nexport class GoogleEmulatorInputInvalid extends Data.TaggedError('GoogleEmulatorInputInvalid')<{\n readonly input: StatefulInputKind\n readonly reason: string\n}> {\n override get message(): string {\n return `Invalid Google emulator ${this.input}: ${this.reason}`\n }\n}\n\nexport type GoogleEmulatorOptions = {\n /** Typed seed; defaults to the fixture entities (`profile: 'default'`). */\n readonly seed?: GoogleEmulatorSeed\n /**\n * Clock in epoch milliseconds (created and updated event times, Drive folder times, and the\n * sent message's `Date` header). Defaults to `Date.now`.\n */\n readonly now?: () => number\n /** Drill knobs (tests only): make the emulator disagree with one conformance case. */\n readonly drills?: GoogleEmulatorDrills\n}\n\nexport type GoogleEmulator = StatefulEmulatorApi<GoogleEmulatorState, GoogleEmulatorSeed>\n\n/** The constant reason of a request on no emulated route shape (nothing of it is ledgered). */\nconst googleUnrecognisedReason = 'no emulated Google route for this method and path'\n\n/** The constant reason of a request whose `Authorization` header is not one recognisable bearer. */\nconst googleUnrecognisedAuthorizationReason =\n 'an unrecognisable Authorization header is not emulated'\n\nconst inputInvalid = (input: StatefulInputKind, reason: string) =>\n new GoogleEmulatorInputInvalid({ input, reason })\n\n/**\n * Create a stateful Google emulator on the `@emulators/core` custom runtime. Each call has its\n * own state, ledger, faults, and page tokens. Rejects with `GoogleEmulatorInputInvalid` for an\n * invalid seed or option. See `src/stateful-emulator.ts` for the request precedence.\n */\nexport const makeGoogleEmulator = async (\n options: GoogleEmulatorOptions = {}\n): Promise<GoogleEmulator> => {\n const initial = buildSeedState(options.seed ?? {})\n\n if (Predicate.isString(initial)) {\n throw inputInvalid('seed', initial)\n }\n\n checkBooleanDrills(options.drills, googleEmulatorDrillKnobs, inputInvalid)\n\n const drills = options.drills ?? {}\n\n const env: GoogleApiEnv = {\n now: options.now ?? (() => Date.now()),\n drills: {\n gmailPageRepeats: drills.gmailPageRepeats === true,\n attachmentStandardBase64: drills.attachmentStandardBase64 === true,\n notFoundWithoutMessage: drills.notFoundWithoutMessage === true,\n gmailThreadPageRepeats: drills.gmailThreadPageRepeats === true,\n metadataHeadersIgnored: drills.metadataHeadersIgnored === true,\n labelDeleteKeepsOnMessages: drills.labelDeleteKeepsOnMessages === true,\n draftUpdateKeepsContent: drills.draftUpdateKeepsContent === true,\n trashAnswerOmitsTrash: drills.trashAnswerOmitsTrash === true,\n sentMessageWithoutTo: drills.sentMessageWithoutTo === true,\n calendarPageRepeats: drills.calendarPageRepeats === true,\n eventPatchKeepsSummary: drills.eventPatchKeepsSummary === true,\n repeatedEventDeleteConflict: drills.repeatedEventDeleteConflict === true,\n drivePageRepeats: drills.drivePageRepeats === true,\n getFileWithoutParents: drills.getFileWithoutParents === true,\n listIncludesTrashed: drills.listIncludesTrashed === true\n },\n pageTokens: new Map(),\n generation: { current: 0 },\n firstIssued: new Map()\n }\n\n return makeStatefulEmulator<GoogleEmulatorState, GoogleApiEnv, GoogleEmulatorSeed>(\n {\n routes: googleApiRoutes,\n env,\n initial,\n buildSeed: buildSeedState,\n requestProblem: header =>\n header('x-goog-drive-resource-keys') === undefined\n ? undefined\n : 'X-Goog-Drive-Resource-Keys is not emulated (no fixture sends it)',\n // `content-type` only (never a credential header); the bearer is checked in it too.\n recordHeaders: [{ name: 'content-type', json: false }],\n // Page token values never cross a reset or seed: the generation makes later tokens distinct.\n clearRuntime: () => {\n env.pageTokens.clear()\n env.generation.current += 1\n },\n runtimeState: () => ({ pageTokens: env.pageTokens.size }),\n seedSummary: state => ({\n messages: state.messages.length,\n events: state.events.length,\n files: state.files.length\n }),\n inputInvalid,\n failClosed: {\n unrecognised: googleUnrecognisedReason,\n unrecognisedAuthorization: googleUnrecognisedAuthorizationReason\n }\n },\n statefulCoreRuntime({ name: 'google', initial, decodeState, inputInvalid })\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6JA,MAAM,kBAA8C;CAClD,GAAG;CACH,GAAG;CACH,GAAG;AACL;;;;;;AAOA,MAAa,uBACX,gBAAgB,IAAI,aAAa;;;;;;AAOnC,MAAa,mBAAmB;;;;;;;;AAWhC,MAAa,cAAc;;AAW3B,IAAa,6BAAb,cAAgD,KAAK,YAAY,4BAA4B,EAG1F;CACD,IAAa,UAAkB;EAC7B,OAAO,2BAA2B,KAAK,MAAM,IAAI,KAAK;CACxD;AACF;;AAiBA,MAAM,2BAA2B;;AAGjC,MAAM,wCACJ;AAEF,MAAM,gBAAgB,OAA0B,WAC9C,IAAI,2BAA2B;CAAE;CAAO;AAAO,CAAC;;;;;;AAOlD,MAAa,qBAAqB,OAChC,UAAiC,CAAC,MACN;CAC5B,MAAM,UAAU,eAAe,QAAQ,QAAQ,CAAC,CAAC;CAEjD,IAAI,UAAU,SAAS,OAAO,GAC5B,MAAM,aAAa,QAAQ,OAAO;CAGpC,mBAAmB,QAAQ,QAAQ,0BAA0B,YAAY;CAEzE,MAAM,SAAS,QAAQ,UAAU,CAAC;CAElC,MAAM,MAAoB;EACxB,KAAK,QAAQ,cAAc,KAAK,IAAI;EACpC,QAAQ;GACN,kBAAkB,OAAO,qBAAqB;GAC9C,0BAA0B,OAAO,6BAA6B;GAC9D,wBAAwB,OAAO,2BAA2B;GAC1D,wBAAwB,OAAO,2BAA2B;GAC1D,wBAAwB,OAAO,2BAA2B;GAC1D,4BAA4B,OAAO,+BAA+B;GAClE,yBAAyB,OAAO,4BAA4B;GAC5D,uBAAuB,OAAO,0BAA0B;GACxD,sBAAsB,OAAO,yBAAyB;GACtD,qBAAqB,OAAO,wBAAwB;GACpD,wBAAwB,OAAO,2BAA2B;GAC1D,6BAA6B,OAAO,gCAAgC;GACpE,kBAAkB,OAAO,qBAAqB;GAC9C,uBAAuB,OAAO,0BAA0B;GACxD,qBAAqB,OAAO,wBAAwB;EACtD;EACA,4BAAY,IAAI,IAAI;EACpB,YAAY,EAAE,SAAS,EAAE;EACzB,6BAAa,IAAI,IAAI;CACvB;CAEA,OAAO,qBACL;EACE,QAAQ;EACR;EACA;EACA,WAAW;EACX,iBAAgB,WACd,OAAO,4BAA4B,MAAM,KAAA,IACrC,KAAA,IACA;EAEN,eAAe,CAAC;GAAE,MAAM;GAAgB,MAAM;EAAM,CAAC;EAErD,oBAAoB;GAClB,IAAI,WAAW,MAAM;GACrB,IAAI,WAAW,WAAW;EAC5B;EACA,qBAAqB,EAAE,YAAY,IAAI,WAAW,KAAK;EACvD,cAAa,WAAU;GACrB,UAAU,MAAM,SAAS;GACzB,QAAQ,MAAM,OAAO;GACrB,OAAO,MAAM,MAAM;EACrB;EACA;EACA,YAAY;GACV,cAAc;GACd,2BAA2B;EAC7B;CACF,GACA,oBAAoB;EAAE,MAAM;EAAU;EAAS;EAAa;CAAa,CAAC,CAC5E;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk-sdk/emulators",
|
|
3
|
-
"version": "0.1.0-canary.
|
|
3
|
+
"version": "0.1.0-canary.102",
|
|
4
4
|
"description": "Experimental emulators for outside services: an Effect HttpClient router, Vercel AI Gateway, OpenAI Chat Completions, Anthropic Messages, OpenAI Responses (Codex, xAI Grok), and OpenCode Go fetch-handler emulators with subscription-usage routes, fixture-driven fake EmailClient and R2 (R2Presigner, R2ObjectClient) backends, stateful Fortnox, Microsoft Graph, Dropbox, Notion, Todoist, Telegram, GitHub, Google (Gmail, Calendar, Drive), LinkedIn search (Exa, Enrich Layer), and synthetic and Afloat MCP emulators, and a loopback Node server.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -143,10 +143,10 @@
|
|
|
143
143
|
"effect": "4.0.0"
|
|
144
144
|
},
|
|
145
145
|
"devDependencies": {
|
|
146
|
-
"@yolk-sdk/agent": "^0.1.0-canary.
|
|
147
|
-
"@yolk-sdk/
|
|
148
|
-
"@yolk-sdk/
|
|
149
|
-
"@yolk-sdk/
|
|
146
|
+
"@yolk-sdk/agent": "^0.1.0-canary.102",
|
|
147
|
+
"@yolk-sdk/conformance": "^0.1.0-canary.102",
|
|
148
|
+
"@yolk-sdk/connectors": "^0.1.0-canary.102",
|
|
149
|
+
"@yolk-sdk/mcp": "^0.1.0-canary.102"
|
|
150
150
|
},
|
|
151
151
|
"scripts": {
|
|
152
152
|
"build": "tsdown",
|
package/src/google/gmail.ts
CHANGED
|
@@ -741,8 +741,48 @@ const decodeBase64UrlText = (raw: string): string | undefined => {
|
|
|
741
741
|
}
|
|
742
742
|
}
|
|
743
743
|
|
|
744
|
-
const
|
|
745
|
-
|
|
744
|
+
const draftBoundary = '=_yolk-draft-alternative'
|
|
745
|
+
|
|
746
|
+
const draftContentType = `multipart/alternative; boundary="${draftBoundary}"`
|
|
747
|
+
|
|
748
|
+
/** The quoted-printable part of the recorded draft MIME. */
|
|
749
|
+
const recordedDraftPart = (type: 'plain' | 'html', encoded: string): string =>
|
|
750
|
+
`Content-Type: text/${type}; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n${encoded}`
|
|
751
|
+
|
|
752
|
+
/** The draft MIME the draft fixture records after the `Subject` line, for each draft kind. */
|
|
753
|
+
const recordedDraftMime = (plain: string, html: string): string =>
|
|
754
|
+
[
|
|
755
|
+
'MIME-Version: 1.0',
|
|
756
|
+
`Content-Type: ${draftContentType}`,
|
|
757
|
+
'',
|
|
758
|
+
`--${draftBoundary}`,
|
|
759
|
+
recordedDraftPart('plain', plain),
|
|
760
|
+
`--${draftBoundary}`,
|
|
761
|
+
recordedDraftPart('html', html),
|
|
762
|
+
`--${draftBoundary}--`
|
|
763
|
+
].join('\r\n')
|
|
764
|
+
|
|
765
|
+
const recordedDrafts: Record<
|
|
766
|
+
'compose' | 'update',
|
|
767
|
+
{ readonly text: string; readonly mime: string }
|
|
768
|
+
> = {
|
|
769
|
+
compose: {
|
|
770
|
+
text: draftText,
|
|
771
|
+
mime: recordedDraftMime(
|
|
772
|
+
'Synthetic conformance draft, safe to delete: gr=C3=BC=C3=9Fe =E2=9C=93',
|
|
773
|
+
'<div dir=3D"ltr">Synthetic conformance draft, safe to delete: gr=C3=BC=\r\n=C3=9Fe =E2=9C=93</div>'
|
|
774
|
+
)
|
|
775
|
+
},
|
|
776
|
+
update: {
|
|
777
|
+
text: updatedDraftText,
|
|
778
|
+
mime: recordedDraftMime(
|
|
779
|
+
'Updated synthetic conformance draft: =C2=A1hola! =E2=9C=93',
|
|
780
|
+
'<div dir=3D"ltr">Updated synthetic conformance draft: =C2=A1hola! =E2=9C=93=\r\n</div>'
|
|
781
|
+
)
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
const draftMimePattern = /^Subject: ([^\r\n]*)\r\n([\s\S]*)$/
|
|
746
786
|
|
|
747
787
|
type DraftContent = { readonly subject: string; readonly body: string }
|
|
748
788
|
|
|
@@ -788,16 +828,16 @@ const readDraftRaw = (message: Schema.Json | undefined, kind: 'compose' | 'updat
|
|
|
788
828
|
|
|
789
829
|
const parts = draftMimePattern.exec(decoded)
|
|
790
830
|
const subject = parts?.[1] ?? ''
|
|
791
|
-
const
|
|
831
|
+
const rest = parts?.[2] ?? ''
|
|
792
832
|
|
|
793
833
|
const runId =
|
|
794
834
|
kind === 'compose'
|
|
795
835
|
? runIdOf(subject, 'draft', draftSubjectRest)
|
|
796
836
|
: runIdOf(subject, 'draft updated', draftSubjectRest)
|
|
797
837
|
|
|
798
|
-
const
|
|
838
|
+
const recorded = recordedDrafts[kind]
|
|
799
839
|
|
|
800
|
-
if (parts === null || runId === undefined ||
|
|
840
|
+
if (parts === null || runId === undefined || rest !== recorded.mime) {
|
|
801
841
|
return { decoded, content: notEmulated(otherDraftReason(kind)) }
|
|
802
842
|
}
|
|
803
843
|
|
|
@@ -805,7 +845,7 @@ const readDraftRaw = (message: Schema.Json | undefined, kind: 'compose' | 'updat
|
|
|
805
845
|
decoded,
|
|
806
846
|
content:
|
|
807
847
|
runId.length === recordedRunIdLength
|
|
808
|
-
? { subject, body }
|
|
848
|
+
? { subject, body: recorded.text }
|
|
809
849
|
: notEmulated(sizedRunIdReason('draft'))
|
|
810
850
|
}
|
|
811
851
|
}
|
|
@@ -842,15 +882,35 @@ const draftRawViews =
|
|
|
842
882
|
return decoded === undefined ? [] : [decoded]
|
|
843
883
|
}
|
|
844
884
|
|
|
845
|
-
|
|
885
|
+
/** A draft's `multipart/alternative` payload as the draft fixture's metadata read records it. */
|
|
886
|
+
const draftPayload = (subject: string): Schema.JsonObject => ({
|
|
846
887
|
partId: '',
|
|
847
|
-
mimeType: '
|
|
888
|
+
mimeType: 'multipart/alternative',
|
|
848
889
|
filename: '',
|
|
849
890
|
headers: [
|
|
850
891
|
{ name: 'Subject', value: subject },
|
|
851
|
-
{ name: 'Content-Type', value:
|
|
892
|
+
{ name: 'Content-Type', value: draftContentType }
|
|
852
893
|
],
|
|
853
|
-
body
|
|
894
|
+
body: { size: 0 }
|
|
895
|
+
})
|
|
896
|
+
|
|
897
|
+
/** A `format=full` text part, its `body.data` transfer-decoded as the draft fixture records it. */
|
|
898
|
+
const draftTextPart = (
|
|
899
|
+
partId: string,
|
|
900
|
+
type: 'plain' | 'html',
|
|
901
|
+
content: string
|
|
902
|
+
): Schema.JsonObject => ({
|
|
903
|
+
partId,
|
|
904
|
+
mimeType: `text/${type}`,
|
|
905
|
+
filename: '',
|
|
906
|
+
headers: [
|
|
907
|
+
{ name: 'Content-Type', value: `text/${type}; charset=UTF-8` },
|
|
908
|
+
{ name: 'Content-Transfer-Encoding', value: 'quoted-printable' }
|
|
909
|
+
],
|
|
910
|
+
body: {
|
|
911
|
+
size: new TextEncoder().encode(content).byteLength,
|
|
912
|
+
data: base64UrlOfText(content)
|
|
913
|
+
}
|
|
854
914
|
})
|
|
855
915
|
|
|
856
916
|
/** A draft message as the draft fixture records it (the metadata rendering only on compose). */
|
|
@@ -868,11 +928,14 @@ const draftMessage = (
|
|
|
868
928
|
historyId: '900020',
|
|
869
929
|
internalDate: recordedInternalDate,
|
|
870
930
|
minimal: false,
|
|
871
|
-
metadataPayload: withMetadata ?
|
|
872
|
-
fullPayload:
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
931
|
+
metadataPayload: withMetadata ? draftPayload(content.subject) : null,
|
|
932
|
+
fullPayload: {
|
|
933
|
+
...draftPayload(content.subject),
|
|
934
|
+
parts: [
|
|
935
|
+
draftTextPart('0', 'plain', content.body),
|
|
936
|
+
draftTextPart('1', 'html', `<div dir="ltr">${content.body}</div>`)
|
|
937
|
+
]
|
|
938
|
+
}
|
|
876
939
|
})
|
|
877
940
|
|
|
878
941
|
const draftAnswer = (draftId: string, message: GoogleEmulatorGmailMessage): Response =>
|
package/src/google.ts
CHANGED
|
@@ -76,8 +76,9 @@
|
|
|
76
76
|
* draft compose and update routes, `message.raw` must be canonical unpadded base64url of exactly
|
|
77
77
|
* the recorded draft MIME of that route, the run id aside; any other `message.raw` (line-wrapped,
|
|
78
78
|
* the standard alphabet, padded, with a stray character, or with MIME-level encodings such as RFC
|
|
79
|
-
* 2047 encoded-words, quoted-printable, or UTF-16) is refused
|
|
80
|
-
* fault is decided, as a constant entry with the route's own
|
|
79
|
+
* 2047 encoded-words, quoted-printable other than the recorded parts, or UTF-16) is refused
|
|
80
|
+
* before anything is recorded or a fault is decided, as a constant entry with the route's own
|
|
81
|
+
* declared reason
|
|
81
82
|
* (`message.raw must be canonical base64url UTF-8 MIME`,
|
|
82
83
|
* `a draft compose other than the recorded run draft is not emulated` or its `update` form, the
|
|
83
84
|
* 13-character run-id reason, or `message has a key this route does not take`), or
|