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/hooks.mjs

36 lines · 1.4 KB · JavaScript
Raw
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'

const stubUrl = pathToFileURL(
  join(dirname(fileURLToPath(import.meta.url)), 'kody-runtime-stub.js')
).href

const srcUrl = new URL('../src/', import.meta.url).href

// A src import with this query loads a separate module graph whose
// src/config.js says SENDING = 'allowed'. The committed file stays barred.
export const ALLOWED_QUERY = '?sending=allowed'

const BARRED_LINE = "export const SENDING = 'barred'"
const ALLOWED_LINE = "export const SENDING = 'allowed'"

export async function resolve(specifier, context, nextResolve) {
  if (specifier === 'kody:runtime') {
    return { url: stubUrl, shortCircuit: true }
  }
  const resolved = await nextResolve(specifier, context)
  if (context.parentURL?.endsWith(ALLOWED_QUERY) && resolved.url.startsWith(srcUrl)) {
    return { ...resolved, url: resolved.url + ALLOWED_QUERY }
  }
  return resolved
}

export async function load(url, context, nextLoad) {
  const loaded = await nextLoad(url, context)
  if (url !== `${srcUrl}config.js${ALLOWED_QUERY}`) return loaded
  const source = typeof loaded.source === 'string' ? loaded.source : new TextDecoder().decode(loaded.source)
  if (!source.includes(BARRED_LINE)) {
    throw new Error(`test/hooks.mjs: src/config.js no longer contains ${BARRED_LINE}`)
  }
  return { ...loaded, source: source.replace(BARRED_LINE, ALLOWED_LINE) }
}