|
| 1 | +import fs from 'node:fs'; |
| 2 | +import { createRequire } from 'node:module'; |
| 3 | +import os from 'node:os'; |
| 4 | +import path from 'node:path'; |
| 5 | + |
| 6 | +import { agentEnvironmentVariables, automatedEnvironmentVariables } from '@clerk/shared/utils'; |
| 7 | +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; |
| 8 | + |
| 9 | +const nodeRequire = createRequire(import.meta.url); |
| 10 | +const pluginPath = nodeRequire.resolve('../../app.plugin.js'); |
| 11 | + |
| 12 | +const loadMaybeWriteAgentRules = () => { |
| 13 | + delete nodeRequire.cache[pluginPath]; |
| 14 | + return nodeRequire(pluginPath)._testing.maybeWriteAgentRules; |
| 15 | +}; |
| 16 | + |
| 17 | +describe('maybeWriteAgentRules', () => { |
| 18 | + let projectRoot; |
| 19 | + |
| 20 | + beforeEach(() => { |
| 21 | + projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'clerk-expo-agent-rules-')); |
| 22 | + fs.writeFileSync(path.join(projectRoot, 'package.json'), '{}'); |
| 23 | + for (const name of [...agentEnvironmentVariables, ...automatedEnvironmentVariables]) { |
| 24 | + vi.stubEnv(name, ''); |
| 25 | + } |
| 26 | + vi.stubEnv('NODE_ENV', 'development'); |
| 27 | + }); |
| 28 | + |
| 29 | + afterEach(() => { |
| 30 | + vi.unstubAllEnvs(); |
| 31 | + fs.rmSync(projectRoot, { recursive: true, force: true }); |
| 32 | + }); |
| 33 | + |
| 34 | + const agentsMdPath = () => path.join(projectRoot, 'AGENTS.md'); |
| 35 | + const config = () => ({ _internal: { projectRoot } }); |
| 36 | + |
| 37 | + test('writes the Expo rules once per process under an AI agent', () => { |
| 38 | + vi.stubEnv('CLAUDECODE', '1'); |
| 39 | + const maybeWriteAgentRules = loadMaybeWriteAgentRules(); |
| 40 | + |
| 41 | + maybeWriteAgentRules(config()); |
| 42 | + expect(fs.readFileSync(agentsMdPath(), 'utf8')).toContain('<!-- BEGIN:clerk-agent-rules:expo -->'); |
| 43 | + |
| 44 | + fs.rmSync(agentsMdPath()); |
| 45 | + maybeWriteAgentRules(config()); |
| 46 | + expect(fs.existsSync(agentsMdPath())).toBe(false); |
| 47 | + }); |
| 48 | + |
| 49 | + test('skips when the agent variable is set to a false value', () => { |
| 50 | + vi.stubEnv('CLAUDECODE', 'False'); |
| 51 | + |
| 52 | + loadMaybeWriteAgentRules()(config()); |
| 53 | + |
| 54 | + expect(fs.existsSync(agentsMdPath())).toBe(false); |
| 55 | + }); |
| 56 | + |
| 57 | + test('skips in production', () => { |
| 58 | + vi.stubEnv('CLAUDECODE', '1'); |
| 59 | + vi.stubEnv('NODE_ENV', 'production'); |
| 60 | + |
| 61 | + loadMaybeWriteAgentRules()(config()); |
| 62 | + |
| 63 | + expect(fs.existsSync(agentsMdPath())).toBe(false); |
| 64 | + }); |
| 65 | + |
| 66 | + test('skips in CI', () => { |
| 67 | + vi.stubEnv('CLAUDECODE', '1'); |
| 68 | + vi.stubEnv('CI', 'true'); |
| 69 | + |
| 70 | + loadMaybeWriteAgentRules()(config()); |
| 71 | + |
| 72 | + expect(fs.existsSync(agentsMdPath())).toBe(false); |
| 73 | + }); |
| 74 | +}); |
0 commit comments