import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { processContext } from '../cli-operation.ts'; import type { DoctorContext } from '../diagnostics/doctor.ts'; import { withIosOperationScope } from '../integrations/ios-operation-scope.ts'; import type { IosProject } from '../integrations/ios-project.ts'; import { projectPluginAt, projectRegistry } from '../integrations/projects.ts'; import { recognition } from '../workspace/discovery.ts'; let dir: string; let home: string; const MARKER = 'stim-sentinel.marker'; const IOS = `{ cacheIneligible: 'the fixture builds with its own script', configurationProblem: (scheme) => (scheme === undefined ? null : { message: 'no schemes', remedy: 'Drop --scheme.' }), bundleId: () => BUNDLE_ID, simulator: () => null, incremental: () => undefined, build: ({ root, simulator, env }) => ({ argv: [root + '/build.sh', simulator ?? 'none'], env }), result: ({ lines }) => ({ app: lines.at(-1) ?? null, diagnostics: [] }), doctor: () => [{ level: 'note', title: 'Fixture app', detail: 'built by build.sh', fix: null }], }`; function write(path: string, text = '') { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); } function plugin(name: string, source: string, project: Record = {}): string { const at = join(home, name); write( join(at, 'package.json'), JSON.stringify({ name, version: '1.2.3', stimPlugin: { kinds: { project: 2 }, project: { id: name, name: 'Fixture', markers: [MARKER], module: 'plugin.mjs', targets: { ios: {} }, ...project, }, }, }), ); write(join(at, 'plugin.mjs'), source); return at; } function setPlugins(...plugins: string[]) { write(join(home, 'config.json'), JSON.stringify({ plugins })); } function root(name: string, files: Record): string { const at = join(dir, name); for (const [file, text] of Object.entries(files)) write(join(at, file), text); return at; } const resolved = (at: string) => ({ context: { projectPath: at, gitCommonDir: null, repoRoot: null }, settings: {}, }); function useIos(at: string, use: (project: IosProject) => Promise) { const selected = projectRegistry.selectIos(at); if (!('load' in selected)) throw new Error(selected.problem.message); return withIosOperationScope(processContext(at), async (scope) => use(await selected.load({}, scope))); } function doctorContext(at: string, platform?: 'ios' | 'android'): DoctorContext { return { root: at, options: { platform }, settings: {}, optimizations: null, platforms: [], repoRoot: null }; } async function refusal(promise: Promise): Promise { const error = await promise.then( () => null, (failure: unknown) => failure, ); if (!(error instanceof Error)) throw new Error('expected the load to refuse'); return error; } beforeEach(() => { dir = realpathSync(mkdtempSync(join(tmpdir(), 'stim-plugin-ios-'))); home = realpathSync(mkdtempSync(join(tmpdir(), 'stim-home-'))); process.env.STIM_HOME = home; }); afterEach(() => { rmSync(dir, { recursive: true, force: true }); rmSync(home, { recursive: true, force: true }); delete process.env.STIM_HOME; }); /** Calls every registry method at `at`, every load it hands out, and doctor unscoped and for each platform. */ async function touchEverything(at: string): Promise { projectRegistry.findProjectRoot(at); projectRegistry.isMobileProject(at); projectRegistry.keepsWorkspace(at); projectRegistry.detectProject(at, { ...resolved(at), settings: { web: { url: 'http://localhost:8000' } } }); for (const operation of ['ios', 'android', 'macos', 'dev-server', 'web'] as const) projectRegistry.projectProblem(at, operation); const ios = projectRegistry.selectIos(at); const android = projectRegistry.selectAndroid(at); const macos = projectRegistry.selectMacos(at); const web = projectRegistry.selectWeb(at); const loads = [ 'load' in ios ? () => withIosOperationScope(processContext(at), (scope) => ios.load({}, scope)) : null, 'load' in android ? () => android.load(resolved(at)) : null, 'load' in macos ? () => macos.load() : null, 'load' in web ? () => web.load() : null, ]; for (const load of loads) await load?.().catch(() => undefined); for (const platform of [undefined, 'ios', 'android'] as const) { const doctors = await projectRegistry.selectDoctor(at, platform).load(); for (const doctor of doctors) await doctor.inspect(doctorContext(at, platform)); } } const sentinelSource = (sentinel: string) => `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(sentinel)}, 'imported');\nthrow new Error('the sentinel module ran');\n`; test('no module is imported in a root of another project type, by any registry method or load it hands out', async () => { const sentinel = join(home, 'imported'); setPlugins(plugin('sentinel', sentinelSource(sentinel))); const rn = JSON.stringify({ dependencies: { 'react-native': '0.81.0' } }); const expo = { 'package.json': JSON.stringify({ dependencies: { expo: '57.0.0' } }), 'app.json': '{}' }; const nativeAndroid = { 'settings.gradle.kts': '', gradlew: '' }; const xcodeProject = readFileSync( new URL('../../../../test/e2e/native/fixtures/xcode/NativeAcceptance.xcodeproj/project.pbxproj', import.meta.url), 'utf8', ) .replaceAll('iphoneos iphonesimulator', 'macosx') .replaceAll('iphoneos', 'macosx'); const roots = [ root('react-native', { 'package.json': rn }), root('react-native-with-marker', { 'package.json': rn, [MARKER]: '' }), root('expo', expo), root('expo-with-marker', { ...expo, [MARKER]: '' }), root('native-android', nativeAndroid), root('native-android-with-marker', { ...nativeAndroid, [MARKER]: '' }), root('swift', { 'Package.swift': '' }), root('swift-with-marker', { 'Package.swift': '', [MARKER]: '' }), root('react-native/ios', { [MARKER]: '' }), root('expo/android', { [MARKER]: '', 'package.json': '{}' }), root('macos-xcode', { 'App.xcodeproj/project.pbxproj': xcodeProject, [MARKER]: '' }), root('xcode-workspace', { 'App.xcworkspace/contents.xcworkspacedata': '', [MARKER]: '' }), root('web', { 'index.html': '' }), ]; for (const at of roots) { await touchEverything(at); expect(existsSync(sentinel) ? at : null).toBeNull(); } for (const [folder, type] of [ ['native-android-with-marker', 'native Android project'], ['swift-with-marker', 'Swift package'], ['react-native/ios', 'native folder owned by a React Native or Expo project'], ['expo/android', 'native folder owned by a React Native or Expo project'], ['macos-xcode', 'Xcode project'], ['xcode-workspace', 'Xcode project'], ] as const) { const at = join(dir, folder); const problem = { kind: 'not-an-app', message: expect.stringContaining(type) }; expect(projectRegistry.selectIos(at)).toMatchObject({ problem }); expect(projectRegistry.projectProblem(at, 'ios')).toMatchObject(problem); expect(projectRegistry.selectDoctor(at, 'ios')).toMatchObject({ platforms: [], problem }); expect(projectRegistry.selectDoctor(at).platforms).not.toContain('ios'); } const own = root('fixture', { [MARKER]: '', 'package.json': '{"name":"fixture"}', 'index.html': '' }); expect(projectRegistry.detectProject(own, resolved(own)).platforms).toContain('ios'); expect(projectRegistry.selectIos(own)).toMatchObject({ id: 'plugin-project', }); const selected = projectRegistry.selectIos(own); if (!('load' in selected)) throw new Error(selected.problem.message); await expect(selected.load({})).rejects.toMatchObject({ code: 'STIM_NO_PROJECT' }); expect(existsSync(sentinel)).toBe(false); expect(await refusal(useIos(own, async () => {}))).toMatchObject({ code: 'STIM_NO_PROJECT', message: `The plugin sentinel cannot serve the Fixture project at ${own}: the module did not load: the sentinel module ran.`, remedy: `Fix plugin.mjs in the plugin at ${join(home, 'sentinel')}, then run stim doctor --platform ios in ${own} to check that it loads.`, }); expect(existsSync(sentinel)).toBe(true); const [doctor] = await projectRegistry.selectDoctor(own).load(); expect(await doctor?.inspect(doctorContext(own))).toEqual([ expect.objectContaining({ level: 'cost', title: 'The plugin sentinel cannot load', fix: expect.stringContaining(`run stim doctor --platform ios in ${own}`), }), ]); }); test('native folder casing follows filesystem identity', async () => { const sentinel = join(home, 'imported'); setPlugins(plugin('sentinel', sentinelSource(sentinel))); const owner = root('react-native', { 'package.json': JSON.stringify({ dependencies: { 'react-native': '0.81.0' } }), [`iOS/${MARKER}`]: '', }); const native = join(owner, 'iOS'); const conventional = join(owner, 'ios'); const aliases = existsSync(conventional); if (!aliases) write(join(conventional, MARKER)); const refused = { problem: { message: expect.stringContaining('native folder owned by a React Native or Expo project') }, }; expect(projectRegistry.selectIos(native)).toMatchObject(aliases ? refused : { id: 'plugin-project' }); expect(projectRegistry.findProjectRoot(native)).toBe(aliases ? owner : native); expect(projectRegistry.selectIos(conventional)).toMatchObject(refused); expect(projectRegistry.findProjectRoot(conventional)).toBe(owner); await touchEverything(conventional); expect(existsSync(sentinel)).toBe(false); }); test.skipIf(process.platform === 'win32')( 'a non-app ancestor with an unrelated iOS symlink loop does not exclude the plugin', () => { setPlugins(plugin('sentinel', '')); const ancestor = root('tools', { 'package.json': '{"name":"tools"}', [`plugin/${MARKER}`]: '' }); symlinkSync('ios', join(ancestor, 'ios')); const own = join(ancestor, 'plugin'); expect(projectRegistry.selectIos(own)).toMatchObject({ id: 'plugin-project' }); expect(projectRegistry.findProjectRoot(own)).toBe(own); }, ); test.skipIf(process.platform === 'win32')( 'a lexical iOS symlink identifies its app owner even when its target is outside the app', async () => { const sentinel = join(home, 'imported'); setPlugins(plugin('sentinel', sentinelSource(sentinel))); const owner = root('react-native', { 'package.json': JSON.stringify({ dependencies: { 'react-native': '0.81.0' } }), }); const target = root('external', { [MARKER]: '', 'src/index.js': '' }); const alias = join(owner, 'external'); symlinkSync(target, alias, 'dir'); const retained = projectRegistry.selectIos(alias); if (!('load' in retained)) throw new Error(retained.problem.message); const link = join(owner, 'ios'); symlinkSync(target, link, 'dir'); await touchEverything(link); expect(projectRegistry.selectIos(link)).toMatchObject({ problem: { message: expect.stringContaining('native folder owned by a React Native or Expo project') }, }); expect(projectRegistry.findProjectRoot(join(link, 'src'))).toBe(owner); expect(projectRegistry.selectIos(target)).toMatchObject({ id: 'plugin-project' }); expect(projectRegistry.findProjectRoot(target)).toBe(target); await expect( withIosOperationScope(processContext(target), (scope) => retained.load({}, scope)), ).rejects.toMatchObject({ code: 'STIM_NO_PROJECT', message: expect.stringContaining('native folder owned by a React Native or Expo project'), }); expect(existsSync(sentinel)).toBe(false); }, ); test.skipIf(process.platform === 'win32')( 'a conventional iOS symlink excludes its differently named in-tree target', async () => { const sentinel = join(home, 'imported'); setPlugins(plugin('sentinel', sentinelSource(sentinel))); const owner = root('react-native', { 'package.json': JSON.stringify({ dependencies: { 'react-native': '0.81.0' } }), 'native/package.json': '{"name":"tools"}', [`native/apple/${MARKER}`]: '', }); const target = join(owner, 'native', 'apple'); const link = join(owner, 'ios'); const selected = projectRegistry.selectIos(target); if (!('load' in selected)) throw new Error(selected.problem.message); symlinkSync(target, link, 'dir'); const problem = { kind: 'not-an-app', message: expect.stringContaining('native folder owned by a React Native or Expo project'), }; for (const at of [target, link]) { await touchEverything(at); expect(projectRegistry.selectIos(at)).toMatchObject({ problem }); expect(projectRegistry.findProjectRoot(at)).toBe(owner); expect(existsSync(sentinel)).toBe(false); } await expect( withIosOperationScope(processContext(target), (scope) => selected.load({}, scope)), ).rejects.toMatchObject({ code: 'STIM_NO_PROJECT', message: problem.message, }); expect(existsSync(sentinel)).toBe(false); }, ); test('a refused iOS module needs an independent manifest to claim a React Native Android folder', () => { const sentinel = join(home, 'imported'); const source = sentinelSource(sentinel); setPlugins(plugin('sentinel', source)); const owner = root('react-native', { 'package.json': JSON.stringify({ dependencies: { 'react-native': '0.81.0' } }), [`android/${MARKER}`]: '', 'android/settings.gradle.kts': '', 'android/gradlew': '', }); const native = join(owner, 'android'); expect(projectRegistry.findProjectRoot(native)).toBe(owner); expect(projectRegistry.selectAndroid(native)).toMatchObject({ problem: { message: expect.stringContaining(`belongs to the project at ${owner}`) }, }); expect(projectRegistry.selectIos(native)).toMatchObject({ problem: { message: expect.stringContaining(`belongs to the project at ${owner}`) }, }); expect(recognition(native)).toBe(false); expect(projectPluginAt(native)).toBeNull(); const android = { build: { debug: ['godot', '{output}'], output: 'apk' } }; const combined = plugin('sentinel', source, { targets: { ios: {}, android } }); setPlugins(combined); expect(projectRegistry.findProjectRoot(native)).toBe(owner); const independent = join(home, 'independent'); for (const kind of [1, 2]) { write( join(independent, 'package.json'), JSON.stringify({ name: 'independent', stimPlugin: { kinds: { project: kind }, project: { id: 'independent', name: 'Independent', markers: [MARKER], ...(kind === 2 && { targets: { android } }), }, }, }), ); setPlugins(combined, independent); expect(projectRegistry.findProjectRoot(native)).toBe(native); expect(projectRegistry.selectAndroid(native)).toMatchObject({ id: 'native-android' }); } expect(existsSync(sentinel)).toBe(false); }); test('retained iOS loaders refuse to import after the root becomes a built-in project', async () => { const sentinel = join(home, 'imported'); setPlugins(plugin('sentinel', sentinelSource(sentinel))); const at = root('fixture', { [MARKER]: '' }); const selected = projectRegistry.selectIos(at); if (!('load' in selected)) throw new Error(selected.problem.message); const [doctor] = await projectRegistry.selectDoctor(at, 'ios').load(); if (!doctor) throw new Error('expected an iOS doctor'); write(join(at, 'Package.swift')); await expect(withIosOperationScope(processContext(at), (scope) => selected.load({}, scope))).rejects.toMatchObject({ code: 'STIM_NO_PROJECT', message: expect.stringContaining('Swift package'), }); expect(await doctor.inspect(doctorContext(at, 'ios'))).toEqual([ expect.objectContaining({ level: 'cost', detail: expect.stringContaining('Swift package'), fix: 'Run the plugin from its own project folder.', }), ]); expect(existsSync(sentinel)).toBe(false); }); test.each(['marker removed', 'iOS target removed', 'module changed', 'plugin disabled'] as const)( 'retained iOS loaders refuse to import after the %s', async (change) => { const sentinel = join(home, 'imported'); const source = sentinelSource(sentinel); const fixture = plugin('sentinel', source); setPlugins(fixture); const at = root('fixture', { [MARKER]: '' }); const selected = projectRegistry.selectIos(at); if (!('load' in selected)) throw new Error(selected.problem.message); const [doctor] = await projectRegistry.selectDoctor(at, 'ios').load(); if (!doctor) throw new Error('expected an iOS doctor'); switch (change) { case 'marker removed': rmSync(join(at, MARKER)); break; case 'iOS target removed': plugin('sentinel', source, { module: undefined, targets: {} }); break; case 'module changed': plugin('sentinel', source, { module: 'other.mjs' }); write(join(fixture, 'other.mjs'), source); break; case 'plugin disabled': setPlugins(); break; } await expect(withIosOperationScope(processContext(at), (scope) => selected.load({}, scope))).rejects.toMatchObject({ code: 'STIM_NO_PROJECT', message: expect.stringContaining('the iOS project selection changed'), }); expect(await doctor.inspect(doctorContext(at, 'ios'))).toEqual([ expect.objectContaining({ level: 'cost', detail: expect.stringContaining('the iOS project selection changed'), }), ]); expect(existsSync(sentinel)).toBe(false); }, ); test('discovery omits refused plugin iOS but retains built-in Android and macOS in a Gradle and Swift folder', () => { const sentinel = join(home, 'imported'); setPlugins(plugin('sentinel', sentinelSource(sentinel))); const at = root('mixed', { [MARKER]: '', 'settings.gradle.kts': '', gradlew: '', 'Package.swift': '' }); expect( projectRegistry.detectProject(at, { ...resolved(at), settings: { macos: { product: 'App', infoPlist: 'Info.plist' } }, }).platforms, ).toEqual(['android', 'macos']); expect(projectRegistry.selectIos(at)).toMatchObject({ problem: { kind: 'not-an-app' } }); expect(existsSync(sentinel)).toBe(false); }); test('a conventional native folder refuses a module when the parent manifest cannot be classified', async () => { const sentinel = join(home, 'imported'); setPlugins(plugin('sentinel', sentinelSource(sentinel))); const at = root('unclear-parent', { 'package.json': '{', [`ios/${MARKER}`]: '' }); const native = join(at, 'ios'); expect(projectRegistry.selectIos(native)).toMatchObject({ problem: { kind: 'unreadable' } }); const doctor = projectRegistry.selectDoctor(native, 'ios'); expect(doctor).toMatchObject({ platforms: [], problem: { kind: 'unreadable' } }); expect(await doctor.load()).toEqual([]); expect(existsSync(sentinel)).toBe(false); }); test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( 'an unlistable root with a readable plugin marker refuses the module before loading', async () => { const sentinel = join(home, 'imported'); setPlugins(plugin('sentinel', sentinelSource(sentinel))); const at = root('unlistable', { [MARKER]: '' }); chmodSync(at, 0o111); try { expect(projectRegistry.selectIos(at)).toMatchObject({ problem: { kind: 'unreadable' } }); const doctor = projectRegistry.selectDoctor(at); expect(doctor).toMatchObject({ platforms: [], problem: { kind: 'unreadable' } }); expect(await doctor.load()).toEqual([]); expect(existsSync(sentinel)).toBe(false); } finally { chmodSync(at, 0o755); } }, ); test('a plugin with an Android and an iOS target imports no module for an Android doctor or where a bundled app won iOS', async () => { const sentinel = join(home, 'imported'); const exportApk = ['godot', '--path', '{root}', '--export-debug', 'Android', '{output}']; setPlugins( plugin('sentinel', sentinelSource(sentinel), { targets: { ios: {}, android: { build: { debug: exportApk, output: 'apk' } } }, }), ); const own = root('fixture', { [MARKER]: '' }); const androidDoctors = await projectRegistry.selectDoctor(own, 'android').load(); for (const doctor of androidDoctors) await doctor.inspect(doctorContext(own, 'android')); const android = projectRegistry.selectAndroid(own); if ('load' in android) await android.load(resolved(own)); expect(existsSync(sentinel)).toBe(false); const swift = root('swift', { 'Package.swift': '', [MARKER]: '' }); expect(projectRegistry.selectAndroid(swift)).toMatchObject({ id: 'plugin-project' }); const doctor = projectRegistry.selectDoctor(swift); expect(doctor).toMatchObject({ platforms: ['android'], problem: null }); for (const inspection of await doctor.load()) await inspection.inspect(doctorContext(swift)); expect(existsSync(sentinel)).toBe(false); const [iosDoctor] = await projectRegistry.selectDoctor(own).load(); expect(existsSync(sentinel)).toBe(false); await iosDoctor?.inspect(doctorContext(own)); expect(existsSync(sentinel)).toBe(true); }); test.skipIf(process.platform === 'win32')( 'a loaded module serves the iOS project: the host runs its program in the root, and Stim runs the build it returns', async () => { setPlugins( plugin( 'fixture', `export async function createProjectPlugin(host) { const { code, stdout, stderr } = await host.exec('/bin/sh', ['-c', 'pwd; echo id >&2; exit 3'], { timeoutMs: 10_000 }); const success = await host.exec('/bin/sh', ['-c', 'echo ready >&2'], { timeoutMs: 10_000 }); const BUNDLE_ID = stdout.trim() === host.root && stderr === 'id\\n' && code === 3 && success.code === 0 && success.stdout === '' && success.stderr === 'ready\\n' ? 'dev.stim.fixture' : 'wrong'; return { ios: ${IOS} }; }\n`, ), ); const own = root('fixture', { [MARKER]: '' }); expect(projectRegistry.detectProject(own, resolved(own))).toEqual({ platforms: ['ios'], devServer: false, }); expect(projectRegistry.projectProblem(own, 'android')?.message).toBe( `The plugin fixture builds the Fixture project at ${own} for iOS only.`, ); await useIos(own, async (project) => { expect(await project.bundleId()).toBe('dev.stim.fixture'); expect(await project.schemeProblem('App', null)).toMatchObject({ code: 'STIM_BAD_ARG', message: 'no schemes', }); }); }, ); const MODULE_REMEDY = (own: string) => `then run stim doctor --platform ios in ${own} to check that it loads.`; test.each([ [ 'a module file that is missing', (at: string) => rmSync(join(at, 'plugin.mjs')), /its module plugin\.mjs cannot be read: ENOENT/, () => 'checks its package.json), then retry.', ], [ 'a module with no factory', (at: string) => write(join(at, 'plugin.mjs'), 'export const ios = {};\n'), /the module does not export createProjectPlugin\(\)/, MODULE_REMEDY, ], [ 'a factory that throws', (at: string) => write(join(at, 'plugin.mjs'), "export function createProjectPlugin() { throw new Error('no SDK'); }\n"), /createProjectPlugin\(\) failed: no SDK/, MODULE_REMEDY, ], [ 'a factory that returns no ios object', (at: string) => write(join(at, 'plugin.mjs'), 'export const createProjectPlugin = () => ({});\n'), /createProjectPlugin\(\) failed: returned no ios object/, MODULE_REMEDY, ], [ 'an empty ios object', (at: string) => write(join(at, 'plugin.mjs'), 'export const createProjectPlugin = () => ({ ios: {} });\n'), /ios has no build\(\) function/, MODULE_REMEDY, ], [ 'an ios object without a required member', (at: string) => write( join(at, 'plugin.mjs'), `const BUNDLE_ID = 'x';\nexport const createProjectPlugin = () => ({ ios: { ...${IOS}, result: undefined } });\n`, ), /ios has no result\(\) function/, MODULE_REMEDY, ], [ 'an optional member that is not a function', (at: string) => write( join(at, 'plugin.mjs'), `const BUNDLE_ID = 'x';\nexport const createProjectPlugin = () => ({ ios: { ...${IOS}, doctor: [] } });\n`, ), /ios\.doctor is not a function/, MODULE_REMEDY, ], [ 'a build tool name that is not one line', (at: string) => write( join(at, 'plugin.mjs'), `const BUNDLE_ID = 'x';\nexport const createProjectPlugin = () => ({ ios: { ...${IOS}, buildTool: 'fixture\\nrm' } });\n`, ), /ios\.buildTool is not one line of 1 to 40 characters/, MODULE_REMEDY, ], [ 'a member that returns the wrong shape', (at: string) => write( join(at, 'plugin.mjs'), `const BUNDLE_ID = 42;\nexport const createProjectPlugin = () => ({ ios: ${IOS} });\n`, ), /its ios\.bundleId\(\) returned 42, which is not what it declares/, () => 'Fix ios.bundleId() in the plugin at ', ], ])( '%s refuses the operation, naming the plugin, the reason and where to check it', async (_, change, reason, remedy) => { const at = plugin('fixture', ''); change(at); setPlugins(at); const own = root('fixture', { [MARKER]: '' }); const failure = await refusal(useIos(own, async (project) => project.bundleId())); expect(failure).toMatchObject({ code: 'STIM_NO_PROJECT', remedy: expect.stringContaining(remedy(own)) }); expect(failure.message.startsWith(`The plugin fixture cannot serve the Fixture project at ${own}: `)).toBe(true); expect(failure.message).toMatch(reason); }, ); test.skipIf(process.platform === 'win32')('a module linked out of the plugin directory is refused', async () => { const at = plugin('fixture', ''); write(join(dir, 'outside.mjs'), 'export const createProjectPlugin = () => ({});\n'); rmSync(join(at, 'plugin.mjs')); symlinkSync(join(dir, 'outside.mjs'), join(at, 'plugin.mjs')); setPlugins(at); const own = root('fixture', { [MARKER]: '' }); expect((await refusal(useIos(own, async () => {}))).message).toMatch( /its module plugin\.mjs resolves to .*outside\.mjs, outside the plugin directory/, ); }); test('a build program that is not an absolute path refuses the build', async () => { setPlugins( plugin( 'fixture', `const BUNDLE_ID = 'x';\nconst ios = ${IOS};\nexport const createProjectPlugin = () => ({ ios: { ...ios, build: () => ({ argv: ['build.sh'], env: {} }) } });\n`, ), ); const own = root('fixture', { [MARKER]: '' }); const { pluginProjectAt } = await import('../integrations/plugin-projects.ts'); const { bundledProjectIds } = await import('../integrations/projects.ts'); const { loadPluginIos } = await import('../integrations/plugin-module.ts'); const match = pluginProjectAt(own, bundledProjectIds()); if (!match) throw new Error('the fixture plugin does not match its root'); await withIosOperationScope(processContext(own), async (scope) => { const { ios } = await loadPluginIos(match, own, scope); await expect( ios.build({ root: own, scheme: undefined, configuration: null, simulator: null, arch: 'all', env: {} }), ).rejects.toThrow(/its ios\.build\(\) returned the program "build\.sh", not an absolute path/); expect(await ios.incremental(own, null, {})).toBeUndefined(); }); }); test('a shipped plugin whose package name is not the one its entry names is refused before its module is imported', async () => { const { loadPluginIos } = await import('../integrations/plugin-module.ts'); const sentinel = join(home, 'imported'); const at = plugin( 'fixture', `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(sentinel)}, '');\n`, ); const project = { id: 'fixture', name: 'Fixture', markers: [MARKER], module: 'plugin.mjs', targets: { ios: {} }, }; const failure = await refusal( withIosOperationScope(processContext(dir), (scope) => loadPluginIos( { reference: 'fixture', dir: at, package: '@stim-cli/plugin-other', project, }, dir, scope, ), ), ); expect(failure.message).toContain('its package.json is named @stim-cli/plugin-other, not @stim-cli/plugin-fixture'); expect(existsSync(sentinel)).toBe(false); }); test('a new iOS operation reads an edited helper from the same entry', async () => { const at = plugin( 'fixture', `import { value as BUNDLE_ID } from './lib/helper.mjs';\nexport const createProjectPlugin = () => ({ ios: ${IOS} });\n`, ); write(join(at, 'lib', 'helper.mjs'), "export const value = 'one';\n"); setPlugins(at); const own = root('fixture', { [MARKER]: '' }); const bundleId = () => useIos(own, async (project) => project.bundleId()); expect(await bundleId()).toBe('one'); write(join(at, 'lib', 'helper.mjs'), "export const value = 'two';\n"); expect(await bundleId()).toBe('two'); }); test.each([ [ 'an async member, whose promise later rejects', `const BUNDLE_ID = 'x';\nconst ios = ${IOS};\nexport const createProjectPlugin = () => ({ ios: { ...ios, bundleId: async () => { throw new Error('late'); } } });\n`, /its ios\.bundleId\(\) failed: late/, ], [ 'an ios object whose getter throws', `export const createProjectPlugin = () => ({ get ios() { throw new Error('no ios today'); } });\n`, /createProjectPlugin\(\) failed: no ios today/, ], [ 'a host.exec call without a numeric timeout', `export async function createProjectPlugin(host) { await host.exec('/bin/echo', [], { timeoutMs: 'unbounded' }); }\n`, /createProjectPlugin\(\) failed: host\.exec needs timeoutMs, a positive number of milliseconds/, ], ])('%s refuses with the plugin named, and the process keeps running', async (_, source, reason) => { setPlugins(plugin('fixture', source)); const own = root('fixture', { [MARKER]: '' }); const failure = await refusal(useIos(own, async (project) => project.bundleId())); expect(failure).toMatchObject({ code: 'STIM_NO_PROJECT' }); expect(failure.message).toMatch(/^The plugin fixture cannot serve the Fixture project/); expect(failure.message).toMatch(reason); await new Promise((resolve) => setImmediate(resolve)); }); test.each(['-tools', 'fixture_tools', 'Fixture-tools', `fixture-${'x'.repeat(57)}`])( 'a doctor finding coded %s, not a lowercase letter then up to 63 lowercase letters, digits and hyphens, reports the failed check', async (code) => { setPlugins( plugin( 'fixture', `const BUNDLE_ID = 'x';\nconst ios = ${IOS};\nexport const createProjectPlugin = () => ({ ios: { ...ios, doctor: () => [{ code: ${JSON.stringify(code)}, level: 'note', title: 'Coded', detail: 'd', fix: null }] } });\n`, ), ); const own = root('fixture', { [MARKER]: '' }); const [doctor] = await projectRegistry.selectDoctor(own, 'ios').load(); expect(await doctor?.inspect(doctorContext(own, 'ios'))).toEqual([ { level: 'cost', title: 'A project plugin failed its doctor check', detail: expect.stringMatching(/its ios\.doctor\(\) returned .*, which is not what it declares/), fix: null, }, ]); }, );