import assert from 'node:assert/strict'
import { AsyncLocalStorage } from 'node:async_hooks'
import { execFileSync } from 'node:child_process'
import { registerHooks } from 'node:module'
import { test } from 'node:test'
const script = new URL('../provision-login.mjs', import.meta.url).href
registerHooks({
resolve(specifier, context, next) { return specifier === '@kodycodes/cli' ? { url: 'mock:cli', shortCircuit: true } : next(specifier, context) },
load(url, context, next) {
if (url === script && process.env.AUTH_TEST_BASE) return { format: 'module', shortCircuit: true, source: execFileSync('git', ['show', `${process.env.AUTH_TEST_BASE}:scripts/provision-login.mjs`], { encoding: 'utf8' }) }
if (url === 'mock:cli') return { format: 'module', shortCircuit: true, source: `globalThis.flagsAtCliImport=[process.env.KODY_SKIP_SKILL_REFRESH,process.env.KODY_SKIP_GIT_HELPER_REFRESH]; export const runCli=async()=>{throw new Error('Fake CLI must not be called without a prompt.')}` }
return next(url, context)
},
})
const { main } = await import('../provision-login.mjs')
test('main disables skill and git-helper refresh before loading the CLI', async () => {
const names = ['KODY_SKIP_SKILL_REFRESH','KODY_SKIP_GIT_HELPER_REFRESH']
const saved = names.map(name => process.env[name])
const tty = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY')
const write = process.stdout.write, send = globalThis.fetch
const scope = new AsyncLocalStorage()
let calls = 0
globalThis.fetch = async () => { calls++; throw new Error('Fake Amazon must not be called without a prompt.') }
process.stdout.write = function(chunk, encoding, callback) {
if (!scope.getStore()) return write.call(this, chunk, encoding, callback)
const done = typeof encoding === 'function' ? encoding : callback; done?.(); return true
}
Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: false })
for (const name of names) delete process.env[name]
try {
await scope.run(true, () => assert.rejects(main(['--locale','ca']), /interactive Terminal/))
assert.deepEqual(globalThis.flagsAtCliImport, ['1','1'])
assert.deepEqual(names.map(name => process.env[name]), ['1','1'])
assert.equal(calls, 0)
} finally {
for (let i = 0; i < names.length; i++) saved[i] === undefined ? delete process.env[names[i]] : process.env[names[i]] = saved[i]
tty ? Object.defineProperty(process.stdin, 'isTTY', tty) : delete process.stdin.isTTY
process.stdout.write = write; globalThis.fetch = send
}
})