UNPKG

advent-of-code-client

Version:

A NodeJS client for fetching inputs, running puzzle challenges and submitting answers to Advent Of Code directly from your JavaScript code.

184 lines 10.2 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; exports.postAnswer = exports.getInput = void 0; var node_fetch_1 = __importDefault(require("node-fetch")); var logger_1 = __importDefault(require("./logger")); var pkg = require('../../package.json'); var HOST_URI = 'https://adventofcode.com'; var USER_AGENT = "node/".concat(process.version, " ").concat(pkg.name, "/").concat(pkg.version); var TOO_EARLY_REQUEST_TEXT = "please don't repeatedly request this endpoint before it unlocks"; var UNAUTHENTICATED_INPUT_TEXT = 'please log in to get your puzzle input'; var INTERNAL_SERVER_ERROR_TEXT = 'internal server error'; var HTML_RESPONSE_TEXT = '!DOCTYPE HTML'; var CORRECT_ANSWER_TEXT = "that's the right answer"; var INCORRECT_ANSWER_TEXT = "that's not the right answer"; var TOO_RECENT_ANSWER_TEXT = 'you gave an answer too recently; you have to wait after submitting an answer before trying again.'; var INCORRECT_LEVEL_TEXT = "you don't seem to be solving the right level"; var fetchFromCacheOrAoC = function (cacheKey, uri, options, config, cache) { return __awaiter(void 0, void 0, void 0, function () { var cachedResponse, response; return __generator(this, function (_a) { switch (_a.label) { case 0: if (config.useCache) { cachedResponse = cache.get(cacheKey); if (cachedResponse) { logger_1["default"].debug('Found a previously cached response, returning response from cache'); return [2, Promise.resolve(cachedResponse)]; } } logger_1["default"].debug('No previously cached response found, fetching from Advent Of Code'); return [4, (0, node_fetch_1["default"])(uri, options)]; case 1: response = _a.sent(); return [2, response.text()]; } }); }); }; function getInput(config, cache) { return __awaiter(this, void 0, void 0, function () { var year, day, token, uri, options, cacheKey, textResponse; return __generator(this, function (_a) { switch (_a.label) { case 0: year = config.year, day = config.day, token = config.token; uri = "".concat(HOST_URI, "/").concat(year, "/day/").concat(day, "/input"); options = { method: 'get', headers: { 'Content-Type': 'text/plain', Cookie: "session=".concat(token), 'User-Agent': USER_AGENT } }; cacheKey = JSON.stringify({ uri: uri, token: token }); return [4, fetchFromCacheOrAoC(cacheKey, uri, options, config, cache)]; case 1: textResponse = _a.sent(); if (textResponse.toLowerCase().includes(UNAUTHENTICATED_INPUT_TEXT)) { return [2, Promise.reject(new Error('You must log in to get your puzzle input, please provide a valid token'))]; } if (textResponse.toLowerCase().includes(TOO_EARLY_REQUEST_TEXT)) { return [2, Promise.reject(new Error('This puzzle has not opened yet, please wait until the puzzle unlocks!'))]; } if (textResponse.toLowerCase().includes(INTERNAL_SERVER_ERROR_TEXT)) { return [2, Promise.reject(new Error('An unexpected error occurred while fetching the input, internal server error.'))]; } if (textResponse.includes(HTML_RESPONSE_TEXT)) { return [2, Promise.reject(new Error('An error occurred while fetching the input. Are you authenticated correctly?'))]; } if (config.useCache && !cache.get(cacheKey)) { cache.set(cacheKey, textResponse); } return [2, textResponse]; } }); }); } exports.getInput = getInput; var postAnswer = function (_a, config, cache) { var part = _a.part, answer = _a.answer; return __awaiter(void 0, void 0, void 0, function () { var year, day, token, uri, options, cacheKey, cachedResponse, textResponse, text, leftToWaitText; return __generator(this, function (_b) { switch (_b.label) { case 0: year = config.year, day = config.day, token = config.token; uri = "".concat(HOST_URI, "/").concat(year, "/day/").concat(day, "/answer"); options = { method: 'post', headers: { Cookie: "session=".concat(token), 'User-Agent': USER_AGENT, 'cache-control': 'no-cache', 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ level: "".concat(part), answer: "".concat(answer) }) }; cacheKey = JSON.stringify({ uri: uri, token: token, part: part, answer: answer }); cachedResponse = cache.get(cacheKey); return [4, fetchFromCacheOrAoC(cacheKey, uri, options, config, cache)]; case 1: textResponse = _b.sent(); text = textResponse.toLowerCase(); if (text.includes(CORRECT_ANSWER_TEXT)) { if (config.useCache && !cachedResponse) { cache.set(cacheKey, textResponse); } return [2, Promise.resolve({ correct: true })]; } if (text.includes(INCORRECT_ANSWER_TEXT)) { if (config.useCache && !cachedResponse) { cache.set(cacheKey, textResponse); } return [2, Promise.resolve({ correct: false })]; } if (text.includes(TOO_RECENT_ANSWER_TEXT)) { leftToWaitText = text .split(TOO_RECENT_ANSWER_TEXT)[1] .split('.')[0] .trim(); return [2, Promise.reject(new Error("You gave an answer too recently, ".concat(leftToWaitText, ".")))]; } if (text.includes(TOO_EARLY_REQUEST_TEXT)) { return [2, Promise.reject(new Error('This puzzle has not opened yet, please wait until the puzzle unlocks!'))]; } if (text.includes(INCORRECT_LEVEL_TEXT)) { return [2, Promise.reject(new Error("You don't seem to be solving the correct level. Did you already complete it?"))]; } return [2, Promise.reject(new Error('Unknown response from AoC. Are you authenticated correctly?'))]; } }); }); }; exports.postAnswer = postAnswer; //# sourceMappingURL=api.js.map