<commit_before>import { runtime, wrapAsync } from './runtime';

const { WebAuthenticationBroker, WebAuthenticationOptions, WebAuthenticationStatus } = Windows.Security.Authentication.Web;
const { HttpStatusCode } = Windows.Web.Http;
const { Uri } = Windows.Foundation;

export const identity: typeof chrome.identity = {
	launchWebAuthFlow: wrapAsync(async (details: chrome.identity.WebAuthFlowOptions) => {
		let result = await WebAuthenticationBroker.authenticateAsync(
			details.interactive ? WebAuthenticationOptions.none : WebAuthenticationOptions.silentMode,
			new Uri(details.url),
			new Uri(identity.getRedirectURL())
		);
		switch (result.responseStatus) {
			case WebAuthenticationStatus.success: {
				return result.responseData;
			}

			case WebAuthenticationStatus.errorHttp: {
				let code = result.responseErrorDetail;
				throw new Error(`HTTP error: ${HttpStatusCode[code] || code}`);
			}

			case WebAuthenticationStatus.userCancel: {
				throw new Error('The user did not approve access.');
			}
		}
		if (result.responseStatus !== WebAuthenticationStatus.success) {
			throw new Error();
		}
	}),

	getRedirectURL: (path?: string) => `https://${runtime.id}.chromiumapp.org/${path.replace(/^\//, '')}`
};<commit_msg>Implement basic chrome.identity.getAuthToken (w/o caching and renewal).<commit_after>import { runtime, wrapAsync } from './runtime';

const { WebAuthenticationBroker, WebAuthenticationOptions, WebAuthenticationStatus } = Windows.Security.Authentication.Web;
const { HttpStatusCode } = Windows.Web.Http;
const { Uri } = Windows.Foundation;
type Uri = Windows.Foundation.Uri;

async function authenticate(interactive: boolean, start: Uri, end: Uri) {
	let result = await WebAuthenticationBroker.authenticateAsync(
		interactive ? WebAuthenticationOptions.none : WebAuthenticationOptions.silentMode,
		start,
		end
	);
	switch (result.responseStatus) {
		case WebAuthenticationStatus.success: {
			return result.responseData;
		}

		case WebAuthenticationStatus.errorHttp: {
			let code = result.responseErrorDetail;
			throw new Error(`HTTP error: ${HttpStatusCode[code] || code}`);
		}

		case WebAuthenticationStatus.userCancel: {
			throw new Error('The user did not approve access.');
		}
	}
}

function uri(strings: TemplateStringsArray, ...values: any[]) {
	return String.raw(strings, values.map(encodeURIComponent));
}

const googleCallbackUrl = 'http://localhost/';
const googleCallbackUri = new Uri(googleCallbackUrl);

export const identity: typeof chrome.identity = {
	getAuthToken: wrapAsync(async (details: chrome.identity.TokenDetails = {}) => {
		let clientId = '';
		let url = await authenticate(
			false,
			new Windows.Foundation.Uri(`https://accounts.google.com/o/oauth2/auth?client_id=${
				encodeURIComponent(clientId)
			}&redirect_uri=${
				encodeURIComponent(googleCallbackUrl)
			}&response_type=code&scope=${
				encodeURIComponent(details.scopes.join(' '))
			}`),
			googleCallbackUri
		);
		let code = new Windows.Foundation.Uri(url).queryParsed.getFirstValueByName('code');
		let content = new Windows.Foundation.Collections.StringMap();
		content.insert('code', code);
		content.insert('client_id', clientId);
		content.insert('redirect_uri', googleCallbackUrl);
		content.insert('grant_type', 'authorization_code');
		let http = new Windows.Web.Http.HttpClient();
		try {
			let response = await http.postAsync(new Uri('https://www.googleapis.com/oauth2/v4/token'), new Windows.Web.Http.HttpFormUrlEncodedContent(content));
			try {
				response.ensureSuccessStatusCode();
				let {
					access_token: accessToken,
					refresh_token: refreshToken,
					expires_in: expiresIn
				}: {
					access_token: string,
					refresh_token: string,
					expires_in: number
				} = JSON.parse(await response.content.readAsStringAsync());
				return accessToken;
			} finally {
				response.close();
			}
		} finally {
			http.close();
		}
	}),

	getProfileUserInfo: wrapAsync(async () => ({
		email: '',
		id: ''
	})),

	launchWebAuthFlow: wrapAsync((details: chrome.identity.WebAuthFlowOptions) => authenticate(
		details.interactive,
		new Uri(details.url),
		new Uri(identity.getRedirectURL())
	)),

	getRedirectURL: (path?: string) => `https://${runtime.id}.chromiumapp.org/${path.replace(/^\//, '')}`
};
{'fraction_non_alphanumeric': 0.1323185011709602, 'fraction_numerical': 0.000702576112412178, 'mean_word_length': 4.771621621621621, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1304069', 'n_tokens_mistral': 1404, 'n_tokens_neox': 1242, 'n_words': 249}