Skip to content
← Public packages

@danj/hey-email

HEY.com email for Kody: search threads, read messages, download PDF attachments, and write drafts. Sending is barred until you allow it.

test/helpers.mjs

75 lines · 1.7 KB · JavaScript
Raw
import {
  disableSecretSetMany,
  failAssertOnly,
  failPersist,
  kody,
  resetKodySecrets,
  savedSecrets,
  writes,
  assertCalls,
} from './kody-runtime-stub.js'

export {
  disableSecretSetMany,
  failAssertOnly,
  failPersist,
  kody,
  resetKodySecrets,
  savedSecrets,
  writes,
  assertCalls,
}

export const HEY = 'https://app.hey.com'
export const STORAGE = 'https://hey-storage.example'
export const BEARER = 'Bearer {{secret:heyToken}}'

export function snapshotHeaders(headers) {
  const out = {}
  if (!headers) return out
  new Headers(headers).forEach((value, key) => {
    out[key.toLowerCase()] = value
  })
  return out
}

export function jsonResponse(status, data, extraHeaders = {}) {
  return new Response(JSON.stringify(data), {
    status,
    headers: { 'content-type': 'application/json', ...extraHeaders },
  })
}

export function redirectResponse(status, location, extraHeaders = {}) {
  return new Response(null, {
    status,
    headers: { location, ...extraHeaders },
  })
}

export function installFetch(handler) {
  const requests = []
  const original = globalThis.fetch
  globalThis.fetch = async (input, init = {}) => {
    const url = typeof input === 'string' ? input : input.url
    requests.push({
      url,
      method: String(init.method || 'GET').toUpperCase(),
      headers: snapshotHeaders(init.headers),
      body: init.body == null ? undefined : String(init.body),
      redirect: init.redirect || 'follow',
    })
    return handler(url, init, requests)
  }
  return {
    requests,
    restore() {
      globalThis.fetch = original
    },
  }
}

export function last(requests, predicate) {
  const matches = predicate ? requests.filter(predicate) : requests
  return matches[matches.length - 1]
}