diff --git a/changes/test-kit-e2e-from-config.md b/changes/test-kit-e2e-from-config.md new file mode 100644 index 0000000..4eaeb09 --- /dev/null +++ b/changes/test-kit-e2e-from-config.md @@ -0,0 +1,21 @@ +### Fixed + +- **A CLI made by `new --from-config` passes its own `pnpm test:coverage`.** A CRM or tracker CLI with `auth.verify` + failed it (a tracker reached 52% of branches against 75%): the seed held the token check and branches on the + config's values that no test of that CLI could take both ways. The check is now cli-core's `manifestVerify`, + `pnpm generate` writes the config's values with their exact types (a removed `verify` fails typecheck), the hosts-only + fetch is cli-core's `hostsFetch`, the CRM store is cli-core's `openAppStore`, and new tests cover a sync before + `session start`, `--offline` and `api show`. +- **The daily "a newer version exists" line shows.** `src/program.ts` set up the update check but never handed it to + cli-core's `run()`, so no CLI made from the template printed it. +- **The `--offline` refusal is cli-core's `refuseOffline`**, in place of a copy in `src/context.ts`. + +### Added + +- **`kit:e2e` makes two CLIs with `new --from-config`**, a CRM over an OpenAPI description and a tracker over a GraphQL + schema, both with a token check and so without the sample, and runs the same checks as the others. The path was + checked only by hand before. + +### Changed — may break callers + +- **A new CLI pins `@wirecat/cli-core` 0.699.0**, which has `manifestVerify` and `hostsFetch`. diff --git a/kit/README.md b/kit/README.md index 2d405d8..517e83a 100644 --- a/kit/README.md +++ b/kit/README.md @@ -88,11 +88,13 @@ read before the CLI has `node_modules`: its import resolves to the kit's own cli `parseCliConfig`. In the CLI: - `pnpm generate` first writes `src/generated/wirecat-config.ts` from the config (`scripts/from-config.ts`): the - token check, the source and the hooks, which `src/` reads; the config stays the one file to edit. + token check, the source and the hooks, which `src/` reads; the config stays the one file to edit. Each value has its + exact type, and one the config leaves out is a bare `undefined`: a command that still reads it fails typecheck, not a + run. - A `source` (a `crm` or a `tracker` category) needs `auth: { preset: "token", verify }`; `new` writes the files below only for what the config holds at `new`, and `pnpm generate` then reads their values again. -- With `auth.verify`, `session start` is cli-core's `tokenSessionCommand`: it checks a token with that operation and - keeps the account's id from the answer. `verify.active` names a field that must be `true`, for a service that +- With `auth.verify`, `session start` is cli-core's `tokenSessionCommand` over `manifestVerify`: it checks a token with + that operation and keeps the account's id from the answer; the CLI holds no check of its own. `verify.active` names a field that must be `true`, for a service that answers a revoked key with 200 and `active: false`, as Attio does; anything else is "sign in again". - With `auth.verify` and a spec, the CLI starts without the template's sample: its wiring and tests reach the API and its fake, so there is nothing for `remove-sample` to do. The hosts an OAuth sign-in in the description reaches join diff --git a/kit/e2e.sh b/kit/e2e.sh index 98a8f1f..ae209e2 100755 --- a/kit/e2e.sh +++ b/kit/e2e.sh @@ -14,26 +14,19 @@ pnpm build >/dev/null tarball=$(npm pack --silent --ignore-scripts --pack-destination "$work" | tail -n 1) npm install --silent --no-save --prefix "$work/install" "$work/$tarball" -# build ; outside @wirecat, as a third party makes one, and with every flag new takes. -build() { - mkdir "$work/new-$2" - cd "$work/new-$2" - "$work/install/node_modules/.bin/cli-template" new "$1" --command "$2" --package "@example/$1" \ - --owner example --tagline "Made by kit e2e" --category "$3" --content-lang en --sign-in none \ - --api official-docs --spec "$4" --filters time --never-store tokens --untrusted none >/dev/null - cmp "$root/.gitignore" "$1/.gitignore" - cd "$1" +# checks : what a CLI made by new must pass, in its own folder. +checks() { pnpm install # As new's next steps say: the rename changes line lengths, so Biome formats the renamed files once. pnpm lint:fix - if [ "$4" != none ]; then + if [ "$2" != none ]; then # A fresh CLI builds and runs before its first pnpm generate. pnpm build env -u XDG_CONFIG_HOME -u XDG_DATA_HOME -u XDG_STATE_HOME -u XDG_CACHE_HOME HOME="$work/home" \ - DBUS_SESSION_BUS_ADDRESS=disabled: node "dist/bin/$2.js" doctor >/dev/null + DBUS_SESSION_BUS_ADDRESS=disabled: node "dist/bin/$1.js" doctor >/dev/null fi pnpm generate - if [ "$4" != none ]; then + if [ "$2" != none ]; then pnpm exec cli-contract contracts/plan.json --update pnpm exec vitest run src/mcp.test.ts --update pnpm lint:fix @@ -43,11 +36,43 @@ build() { pnpm contracts:check pnpm test:coverage pnpm docs:check +} + +# build ; outside @wirecat, as a third party makes one, and with every flag new takes. +build() { + mkdir "$work/new-$2" + cd "$work/new-$2" + "$work/install/node_modules/.bin/cli-template" new "$1" --command "$2" --package "@example/$1" \ + --owner example --tagline "Made by kit e2e" --category "$3" --content-lang en --sign-in none \ + --api official-docs --spec "$4" --filters time --never-store tokens --untrusted none >/dev/null + cmp "$root/.gitignore" "$1/.gitignore" + cd "$1" + checks "$2" "$4" echo "kit e2e: new $1 ($2, $3, --spec $4) passed lint, generate, ci:quick, contracts:check, test:coverage and docs:check" } +# from_config : new --from-config over kit/test/from-config/, a config +# with a token check (auth.verify) and a source, so the CLI starts without the sample. The preload answers the spec URL +# from the file, for `new` only: install and generate run without it. +from_config() { + mkdir "$work/config-$2" + cp "$root/kit/test/from-config/$1/wirecat.config.ts" "$work/config-$2/" + cd "$work/config-$2" + E2E_SPEC_URL="$3" E2E_SPEC_FILE="$root/kit/test/from-config/$1/$4" \ + node --import "$root/kit/test/from-config/spec-fetch.mjs" \ + "$work/install/node_modules/@wirecat/cli-template/kit/dist/main.js" \ + new --from-config wirecat.config.ts --content-lang en --api official-docs --filters text --never-store tokens \ + --untrusted records >/dev/null + [ ! -e "$2-cli/src/sample" ] + cd "$2-cli" + checks "$2" "$1" + echo "kit e2e: new --from-config ($1, $2) started without the sample and passed the same checks" +} + build demo-cli demo notes openapi build acme-workspace-cli acme-workspace crm none +from_config crm acme https://docs.acme.example/openapi.json openapi.json +from_config tracker acmet https://api.acme-tracker.example/graphql schema.json cd "$work/new-demo/demo-cli" bin=$(node -p 'require("./package.json").bin.demo') diff --git a/kit/seeds/config/scripts/from-config.ts b/kit/seeds/config/scripts/from-config.ts index 6bd6b96..3c7588c 100644 --- a/kit/seeds/config/scripts/from-config.ts +++ b/kit/seeds/config/scripts/from-config.ts @@ -25,7 +25,11 @@ if (functions.length) "move it into the hooks module the config names in hooks (./src/hooks.ts)", ) const verify = cli.auth.preset === "none" ? undefined : cli.auth.verify -const literal = (value: unknown) => (value === undefined ? "undefined" : JSON.stringify(value, null, 2)) +// A value the config leaves out is a bare `undefined`, so a command that still reads it fails typecheck, not a run. +const constant = (name: string, type: string, value: unknown) => + value === undefined + ? `export const ${name} = undefined` + : `export const ${name}: ${type} = ${JSON.stringify(value, null, 2)}` // The hooks module is imported from src/generated/, inside the bundle: it must live under src/. const hooksImport = (() => { if (!cli.hooks) return undefined @@ -49,24 +53,36 @@ const text = formatted( [ "// Generated from wirecat.config.ts by scripts/from-config.ts; run pnpm generate", "", - `export const VERIFY: { operation: string; id: string; name?: string; active?: string } | undefined = ${literal(verify)}`, + constant("VERIFY", "{ operation: string; id: string; name?: string; active?: string }", verify), "", - `export const SOURCE: Readonly> | undefined = ${literal(cli.source)}`, + constant( + "SOURCE", + "Readonly> & { readonly provider: string; readonly kinds: readonly string[] }", + cli.source, + ), "", + // Spread into the source's options: `{}` without a hooks module. ...(hooksImport - ? [`export { hooks as HOOKS } from "${hooksImport}"`] + ? [`import { hooks } from "${hooksImport}"`, "", "export const HOOK_OPTIONS = { hooks }"] : cli.category === "tracker" ? [ 'import type { TrackerManifestHooks } from "@wirecat/cli-core/tracker"', "", - "export const HOOKS: TrackerManifestHooks | undefined = undefined", + "export const HOOK_OPTIONS: { hooks?: TrackerManifestHooks } = {}", ] : [ 'import type { CrmManifestHooks } from "@wirecat/cli-core/crm"', "", - "export const HOOKS: CrmManifestHooks | undefined = undefined", + "export const HOOK_OPTIONS: { hooks?: CrmManifestHooks } = {}", ]), "", + // What a CRM reads live: its users, when the source names a call for them. + ...(cli.category === "crm" + ? [ + `export const LIVE: readonly "user"[] = ${cli.source && "users" in cli.source && cli.source.users ? '["user"]' : "[]"}`, + "", + ] + : []), ].join("\n"), ) diff --git a/kit/seeds/config/src/commands/crm.ts b/kit/seeds/config/src/commands/crm.ts index dac69cc..3ff454c 100644 --- a/kit/seeds/config/src/commands/crm.ts +++ b/kit/seeds/config/src/commands/crm.ts @@ -1,50 +1,20 @@ import { CliError } from "@wirecat/cli-base" -import { hostFetch, retrying } from "@wirecat/cli-base/http" -import { recalledAccount, serviceApiCall } from "@wirecat/cli-core/cli" +import { retrying } from "@wirecat/cli-base/http" +import { openAppStore, recalledAccount, serviceApiCall } from "@wirecat/cli-core/cli" import { crmSourceFromManifest } from "@wirecat/cli-core/crm" import { addCrmCommands, type CrmRun, openCrmStore } from "@wirecat/cli-core/crm/cli" import { Pacer, pacePathFor } from "@wirecat/cli-core/sends" -import type { MessageStore } from "@wirecat/cli-core/store" import { Command } from "commander" import { API } from "../config.js" import { contextOf, PACE, tokenOf } from "../context.js" -import { HOOKS, SOURCE } from "../generated/wirecat-config.js" -import { DESKTOP, IDENTITY } from "../identity.js" - -const provider = (): string => { - if (typeof SOURCE?.provider !== "string") throw new CliError("configuration_error", "wirecat.config.ts has no source") - return SOURCE.provider -} - -/** - * The shared store, with this CLI's provider entry written, so every other CLI's search knows it (WC-ARCH-21). A - * read-only open writes nothing, the entry included. - */ -const openStore = async (env: NodeJS.ProcessEnv, { readOnly = false } = {}): Promise => { - const { ensureSqlite } = await import("@wirecat/cli-core/sqlite-runtime") - await ensureSqlite() - const { openStore: open, storePath } = await import("@wirecat/cli-core/store") - const store = await open({ - path: storePath(env), - env, - command: IDENTITY.command, - version: IDENTITY.version, - ...(readOnly ? { readOnly } : {}), - }) - try { - if (!readOnly) - await store.accounts.registerProvider({ name: provider(), kind: "crm", aliases: [], command: IDENTITY.command }) - return store - } catch (error) { - await store.close() - throw error - } -} +import { HOOK_OPTIONS, LIVE, SOURCE } from "../generated/wirecat-config.js" +import { IDENTITY } from "../identity.js" +import { serviceFetch } from "./api.js" // The account is the one `session start` checked the token against; the store keeps each account's rows apart. const accountOf = (command: Command) => { const { env, profile } = contextOf(command) - const account = recalledAccount(IDENTITY, provider(), profile, env) + const account = recalledAccount(IDENTITY, SOURCE.provider, profile, env) if (!account) throw new CliError( "authentication_error", @@ -63,14 +33,17 @@ const open = async (command: Command, { readOnly }: { readOnly: boolean }): Prom env, profile, readOnly, - provider: provider(), - open: openStore, + provider: SOURCE.provider, + // The shared store, with this CLI's provider entry written so every other CLI's search knows it (WC-ARCH-21). + open: (at, options) => + openAppStore(at, { + app: IDENTITY, + provider: { name: SOURCE.provider, kind: "crm", aliases: [], command: IDENTITY.command }, + ...options, + }), account: () => accountOf(command), }) - const fetch = retrying( - hostFetch({ hosts: DESKTOP.hosts ?? [], ...(environment.fetch ? { fetch: environment.fetch } : {}) }), - { pacer: new Pacer(pacePathFor(IDENTITY, profile, env), PACE) }, - ) + const fetch = retrying(serviceFetch(environment), { pacer: new Pacer(pacePathFor(IDENTITY, profile, env), PACE) }) const call = serviceApiCall({ manifest: API.manifest, service: API.service, fetch, token: () => tokenOf(command) }) let source: ReturnType | undefined return { @@ -81,8 +54,7 @@ const open = async (command: Command, { readOnly }: { readOnly: boolean }): Prom store, env, locked: Boolean(env[`${IDENTITY.envPrefix}_PROFILE_LOCK`]), - source: () => - (source ??= crmSourceFromManifest(SOURCE, { api: API.manifest, call, ...(HOOKS ? { hooks: HOOKS } : {}) })), + source: () => (source ??= crmSourceFromManifest(SOURCE, { api: API.manifest, call, ...HOOK_OPTIONS })), close: () => store.close(), } } @@ -93,9 +65,9 @@ export const crmCommands = (): Command[] => { addCrmCommands(holder, { app: IDENTITY, open, - leads: Array.isArray(SOURCE?.kinds) && SOURCE.kinds.includes("lead"), + leads: SOURCE.kinds.includes("lead"), // People and companies have no live list in a manifest source yet; its users do. - ...(SOURCE?.users ? { live: ["user"] as const } : {}), + live: LIVE, }) return [...holder.commands] } diff --git a/kit/seeds/config/src/commands/session.test.ts b/kit/seeds/config/src/commands/session.test.ts index e5dda64..13a6b9e 100644 --- a/kit/seeds/config/src/commands/session.test.ts +++ b/kit/seeds/config/src/commands/session.test.ts @@ -16,7 +16,7 @@ it("session start checks the token with the call auth.verify names and remembers stdin: FAKE_API_TOKEN, }) expect(started.code, started.err).toBe(0) - expect(fake.calls.map((call) => call.operation)).toEqual([VERIFY?.operation]) + expect(fake.calls.map((call) => call.operation)).toEqual([VERIFY.operation]) expect(fake.refusals).toEqual([]) const { id } = started.json().item as { id: string } expect(id).toEqual(expect.any(String)) diff --git a/kit/seeds/config/src/commands/session.ts b/kit/seeds/config/src/commands/session.ts index 75c5efb..36f012c 100644 --- a/kit/seeds/config/src/commands/session.ts +++ b/kit/seeds/config/src/commands/session.ts @@ -1,12 +1,10 @@ -import { CliError } from "@wirecat/cli-base" -import { hostFetch } from "@wirecat/cli-base/http" -import { serviceApiCall, tokenSessionCommand } from "@wirecat/cli-core/cli" -import { valueAt } from "@wirecat/cli-core/manifest" +import { manifestVerify, tokenSessionCommand } from "@wirecat/cli-core/cli" import type { Command } from "commander" import { API, configuration } from "../config.js" import { contextOf } from "../context.js" import { VERIFY } from "../generated/wirecat-config.js" -import { DESKTOP, IDENTITY } from "../identity.js" +import { IDENTITY } from "../identity.js" +import { serviceFetch } from "./api.js" /** * `session start | status | end | list` (WC-ACCT-12): the token is checked by the call `auth.verify` names in @@ -17,25 +15,10 @@ export const sessionCommand = (): Command => app: IDENTITY, service: API.service, resolveSettings: configuration.resolveSettings, - verify: async (command, token) => { - if (!VERIFY) throw new CliError("configuration_error", "wirecat.config.ts names no auth.verify call") - const { environment } = contextOf(command) - const call = serviceApiCall({ - manifest: API.manifest, - service: API.service, - fetch: hostFetch({ hosts: DESKTOP.hosts ?? [], ...(environment.fetch ? { fetch: environment.fetch } : {}) }), - token: () => token, - }) - const answer = await call(VERIFY.operation, { path: {}, query: {}, headers: {}, fields: {} }) - // A service such as Attio answers a revoked key with 200 and `active: false`, not with 401. - if (VERIFY.active && valueAt(answer, VERIFY.active) !== true) - throw new CliError("authentication_error", `${API.service} does not accept this token; sign in again`) - const id = valueAt(answer, VERIFY.id) - if (typeof id !== "string" && typeof id !== "number") - throw new CliError("provider_error", `${API.service} answered ${VERIFY.operation} without ${VERIFY.id}`, { - reason: "verify.no-id", - }) - const name = VERIFY.name ? valueAt(answer, VERIFY.name) : undefined - return { id: String(id), account: { id: String(id), ...(typeof name === "string" ? { name } : {}) } } - }, + verify: manifestVerify({ + manifest: API.manifest, + service: API.service, + verify: VERIFY, + fetch: (command) => serviceFetch(contextOf(command).environment), + }), }) diff --git a/kit/seeds/config/src/commands/tracker.ts b/kit/seeds/config/src/commands/tracker.ts index db8418c..9ff6bb2 100644 --- a/kit/seeds/config/src/commands/tracker.ts +++ b/kit/seeds/config/src/commands/tracker.ts @@ -1,5 +1,5 @@ import { CliError } from "@wirecat/cli-base" -import { hostFetch, retrying } from "@wirecat/cli-base/http" +import { retrying } from "@wirecat/cli-base/http" import { recalledAccount, serviceApiCall } from "@wirecat/cli-core/cli" import { openCrmStore } from "@wirecat/cli-core/crm/cli" import { Pacer, pacePathFor } from "@wirecat/cli-core/sends" @@ -8,13 +8,9 @@ import { addTrackerCommands, type TrackerRun, trackerSourceFromManifest } from " import { Command } from "commander" import { API } from "../config.js" import { contextOf, PACE, tokenOf } from "../context.js" -import { HOOKS, SOURCE } from "../generated/wirecat-config.js" -import { DESKTOP, IDENTITY } from "../identity.js" - -const provider = (): string => { - if (typeof SOURCE?.provider !== "string") throw new CliError("configuration_error", "wirecat.config.ts has no source") - return SOURCE.provider -} +import { HOOK_OPTIONS, SOURCE } from "../generated/wirecat-config.js" +import { IDENTITY } from "../identity.js" +import { serviceFetch } from "./api.js" // A tracker's items are not a kind the shared search reads yet, so the store gets no provider entry. const openStore = async (env: NodeJS.ProcessEnv, { readOnly = false } = {}): Promise => { @@ -33,7 +29,7 @@ const openStore = async (env: NodeJS.ProcessEnv, { readOnly = false } = {}): Pro // The account is the one `session start` checked the token against; the store keeps each account's rows apart. const accountOf = (command: Command) => { const { env, profile } = contextOf(command) - const account = recalledAccount(IDENTITY, provider(), profile, env) + const account = recalledAccount(IDENTITY, SOURCE.provider, profile, env) if (!account) throw new CliError( "authentication_error", @@ -50,21 +46,17 @@ const open = async (command: Command, { readOnly }: { readOnly: boolean }): Prom env, profile, readOnly, - provider: provider(), + provider: SOURCE.provider, open: openStore, account: () => accountOf(command), }) - const fetch = retrying( - hostFetch({ hosts: DESKTOP.hosts ?? [], ...(environment.fetch ? { fetch: environment.fetch } : {}) }), - { pacer: new Pacer(pacePathFor(IDENTITY, profile, env), PACE) }, - ) + const fetch = retrying(serviceFetch(environment), { pacer: new Pacer(pacePathFor(IDENTITY, profile, env), PACE) }) const call = serviceApiCall({ manifest: API.manifest, service: API.service, fetch, token: () => tokenOf(command) }) let source: ReturnType | undefined return { account, store, - source: () => - (source ??= trackerSourceFromManifest(SOURCE, { api: API.manifest, call, ...(HOOKS ? { hooks: HOOKS } : {}) })), + source: () => (source ??= trackerSourceFromManifest(SOURCE, { api: API.manifest, call, ...HOOK_OPTIONS })), close: () => store.close(), } } diff --git a/kit/seeds/config/src/crm-contracts.test.ts b/kit/seeds/config/src/crm-contracts.test.ts index c2efd49..6eb5be5 100644 --- a/kit/seeds/config/src/crm-contracts.test.ts +++ b/kit/seeds/config/src/crm-contracts.test.ts @@ -15,7 +15,7 @@ import { type MessageStore, openStore } from "@wirecat/cli-core/store" import { afterEach, describe, expect, it } from "vitest" import { API } from "./config.js" import { definitions } from "./generated/definitions.js" -import { HOOKS, SOURCE, VERIFY } from "./generated/wirecat-config.js" +import { HOOK_OPTIONS, SOURCE, VERIFY } from "./generated/wirecat-config.js" import { fakeServiceApi } from "./testing/fake-api.js" import { runCli } from "./testing/harness.js" @@ -31,7 +31,7 @@ afterEach(async () => { describe("crmSourceContract over a fake of the API, from wirecat.config.ts", () => { for (const { name, run } of crmSourceContract(() => { - const fixture = crmManifestFixture(manifest, { api: API.manifest, definitions, ...(HOOKS ? { hooks: HOOKS } : {}) }) + const fixture = crmManifestFixture(manifest, { api: API.manifest, definitions, ...HOOK_OPTIONS }) fakes.push(fixture.fake) return fixture })) @@ -42,7 +42,7 @@ describe("crmSyncContract over a store", () => { for (const { name, run } of crmSyncContract(async () => { const store = await openStore({ path: join(mkdtempSync(join(tmpdir(), "crm-sync-")), "store.db") }) stores.push(store) - return { store, account: { provider: String(SOURCE?.provider), account: "example.test" } } + return { store, account: { provider: SOURCE.provider, account: "example.test" } } })) it(name, run) }) @@ -51,7 +51,7 @@ describe("crmSyncContract over a store", () => { // over it reads until its budget runs out. The CRM's rows come from crmManifestFake, which pages them to their end; the // call auth.verify names stays with fakeServiceApi, which crmManifestFake does not answer. const signInAndCrm = (crm: CrmManifestFake) => { - const verify = API.manifest.operations.find((one) => one.id === VERIFY?.operation) + const verify = API.manifest.operations.find((one) => one.id === VERIFY.operation) const path = verify?.binding.kind === "http" ? verify.binding.path : undefined const pattern = path ? new RegExp(`${path.replace(/\{[^}]+\}/g, "[^/]+")}$`) : undefined const signIn = fakeServiceApi(FAKE_MANIFEST_TOKEN) @@ -89,3 +89,18 @@ it("sync through this CLI keeps the rows under the account session start checked stored: crm.rows[kind]?.length, }) }) + +// Its own profile: the account another test signed in to stays remembered for this file. +it("sync before session start says to sign in, and after it --offline sends nothing", async () => { + const keyring = memoryKeyring() + const crm = crmManifestFake(manifest, { api: API.manifest, definitions }) + fakes.push(crm) + const service = signInAndCrm(crm) + const unsigned = await runCli(["work", "sync", "--json"], { keyring, service }) + expect(unsigned.json()).toMatchObject({ error: { code: "authentication_error" } }) + expect(unsigned.err).toContain("session start") + await runCli(["work", "session", "start", "--json"], { keyring, service, stdin: FAKE_MANIFEST_TOKEN }) + const offline = await runCli(["work", "sync", "--offline", "--json"], { keyring, service }) + expect(JSON.stringify(offline.json())).toContain("offline.refused") + expect(crm.calls).toEqual([]) +}) diff --git a/kit/seeds/config/src/testing/fake-api.ts b/kit/seeds/config/src/testing/fake-api.ts index 159b10b..da74683 100644 --- a/kit/seeds/config/src/testing/fake-api.ts +++ b/kit/seeds/config/src/testing/fake-api.ts @@ -19,10 +19,10 @@ const graphqlAuth = (token: string) => { /** The answer of the call auth.verify names, with the token marked active where auth.verify.active says. */ const verifyAnswer = (): Record { body: unknown }> => { - const operation = API.manifest.operations.find((one) => one.id === VERIFY?.operation) + const operation = API.manifest.operations.find((one) => one.id === VERIFY.operation) const schema = operation?.response?.schema - const active = VERIFY?.active - if (!VERIFY || !active || !schema) return {} + const active = VERIFY.active + if (!active || !schema) return {} return { [VERIFY.operation]: () => { const body = sampleOf({ type: "ref", ref: schema }, definitions) diff --git a/kit/seeds/config/src/tracker-contracts.test.ts b/kit/seeds/config/src/tracker-contracts.test.ts index 0bc3865..cc0d5ff 100644 --- a/kit/seeds/config/src/tracker-contracts.test.ts +++ b/kit/seeds/config/src/tracker-contracts.test.ts @@ -28,3 +28,17 @@ it("sync through this CLI sends only calls the schema allows, under the account expect(listed.code, listed.err).toBe(0) expect(fake.refusals).toEqual([]) }) + +// Its own profile: the account another test signed in to stays remembered for this file. +it("sync before session start says to sign in, and after it --offline sends nothing", async () => { + const keyring = memoryKeyring() + const fake = fakeServiceApi() + const unsigned = await runCli(["work", "sync", "--json"], { keyring, service: fake }) + expect(unsigned.json()).toMatchObject({ error: { code: "authentication_error" } }) + expect(unsigned.err).toContain("session start") + await runCli(["work", "session", "start", "--json"], { keyring, service: fake, stdin: FAKE_API_TOKEN }) + const sent = fake.calls.length + const offline = await runCli(["work", "sync", "--offline", "--json"], { keyring, service: fake }) + expect(JSON.stringify(offline.json())).toContain("offline.refused") + expect(fake.calls.length).toBe(sent) +}) diff --git a/kit/seeds/graphql/src/api.test.ts b/kit/seeds/graphql/src/api.test.ts index ffa6c6d..15c85ee 100644 --- a/kit/seeds/graphql/src/api.test.ts +++ b/kit/seeds/graphql/src/api.test.ts @@ -53,6 +53,15 @@ it("the spec offers operations", () => { expect(API.manifest.operations.length).toBeGreaterThan(0) }) +it("api show describes an operation from the generated files, without calling the service", async () => { + const [operation] = API.manifest.operations + const service = fake() + const shown = await runCli(["personal", "api", "show", String(operation?.command), "--json"], { service }) + expect(shown.code, shown.err).toBe(0) + expect(shown.json().item).toMatchObject({ operation: { id: operation?.id } }) + expect(service.calls).toEqual([]) +}) + // One test each, so a large API stays inside the per-test timeout and a failure names its operation. it.each(API.manifest.operations.map((operation) => [operation.command, operation] as const))( "sends %s as the spec describes it", diff --git a/kit/seeds/shared/src/api.test.ts b/kit/seeds/shared/src/api.test.ts index 092cb2d..18cb12b 100644 --- a/kit/seeds/shared/src/api.test.ts +++ b/kit/seeds/shared/src/api.test.ts @@ -59,6 +59,15 @@ it("the spec offers operations", () => { expect(API.manifest.operations.length).toBeGreaterThan(0) }) +it("api show describes an operation from the generated files, without calling the service", async () => { + const [operation] = API.manifest.operations + const service = fake() + const shown = await runCli(["personal", "api", "show", String(operation?.command), "--json"], { service }) + expect(shown.code, shown.err).toBe(0) + expect(shown.json().item).toMatchObject({ operation: { id: operation?.id } }) + expect(service.calls).toEqual([]) +}) + // One test each, so a large API stays inside the per-test timeout and a failure names its operation. it.each(API.manifest.operations.map((operation) => [operation.command, operation] as const))( "sends %s as the spec describes it", diff --git a/kit/seeds/shared/src/commands/api.ts b/kit/seeds/shared/src/commands/api.ts index acddd38..ba367ab 100644 --- a/kit/seeds/shared/src/commands/api.ts +++ b/kit/seeds/shared/src/commands/api.ts @@ -1,11 +1,14 @@ -import { hostFetch, retrying } from "@wirecat/cli-base/http" -import { serviceApiCommand } from "@wirecat/cli-core/cli" +import { retrying } from "@wirecat/cli-base/http" +import { hostsFetch, serviceApiCommand } from "@wirecat/cli-core/cli" import { Pacer, pacePathFor } from "@wirecat/cli-core/sends" import type { Command } from "commander" import { API, configuration } from "../config.js" -import { contextOf, PACE, tokenOf } from "../context.js" +import { contextOf, PACE, type ServiceEnvironment, tokenOf } from "../context.js" import { DESKTOP, IDENTITY } from "../identity.js" +/** The service's hosts and nothing else (WC-CMD-32), over the test's fake when it gives one. */ +export const serviceFetch = (environment: ServiceEnvironment) => hostsFetch(DESKTOP.hosts, environment.fetch) + /** * The service's raw API from its spec, `api list`, `api show` and one command per operation, through cli-core's shared * group. The manifest gives the server, the sign-in header, the paging of `--all` and the keys: each write asks or @@ -19,8 +22,7 @@ export const apiCommand = (): Command => configuration, fetch: (command) => { const { environment, env, profile } = contextOf(command) - const send = hostFetch({ hosts: DESKTOP.hosts ?? [], ...(environment.fetch ? { fetch: environment.fetch } : {}) }) - return retrying(send, { pacer: new Pacer(pacePathFor(IDENTITY, profile, env), PACE) }) + return retrying(serviceFetch(environment), { pacer: new Pacer(pacePathFor(IDENTITY, profile, env), PACE) }) }, token: tokenOf, schemas: () => import("../generated/schemas.js").then((module) => module.schemas), diff --git a/kit/src/new.ts b/kit/src/new.ts index 7411250..171e8a6 100644 --- a/kit/src/new.ts +++ b/kit/src/new.ts @@ -506,7 +506,7 @@ export const withContentLanguages = (text: string, languages: readonly string[]) // A CLI that never signs in has no account for `mcp check` to look for; with the check, it reports every profile unhealthy. export const withoutSignInCheck = (text: string): string => { - const check = /^ {4}signedIn: \(profile, env, keyring\) =>\n {6}new ProfileTokenStore\(.*\)\.signedIn\(profile\),\n/m + const check = /^ {4}signedIn: \(profile, env, keyring\) =>\s+new ProfileTokenStore\(.*\)\.signedIn\(profile\),\n/m const named = /^ {2}ProfileTokenStore,\n/m if (!check.test(text) || !named.test(text)) throw new Error("src/program.ts: no signedIn check to take out of the MCP command") diff --git a/kit/test/from-config.test.ts b/kit/test/from-config.test.ts index 707e856..4c8e838 100644 --- a/kit/test/from-config.test.ts +++ b/kit/test/from-config.test.ts @@ -120,7 +120,7 @@ describe("new --from-config", () => { ]) expect(read(dir, path), path).not.toMatch(/sample\/|fake-comments|commentsCommand/) expect(read(dir, "src/identity.ts")).toContain('hosts: ["api.acme.example", "app.acme.example"],') - expect(read(dir, "src/commands/crm.ts")).toContain('live: ["user"]') + expect(read(dir, "src/commands/crm.ts")).toContain("live: LIVE") expect(runScope).toContain("sync: \"cli-core's addCrmCommands runs it in its run") expect(read(dir, "src/program.ts")).toMatch(/apiCommand\(\),\n +\.\.\.crmCommands\(\),/) expect(read(dir, "src/crm-contracts.test.ts")).toContain("crmSourceContract(") diff --git a/kit/test/from-config/crm/openapi.json b/kit/test/from-config/crm/openapi.json new file mode 100644 index 0000000..879a8de --- /dev/null +++ b/kit/test/from-config/crm/openapi.json @@ -0,0 +1,168 @@ +{ + "openapi": "3.0.3", + "info": { "title": "Acme CRM", "version": "1" }, + "servers": [{ "url": "https://api.acme.example/v1" }], + "security": [{ "bearer": [] }], + "components": { + "securitySchemes": { "bearer": { "type": "http", "scheme": "bearer" } }, + "schemas": { + "Self": { + "type": "object", + "required": ["active", "workspace_id"], + "properties": { + "active": { "type": "boolean" }, + "workspace_id": { "type": "string" }, + "workspace_name": { "type": "string" } + } + }, + "Person": { + "type": "object", + "required": ["id", "name", "created_at"], + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "email": { "type": "string" }, + "company_id": { "type": "string" }, + "created_at": { "type": "string", "format": "date-time" } + } + }, + "Company": { + "type": "object", + "required": ["id", "name", "created_at"], + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "domain": { "type": "string" }, + "created_at": { "type": "string", "format": "date-time" } + } + }, + "Member": { + "type": "object", + "required": ["id", "name"], + "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" } } + } + }, + "parameters": { + "limit": { "name": "limit", "in": "query", "schema": { "type": "integer", "maximum": 100 } }, + "offset": { "name": "offset", "in": "query", "schema": { "type": "integer" } } + } + }, + "paths": { + "/self": { + "get": { + "operationId": "getSelf", + "summary": "The workspace the token belongs to", + "responses": { + "200": { + "description": "ok", + "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Self" } } } + } + } + } + }, + "/people": { + "get": { + "operationId": "listPeople", + "summary": "List people", + "parameters": [{ "$ref": "#/components/parameters/limit" }, { "$ref": "#/components/parameters/offset" }], + "responses": { + "200": { + "description": "ok", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["data"], + "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Person" } } } + } + } + } + } + } + } + }, + "/people/{person_id}": { + "get": { + "operationId": "getPerson", + "summary": "Get a person", + "parameters": [{ "name": "person_id", "in": "path", "required": true, "schema": { "type": "string" } }], + "responses": { + "200": { + "description": "ok", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["data"], + "properties": { "data": { "$ref": "#/components/schemas/Person" } } + } + } + } + } + } + } + }, + "/companies": { + "get": { + "operationId": "listCompanies", + "summary": "List companies", + "parameters": [{ "$ref": "#/components/parameters/limit" }, { "$ref": "#/components/parameters/offset" }], + "responses": { + "200": { + "description": "ok", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["data"], + "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Company" } } } + } + } + } + } + } + } + }, + "/companies/{company_id}": { + "get": { + "operationId": "getCompany", + "summary": "Get a company", + "parameters": [{ "name": "company_id", "in": "path", "required": true, "schema": { "type": "string" } }], + "responses": { + "200": { + "description": "ok", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["data"], + "properties": { "data": { "$ref": "#/components/schemas/Company" } } + } + } + } + } + } + } + }, + "/members": { + "get": { + "operationId": "listMembers", + "summary": "List workspace members", + "responses": { + "200": { + "description": "ok", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["data"], + "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Member" } } } + } + } + } + } + } + } + } + } +} diff --git a/kit/test/from-config/crm/wirecat.config.ts b/kit/test/from-config/crm/wirecat.config.ts new file mode 100644 index 0000000..69771e2 --- /dev/null +++ b/kit/test/from-config/crm/wirecat.config.ts @@ -0,0 +1,37 @@ +import { defineCli } from "@wirecat/cli-core/manifest" + +export default defineCli({ + identity: { command: "acme", package: "@example/acme-cli", prefix: "WCACME", service: "Acme", owner: "example" }, + spec: { kind: "openapi", from: "https://docs.acme.example/openapi.json" }, + auth: { + preset: "token", + verify: { operation: "getSelf", active: "active", id: "workspace_id", name: "workspace_name" }, + }, + category: "crm", + source: { + provider: "acme", + kinds: ["organization", "person"], + entities: { + organization: { + list: { operation: "listCompanies", query: { limit: 100 }, items: "data" }, + get: { operation: "getCompany", path: { company_id: "{id}" }, items: "data" }, + map: { externalId: "id", name: "name", url: "domain", createdAt: "created_at" }, + }, + person: { + list: { operation: "listPeople", query: { limit: 100 }, items: "data" }, + get: { operation: "getPerson", path: { person_id: "{id}" }, items: "data" }, + map: { + externalId: "id", + name: "name", + emails: { all: ["email"] }, + organizations: { all: ["company_id"] }, + createdAt: "created_at", + }, + }, + }, + users: { + call: { operation: "listMembers", items: "data" }, + map: { externalId: "id", name: "name", email: "email" }, + }, + }, +}) diff --git a/kit/test/from-config/spec-fetch.mjs b/kit/test/from-config/spec-fetch.mjs new file mode 100644 index 0000000..0c0e487 --- /dev/null +++ b/kit/test/from-config/spec-fetch.mjs @@ -0,0 +1,10 @@ +// Preloaded into `new --from-config` by kit/e2e.sh: answers the config's spec URL from a file, so the run reaches no +// service. A config's spec.from must be https, so a local server cannot stand in. Every other request goes on as sent. +import { readFileSync } from "node:fs" + +const { E2E_SPEC_URL: url, E2E_SPEC_FILE: file } = process.env +const send = globalThis.fetch +globalThis.fetch = (input, init) => + String(input instanceof Request ? input.url : input) === url + ? Promise.resolve(new Response(readFileSync(file), { headers: { "content-type": "application/json" } })) + : send(input, init) diff --git a/kit/test/from-config/tracker/schema.json b/kit/test/from-config/tracker/schema.json new file mode 100644 index 0000000..0cc79fc --- /dev/null +++ b/kit/test/from-config/tracker/schema.json @@ -0,0 +1,456 @@ +{ + "data": { + "__schema": { + "queryType": { "name": "Query" }, + "mutationType": null, + "types": [ + { + "kind": "OBJECT", + "name": "Query", + "description": null, + "fields": [ + { + "name": "teams", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "OBJECT", "name": "TeamConnection", "ofType": null } + }, + "args": [ + { + "name": "first", + "type": { "kind": "SCALAR", "name": "Int", "ofType": null }, + "defaultValue": null, + "description": null + }, + { + "name": "after", + "type": { "kind": "SCALAR", "name": "String", "ofType": null }, + "defaultValue": null, + "description": null + }, + { + "name": "includeArchived", + "type": { "kind": "SCALAR", "name": "Boolean", "ofType": null }, + "defaultValue": null, + "description": null + } + ], + "description": null, + "isDeprecated": false + }, + { + "name": "issues", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "OBJECT", "name": "IssueConnection", "ofType": null } + }, + "args": [ + { + "name": "first", + "type": { "kind": "SCALAR", "name": "Int", "ofType": null }, + "defaultValue": null, + "description": null + }, + { + "name": "after", + "type": { "kind": "SCALAR", "name": "String", "ofType": null }, + "defaultValue": null, + "description": null + }, + { + "name": "includeArchived", + "type": { "kind": "SCALAR", "name": "Boolean", "ofType": null }, + "defaultValue": null, + "description": null + }, + { + "name": "filter", + "type": { "kind": "INPUT_OBJECT", "name": "IssueFilter", "ofType": null }, + "defaultValue": null, + "description": null + } + ], + "description": null, + "isDeprecated": false + }, + { + "name": "viewer", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "OBJECT", "name": "User", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + } + ], + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "OBJECT", + "name": "Team", + "description": null, + "fields": [ + { + "name": "id", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "ID", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "name", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "key", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "createdAt", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "updatedAt", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "archivedAt", + "type": { "kind": "SCALAR", "name": "String", "ofType": null }, + "args": [], + "description": null, + "isDeprecated": false + } + ], + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "OBJECT", + "name": "Issue", + "description": null, + "fields": [ + { + "name": "id", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "ID", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "identifier", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "title", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "team", + "type": { "kind": "OBJECT", "name": "Team", "ofType": null }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "createdAt", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "updatedAt", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "archivedAt", + "type": { "kind": "SCALAR", "name": "String", "ofType": null }, + "args": [], + "description": null, + "isDeprecated": false + } + ], + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "OBJECT", + "name": "User", + "description": null, + "fields": [ + { + "name": "id", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "ID", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "name", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + } + ], + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "OBJECT", + "name": "TeamConnection", + "description": null, + "fields": [ + { + "name": "nodes", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "OBJECT", "name": "Team", "ofType": null } + } + } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "pageInfo", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "OBJECT", "name": "PageInfo", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + } + ], + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "OBJECT", + "name": "IssueConnection", + "description": null, + "fields": [ + { + "name": "nodes", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "OBJECT", "name": "Issue", "ofType": null } + } + } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "pageInfo", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "OBJECT", "name": "PageInfo", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + } + ], + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "OBJECT", + "name": "PageInfo", + "description": null, + "fields": [ + { + "name": "hasNextPage", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "Boolean", "ofType": null } + }, + "args": [], + "description": null, + "isDeprecated": false + }, + { + "name": "endCursor", + "type": { "kind": "SCALAR", "name": "String", "ofType": null }, + "args": [], + "description": null, + "isDeprecated": false + } + ], + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "INPUT_OBJECT", + "name": "IssueFilter", + "description": null, + "fields": null, + "inputFields": [ + { + "name": "updatedAt", + "type": { "kind": "INPUT_OBJECT", "name": "DateComparator", "ofType": null }, + "defaultValue": null, + "description": null + } + ], + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "INPUT_OBJECT", + "name": "DateComparator", + "description": null, + "fields": null, + "inputFields": [ + { + "name": "gte", + "type": { "kind": "SCALAR", "name": "String", "ofType": null }, + "defaultValue": null, + "description": null + } + ], + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "SCALAR", + "name": "Boolean", + "description": null, + "fields": null, + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "SCALAR", + "name": "ID", + "description": null, + "fields": null, + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "SCALAR", + "name": "Int", + "description": null, + "fields": null, + "inputFields": null, + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "SCALAR", + "name": "String", + "description": null, + "fields": null, + "inputFields": null, + "enumValues": null, + "possibleTypes": null + } + ] + } + } +} diff --git a/kit/test/from-config/tracker/wirecat.config.ts b/kit/test/from-config/tracker/wirecat.config.ts new file mode 100644 index 0000000..7c0e6ee --- /dev/null +++ b/kit/test/from-config/tracker/wirecat.config.ts @@ -0,0 +1,39 @@ +import { defineCli } from "@wirecat/cli-core/manifest" + +const times = { createdAt: "createdAt", updatedAt: "updatedAt", archivedAt: "archivedAt" } +const page = "pageInfo { hasNextPage endCursor }" +const issue = `nodes { id identifier title createdAt updatedAt archivedAt team { id } } ${page}` + +export default defineCli({ + identity: { + command: "acmet", + package: "@example/acmet-cli", + prefix: "ACMET", + service: "Acme Tracker", + owner: "example", + }, + spec: { kind: "graphql", from: "https://api.acme-tracker.example/graphql" }, + auth: { preset: "token", verify: { operation: "viewer", id: "id", name: "name" } }, + category: "tracker", + source: { + provider: "acme-tracker", + kinds: ["team", "issue"], + entities: { + team: { + list: { operation: "teams", variables: { first: 50, includeArchived: true } }, + map: { externalId: "id", name: "name", key: "key", ...times }, + }, + issue: { + list: { operation: "issues", variables: { first: 50, includeArchived: true }, selection: issue }, + changes: { + operation: "issues", + variables: { first: 50, includeArchived: true, filter: { updatedAt: { gte: "{since}" } } }, + selection: issue, + since: "iso", + }, + map: { externalId: "id", key: "identifier", title: "title", team: "team.id", ...times }, + }, + }, + self: { call: { operation: "viewer" }, path: "id" }, + }, +}) diff --git a/kit/test/seeds.test.ts b/kit/test/seeds.test.ts index 9d7411b..448c358 100644 --- a/kit/test/seeds.test.ts +++ b/kit/test/seeds.test.ts @@ -62,7 +62,7 @@ it("gives a CLI without sign-in an api group and a test fake with no token", () const api = withoutApiSignIn("src/commands/api.ts", seed("src/commands/api.ts")) const test = withoutApiSignIn("src/api.test.ts", seed("src/api.test.ts")) expect(api).not.toContain("tokenOf") - expect(api).toContain('import { contextOf, PACE } from "../context.js"') + expect(api).toContain('import { contextOf, PACE, type ServiceEnvironment } from "../context.js"') expect(test).not.toContain("FAKE_TOKEN") expect(withoutApiSignIn("src/config.ts", "as it was")).toBe("as it was") expect(() => withoutApiSignIn("src/commands/api.ts", "")).toThrow("src/commands/api.ts: no token to take out") diff --git a/package.json b/package.json index 49da7ba..feb2548 100644 --- a/package.json +++ b/package.json @@ -91,7 +91,7 @@ }, "dependencies": { "@wirecat/cli-base": "0.117.0", - "@wirecat/cli-core": "0.698.0", + "@wirecat/cli-core": "0.699.0", "commander": "15.0.0", "valibot": "1.5.0", "yaml": "2.9.1" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cfcbb3c..3cf3bc0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16,8 +16,8 @@ importers: specifier: 0.117.0 version: 0.117.0(@scalar/openapi-upgrader@0.4.6)(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) '@wirecat/cli-core': - specifier: 0.698.0 - version: 0.698.0(@wirecat/cli-base@0.117.0(@scalar/openapi-upgrader@0.4.6)(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7) + specifier: 0.699.0 + version: 0.699.0(@wirecat/cli-base@0.117.0(@scalar/openapi-upgrader@0.4.6)(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7) commander: specifier: 15.0.0 version: 15.0.0 @@ -1201,8 +1201,8 @@ packages: '@wirecat/cli-core-sqlite@1.1.0': resolution: {integrity: sha512-GpGlh/dAIX/nblBYCdT6DfWSLFxav9mxxeELQAfEuw+QZdT9unKxbi5xa02s/s4JS1P7n0PQx2sCABj4FlMRNw==} - '@wirecat/cli-core@0.698.0': - resolution: {integrity: sha512-Vv67aCuMErhjWKhpZvNkfwHk5v423LpLxXtdwfMwAY5q2eejZPM4k0FCz16lm9O02mGkL1YMkz4JC0pUBNmDxw==} + '@wirecat/cli-core@0.699.0': + resolution: {integrity: sha512-HXcxnfcVr6mVHLKk3BG2mnJrbXFiSG6raWiG7RqGO+82OMLaP7gHpxWX5K/j2DbI8zp6k4+Tl9K/iGTyEYaMMg==} engines: {node: ^22.16.0 || >=24} hasBin: true peerDependencies: @@ -3219,7 +3219,7 @@ snapshots: '@wirecat/cli-core-sqlite@1.1.0': {} - '@wirecat/cli-core@0.698.0(@wirecat/cli-base@0.117.0(@scalar/openapi-upgrader@0.4.6)(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': + '@wirecat/cli-core@0.699.0(@wirecat/cli-base@0.117.0(@scalar/openapi-upgrader@0.4.6)(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': dependencies: '@anthropic-ai/sdk': 1.3.0(zod@4.6.7) '@bomb.sh/tab': 0.0.22(commander@15.0.0) diff --git a/src/commands/session.ts b/src/commands/session.ts index 7aeb24d..ce6f48b 100644 --- a/src/commands/session.ts +++ b/src/commands/session.ts @@ -16,6 +16,7 @@ import { profilesHere, REMOTE_READ, refuseCommandName, + refuseOffline, refuseUnderReadOnly, rememberAccount, renderAnswer, @@ -25,7 +26,7 @@ import { } from "@wirecat/cli-core/cli" import { Command } from "commander" import { configuration } from "../config.js" -import { contextOf, refuseOffline, serviceFor, withService } from "../context.js" +import { contextOf, serviceFor, withService } from "../context.js" import { IDENTITY, SERVICE } from "../identity.js" // `session start | status | end | list` is every provider CLI's sign-in (WC-ACCT-12). Keep it; replace the token @@ -62,9 +63,9 @@ const startCommand = () => "keyring" as TokenStorage, ) .action(async function (this: Command, args: { credentialStorage: TokenStorage }) { - const { env, flags, profile, tokens, run } = contextOf(this) + const { env, profile, tokens, run } = contextOf(this) refuseCommandName(profile, commandWords(rootOf(this)), CLI) - refuseOffline(flags) + refuseOffline(this, SERVICE) // A secret is never an argument: it would land in shell history and in the run record (WC-SECR-5). const token = (await readSecret(`${SERVICE} API token: `, secretInputOf(this))).trim() if (!token) throw new CliError("validation_error", "no token was given") diff --git a/src/context.ts b/src/context.ts index 6baadc9..0dab7f5 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,4 +1,3 @@ -import { CliError } from "@wirecat/cli-base" import { type BaseEnvironment, baseContext, @@ -6,6 +5,7 @@ import { environmentOf, type GlobalFlags, ProfileTokenStore, + refuseOffline, } from "@wirecat/cli-core/cli" import { Pacer, pacePathFor } from "@wirecat/cli-core/sends" import type { Command } from "commander" @@ -36,17 +36,12 @@ export const contextOf = (command: Command) => { tokens: new ProfileTokenStore({ app: IDENTITY, env: base.env, - ...(base.keyring ? { keyring: base.keyring } : {}), + keyring: base.keyring, warn: base.renderer.warn, }), } } -export const refuseOffline = (flags: GlobalFlags) => { - if (flags.offline) - throw new CliError("permission_error", `this needs ${SERVICE}; leave out --offline`, { reason: "offline.refused" }) -} - /** The service for one run, with the token it was given; `events` comes from `run()`, so each request is recorded. */ export const serviceFor = (command: Command, token: string, events: EventSink) => { const { environment, env, profile } = contextOf(command) @@ -63,8 +58,8 @@ export const serviceFor = (command: Command, token: string, events: EventSink) = /** The profile's saved token, or an authentication error that says how to sign in. Read before any request. */ export const tokenOf = (command: Command): string => { - const { flags, profile, tokens } = contextOf(command) - refuseOffline(flags) + const { profile, tokens } = contextOf(command) + refuseOffline(command, SERVICE) return tokens.need(profile) } diff --git a/src/identity.ts b/src/identity.ts index ce00073..cc9b73d 100644 --- a/src/identity.ts +++ b/src/identity.ts @@ -19,7 +19,7 @@ export const IDENTITY: AppIdentity = { // What `wcat` and WireCat Desktop show before the tool is installed: rewrite the tagline and the sign-in texts for // yours. The bin passes it to wcatStart before anything else loads; src/wcat.ts adds the permission keys. -export const DESKTOP: ManifestIdentity = { +export const DESKTOP = { ...IDENTITY, docs: "https://github.com/WireCatLabs/clidev-cli#readme", // SAMPLE: every host the CLI contacts (WC-CMD-32); src/sample/transport.ts reaches only these. @@ -29,6 +29,6 @@ export const DESKTOP: ManifestIdentity = { gives: "Lets your agent read and change your account through clidev.", asks: "An API token or key from the service.", }, -} +} satisfies ManifestIdentity export const SKILL = new URL("../skills/clidev-app/SKILL.md", import.meta.url) diff --git a/src/program.ts b/src/program.ts index 7c9cd1b..7715bb2 100644 --- a/src/program.ts +++ b/src/program.ts @@ -42,12 +42,13 @@ const mcpCommand = () => untrusted: ["comment text", "author names"], permissionExample: "comments.create=deny", skill: SKILL, - signedIn: (profile, env, keyring) => - new ProfileTokenStore({ app: IDENTITY, env, ...(keyring ? { keyring } : {}) }).signedIn(profile), + signedIn: (profile, env, keyring) => new ProfileTokenStore({ app: IDENTITY, env, keyring }).signedIn(profile), }) export const definition = (): ProgramDefinition => ({ app: IDENTITY, + // The daily "a newer version exists" line after a command that succeeded; _NO_UPDATE_CHECK turns it off. + update, // The whole object: cli-core refuses a command by its key only when it gets the permission table too. configuration, commands: () => [ diff --git a/src/sample/transport.ts b/src/sample/transport.ts index 07c7d5a..5a0de20 100644 --- a/src/sample/transport.ts +++ b/src/sample/transport.ts @@ -87,7 +87,7 @@ export const failureOf = (status: number, writes: boolean, retryAfterMs?: number * first may have landed (WC-OUT-20). */ export const transport = (options: TransportOptions) => { - const fetchOf = hostFetch({ hosts: DESKTOP.hosts ?? [], ...(options.fetch ? { fetch: options.fetch } : {}) }) + const fetchOf = hostFetch({ hosts: DESKTOP.hosts, ...(options.fetch ? { fetch: options.fetch } : {}) }) const sleep = options.sleep ?? realSleep const now = options.now ?? Date.now