kidchen94 reported four ways the credits refresh failed on one machine: Chrome's last-used profile decided whose session a read used, a page Chrome translated could not be parsed, a JPY billing account timed out on the wait for a "$" row, and an ambiguous billing account could only be fixed with the machine-wide VERTEX_BILLING_ACCOUNT. - Chrome profile: profileDirectories (Google account -> profile directory), profileDirectory and VERTEX_CHROME_PROFILE_DIRECTORY pass --profile-directory to every Chrome the plugin opens: reads, the kept browser and the sign-in window. The name is checked (no path separators, no "."/"..", no leading "-"), and a kept browser is never handed to a read pinned to another directory. - Billing account: billingAccounts maps a project to its billing account, ahead of the row's billingAccount and the environment. The discovery error names the project, the accounts the Console showed and the option to set. - Currency: billingCurrencies names a billing account's currency (USD, JPY). Yen is read with no minor unit and shown as "¥8500 JPY". A ¥ is never taken for yen on its own, since the Console writes yuan the same way: a ¥ table read as USD names the setting at once. Amounts need strict comma grouping. The row wait is any cell with a digit, not "$". - Translation: a page Chrome marked translated (translated-ltr/rtl on <html>) and a table with non-English column names each give an error that says so and how to turn translation off, not a timeout or "session may be expired". - Cache: the profile directory and the currency map join the cache key only when set, so existing caches are kept. - fetch_credits.mjs takes --profile-directory and --currency. Run at this head on mote (macOS, Node 22, Chrome for Testing 1234): node --test test/*.test.mjs: 84 tests, 81 pass, 3 skipped (the Linux/Windows-only ones, as on origin/main's 76), 0 fail. bun scripts/check.mjs: ok. Broken by hand: the new tests against origin/main's lib/ and index.mjs. The JPY and translated browser tests fail with the reporter's symptom (21s and 41s, "Credits table was not found or is empty; the session may be expired"), the billing test with "set VERTEX_BILLING_ACCOUNT explicitly", the profile test with "Chrome used Default, not Profile 1", and plugin.test.mjs fails to load (billingCurrenciesOf is new). Not tried: a real Console (a JPY billing account, a page Chrome translated, a real multi-profile Chrome); the fixtures are tables served from the test. Not run on Windows or Linux. Chrome's own translate preference is not written; translation is detected, not prevented. Currencies other than USD and JPY are refused, not converted.
98 lines
6.0 KiB
JavaScript
98 lines
6.0 KiB
JavaScript
#!/usr/bin/env node
|
|
import { readFile } from "node:fs/promises"
|
|
import { pathToFileURL } from "node:url"
|
|
import { closeKeptBrowsers, defaultProfile, openBrowser, routeAll } from "./browser.mjs"
|
|
import { accountOf, resolveIdentity, startLogin, tokenProvider } from "./credentials.mjs"
|
|
import { fetchCredits, parseCreditTables, readTables } from "./credits.mjs"
|
|
import { testEndpoint, summarize } from "./endpoint.mjs"
|
|
import { availableModels } from "./models.mjs"
|
|
|
|
export async function main(args = process.argv.slice(2)) {
|
|
const command = args[0] ?? "credits"
|
|
if (command === "help" || args.includes("--help")) {
|
|
console.log("Usage: node lib/fetch_credits.mjs credits|credentials|login|models|endpoint|parse-html [--project ID] [--billing-account ID] [--profile PATH] [--profile-directory NAME] [--currency USD|JPY] [--cloudsdk-config DIR] [--force] [--headed] [--account EMAIL] [--auth-mode auto|gcloud|adc] [--location REGION] [--model ID] [--json] [--file HTML]")
|
|
return
|
|
}
|
|
if (!["credits", "credentials", "login", "models", "endpoint", "parse-html"].includes(command)) throw new Error(`Unknown command: ${command}`)
|
|
const valued = new Set(["--project", "--billing-account", "--profile", "--profile-directory", "--currency", "--cloudsdk-config", "--account", "--auth-mode", "--file", "--location", "--model"])
|
|
for (let i = 1; i < args.length; i++) {
|
|
const option = args[i]
|
|
if (valued.has(option)) {
|
|
if (!args[i + 1] || args[i + 1].startsWith("--")) throw new Error(`${option} requires a value`)
|
|
i++
|
|
} else if (!["--force", "--headed", "--json"].includes(option)) throw new Error(`Unknown option: ${option}`)
|
|
}
|
|
const value = (name) => {
|
|
const i = args.indexOf(name)
|
|
if (i < 0) return undefined
|
|
if (!args[i + 1] || args[i + 1].startsWith("--")) throw new Error(`${name} requires a value`)
|
|
return args[i + 1]
|
|
}
|
|
const options = {
|
|
project: value("--project") ?? process.env.GOOGLE_VERTEX_PROJECT ?? process.env.GOOGLE_CLOUD_PROJECT,
|
|
billingAccount: value("--billing-account") ?? process.env.VERTEX_BILLING_ACCOUNT,
|
|
profile: value("--profile") ?? process.env.VERTEX_CHROME_PROFILE ?? defaultProfile(),
|
|
profileDirectory: value("--profile-directory") ?? process.env.VERTEX_CHROME_PROFILE_DIRECTORY,
|
|
account: value("--account") ?? process.env.VERTEX_GCLOUD_ACCOUNT,
|
|
authMode: value("--auth-mode") ?? process.env.VERTEX_GCLOUD_AUTH_MODE,
|
|
// Which ADC a command reads: a directory named here, else the plugin's own
|
|
// for the account, else gcloud's default. The machine-wide CLOUDSDK_CONFIG
|
|
// is deliberately not read: one variable would point every account at one
|
|
// credential, and this plugin writes only its own directories.
|
|
cloudsdkConfig: value("--cloudsdk-config"),
|
|
location: value("--location") ?? process.env.GOOGLE_VERTEX_LOCATION ?? "global",
|
|
force: args.includes("--force"), headless: !args.includes("--headed"),
|
|
}
|
|
// --currency names the currency of the billing account given with
|
|
// --billing-account; without one, the account is read in USD.
|
|
const currency = value("--currency")
|
|
if (currency && command !== "parse-html") {
|
|
if (!options.billingAccount) throw new Error("--currency needs --billing-account")
|
|
options.billingCurrencies = { [options.billingAccount]: currency }
|
|
}
|
|
if (command === "credits") {
|
|
try {
|
|
console.log(JSON.stringify(await fetchCredits(options), null, 2))
|
|
} finally { await closeKeptBrowsers() }
|
|
} else if (command === "credentials") {
|
|
const identity = await resolveIdentity(options)
|
|
const token = await tokenProvider(identity)()
|
|
const account = identity.account ?? (identity.authMode === "adc" ? await accountOf(token) : undefined)
|
|
console.log(JSON.stringify({ ...identity, ...(account ? { account } : {}), inferenceAuth: "token-verified" }, null, 2))
|
|
} else if (command === "login") {
|
|
console.error("Opening Chrome. If no Application Default Credentials exist yet, approving Google there also has gcloud write them.")
|
|
const login = await startLogin(options)
|
|
try {
|
|
console.log(JSON.stringify({ ...await login.result, inferenceAuth: "token-verified" }, null, 2))
|
|
} finally { await login.close() }
|
|
} else if (command === "models") {
|
|
console.log(JSON.stringify(await availableModels({ ...options, force: options.force }), null, 2))
|
|
} else if (command === "endpoint") {
|
|
// The models the row offers are what a real endpoint test should ask
|
|
// about; --model narrows it to one when a single answer is wanted.
|
|
const chosen = value("--model")
|
|
const models = chosen ? [chosen] : (await availableModels(options).catch(() => ({ ids: [] }))).ids
|
|
const report = await testEndpoint(options, { models })
|
|
console.log(args.includes("--json") ? JSON.stringify(report, null, 2) : summarize(report))
|
|
if (!report.reachable) process.exitCode = 1
|
|
} else if (command === "parse-html") {
|
|
const file = value("--file")
|
|
if (!file) throw new Error("parse-html requires --file PATH")
|
|
const browser = await openBrowser({ profile: options.profile, headless: true, javaScriptEnabled: false })
|
|
try {
|
|
// The file is data, never code: scripts are stripped before it is parsed,
|
|
// and every request it would make is refused.
|
|
await routeAll(browser.page, () => undefined)
|
|
const html = (await readFile(file, "utf8")).replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi, "")
|
|
const encoded = Buffer.from(html).toString("base64")
|
|
await browser.page.send("Page.navigate", { url: `data:text/html;base64,${encoded}` })
|
|
await browser.page.waitForFunction(() => document.readyState !== "loading")
|
|
console.log(JSON.stringify(parseCreditTables(await readTables(browser.page), { currency: currency?.toUpperCase() ?? "USD", billingAccount: options.billingAccount }), null, 2))
|
|
} finally { await browser.close() }
|
|
}
|
|
}
|
|
|
|
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
main().catch((error) => { console.error(JSON.stringify({ error: error.message })); process.exitCode = 1 })
|
|
}
|