( sessionName: string, headed: boolean, )
| 151 | } |
| 152 | |
| 153 | export async function launchSession( |
| 154 | sessionName: string, |
| 155 | headed: boolean, |
| 156 | ): Promise<{session: BrowserSession; error?: string}> { |
| 157 | // Close existing instance if any |
| 158 | const existing = sessionMap.get(sessionName); |
| 159 | if (existing) { |
| 160 | await existing.context.close().catch(() => {}); |
| 161 | sessionMap.delete(sessionName); |
| 162 | } |
| 163 | |
| 164 | const sessionConfig = getSessionConfig(sessionName); |
| 165 | if (!sessionConfig) { |
| 166 | return { |
| 167 | session: undefined as unknown as BrowserSession, |
| 168 | error: `Session "${sessionName}" is not configured. Run: corebrain browser create-session ${sessionName} --profile <profile>`, |
| 169 | }; |
| 170 | } |
| 171 | |
| 172 | try { |
| 173 | const {chromium} = await import('playwright'); |
| 174 | |
| 175 | const profileDir = getProfileDir(sessionConfig.profile); |
| 176 | fs.mkdirSync(profileDir, {recursive: true}); |
| 177 | |
| 178 | const browserConfig = getBrowserExecutable(); |
| 179 | const launchOptions: import('playwright').LaunchOptions = { |
| 180 | headless: !headed, |
| 181 | args: ['--remote-debugging-port=0'], |
| 182 | }; |
| 183 | if (browserConfig.type !== 'default' && browserConfig.path) { |
| 184 | launchOptions.executablePath = browserConfig.path; |
| 185 | } |
| 186 | |
| 187 | const context = await chromium.launchPersistentContext(profileDir, launchOptions); |
| 188 | |
| 189 | context.on('close', () => { |
| 190 | sessionMap.delete(sessionName); |
| 191 | }); |
| 192 | |
| 193 | const page = context.pages()[0] ?? (await context.newPage()); |
| 194 | |
| 195 | const cdp = await captureCdpEndpoint(profileDir); |
| 196 | |
| 197 | const session: BrowserSession = { |
| 198 | context, |
| 199 | page, |
| 200 | sessionName, |
| 201 | profile: sessionConfig.profile, |
| 202 | profileDir, |
| 203 | headed, |
| 204 | createdAt: Date.now(), |
| 205 | cdpPort: cdp?.port, |
| 206 | cdpWsEndpoint: cdp?.wsEndpoint, |
| 207 | cdpHttpEndpoint: cdp?.httpEndpoint, |
| 208 | }; |
| 209 | |
| 210 | sessionMap.set(sessionName, session); |
no test coverage detected