@ideal-postcodes/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1 @@
1
+ Copyright (C) IDDQD Limited - All Rights Reserved
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # @ideal-postcodes/cli
2
+
3
+ The official CLI for [Ideal Postcodes](https://ideal-postcodes.co.uk) — `idpc`.
4
+
5
+ Built for LLM agents (Claude Code, Cursor, Codex) and CI/CD pipelines; usable from a terminal too.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install -g @ideal-postcodes/cli
11
+ idpc --version
12
+ ```
13
+
14
+ ## Authenticate
15
+
16
+ Two credentials — `api_key` (public) and `user_token` (private; needed for key reads, usage, logs, and configs).
17
+
18
+ ```bash
19
+ idpc auth login --api-key ak_xxx --user-token ut_xxx
20
+ ```
21
+
22
+ Resolution order per credential: `--api-key`/`--user-token` flag → `IDPC_API_KEY`/`IDPC_USER_TOKEN` env var → active profile in `~/.config/ideal-postcodes/credentials.json`.
23
+
24
+ ## Quickstart
25
+
26
+ ```bash
27
+ # Inspect a key
28
+ idpc keys details
29
+
30
+ # Cleanse an address
31
+ idpc cleanse "10 downing street, london"
32
+
33
+ # Batch cleanse from a file
34
+ cat addresses.txt | idpc cleanse --stdin > cleaned.json
35
+
36
+ # Autocomplete then resolve
37
+ idpc find "10 downing" --resolve
38
+
39
+ # Manage allowed URLs
40
+ idpc keys configs create web --allowed-urls https://example.com,https://www.example.com
41
+
42
+ # Diagnose your setup
43
+ idpc doctor
44
+ ```
45
+
46
+ ## Agent protocol
47
+
48
+ - Non-TTY (pipe, CI, agent run): output is always JSON; no prompts, no spinners.
49
+ - Exit `0` on success, `1` on error. Both success and error JSON go to **stdout** so a single pipe (`idpc … | jq`) parses uniformly; the exit code signals failure. Error shape: `{"error":{"code":"...","message":"..."}}`.
50
+ - Destructive commands require `--yes` in non-TTY.
51
+
52
+ The bundled [`skills/idpc-cli/`](./skills/idpc-cli/SKILL.md) teaches agents the flag contract and common gotchas.
53
+
54
+ ## Commands
55
+
56
+ | Group | Subcommands |
57
+ |---|---|
58
+ | `idpc auth` | `login`, `logout`, `whoami` |
59
+ | `idpc keys` | `get`, `details`, `update`, `usage`, `logs`, `configs {list,get,create,update,delete}` |
60
+ | `idpc cleanse` | Cleanse one address, a file, or stdin |
61
+ | `idpc find` | Autocomplete (interactive in TTY, JSON in non-TTY) |
62
+ | `idpc resolve` | Resolve a suggestion id to a full address |
63
+ | `idpc doctor` | Env + connectivity check |
64
+
65
+ Run `idpc <command> --help` for full flags.
66
+
67
+ ## Source
68
+
69
+ Built in the [atlas monorepo](https://github.com/ideal-postcodes/atlas/tree/main/packages/cli-ideal).
package/dist/cli.cjs ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var Be=Object.create;var F=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var Xe=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Me(t))!We.call(e,s)&&s!==o&&F(e,s,{get:()=>t[s],enumerable:!(n=Ye(t,s))||n.enumerable});return e};var v=(e,t,o)=>(o=e!=null?Be(Ve(e)):{},Xe(t||!e||!e.__esModule?F(o,"default",{value:e,enumerable:!0}):o,e));var Je=require("commander"),Fe=v(require("picocolors"),1);var ie=require("commander");var x=v(require("@clack/prompts"),1),ee=require("commander");var h=require("fs"),B=require("os"),O=require("path");var u=class extends Error{constructor(o,n,s){super(n);this.code=o;this.details=s;this.name="CliError"}};var Y=()=>process.env.IDPC_CONFIG_DIR?process.env.IDPC_CONFIG_DIR:process.env.XDG_CONFIG_HOME?(0,O.join)(process.env.XDG_CONFIG_HOME,"ideal-postcodes"):process.platform==="win32"&&process.env.APPDATA?(0,O.join)(process.env.APPDATA,"ideal-postcodes"):(0,O.join)((0,B.homedir)(),".config","ideal-postcodes"),b=()=>(0,O.join)(Y(),"credentials.json"),$=()=>{try{let e=(0,h.readFileSync)(b(),"utf-8"),t=JSON.parse(e);return t.profiles?{active_profile:t.active_profile??"default",profiles:t.profiles}:null}catch{return null}},M=e=>{let t=Y();(0,h.mkdirSync)(t,{recursive:!0,mode:448});let o=b();try{(0,h.writeFileSync)(o,`${JSON.stringify(e,null,2)}
3
+ `,{mode:384}),(0,h.chmodSync)(o,384)}catch(n){throw new u("write_failed",`Failed to write credentials file at ${o}: ${n instanceof Error?n.message:String(n)}`)}return o},D=()=>{try{return(0,h.rmSync)(b()),!0}catch{return!1}},V=e=>{let t=$();return!t||!(e in t.profiles)?!1:(delete t.profiles[e],Object.keys(t.profiles).length===0?D():(t.active_profile===e&&(t.active_profile=Object.keys(t.profiles)[0]),M(t),!0))},T=e=>e||(process.env.IDPC_PROFILE?process.env.IDPC_PROFILE:$()?.active_profile??"default"),W=e=>$()?.profiles[e],U=(e,t)=>{if(e)return{value:e,source:"flag"};if(process.env.IDPC_API_KEY)return{value:process.env.IDPC_API_KEY,source:"env"};let o=T(t),n=W(o);return n?.api_key?{value:n.api_key,source:"config",profile:o}:null},I=(e,t)=>{if(e)return{value:e,source:"flag"};if(process.env.IDPC_USER_TOKEN)return{value:process.env.IDPC_USER_TOKEN,source:"env"};let o=T(t),n=W(o);return n?.user_token?{value:n.user_token,source:"config",profile:o}:null},X=(e,t)=>{let o=U(e,t);if(!o)throw new u("missing_api_key","No API key found. Pass --api-key, set IDPC_API_KEY, or run `idpc auth login`.");return o},z=(e,t)=>{let o=I(e,t);if(!o)throw new u("missing_user_token","This command requires a user token. Pass --user-token, set IDPC_USER_TOKEN, or run `idpc auth login`.");return o},Q=(e,t)=>{let o=$()??{active_profile:e,profiles:{}},n=o.profiles[e]??{};return o.profiles[e]={...n,...t},o.active_profile=o.active_profile||e,M(o)};var ze="https://api.ideal-postcodes.co.uk/v1",Qe=e=>{let t=[`api_key="${e.apiKey}"`];return e.userToken&&t.push(`user_token="${e.userToken}"`),t.join(" ")},Ze=(e,t,o)=>{let n=new URL(`${e}${t}`);if(o)for(let[s,r]of Object.entries(o))r!=null&&n.searchParams.set(s,String(r));return n.toString()},Z=e=>e===401?"auth_failed":e===403?"forbidden":e===404?"not_found":e===429?"rate_limited":e>=500?"server_error":"invalid_input",p=async(e,t)=>{let o=t.baseUrl??ze,n=Ze(o,e,t.query),s={Authorization:Qe(t.auth),Accept:t.accept==="csv"?"text/csv":"application/json","User-Agent":"idpc-cli"},r;t.body!==void 0&&(s["Content-Type"]="application/json",r=JSON.stringify(t.body));let i=new AbortController,a=setTimeout(()=>i.abort(),t.timeoutMs??3e4),d;try{d=await fetch(n,{method:t.method??"GET",headers:s,body:r,signal:i.signal})}catch(w){throw new u("network_error",`Request failed: ${w instanceof Error?w.message:String(w)}`)}finally{clearTimeout(a)}let g=await d.text();if(t.accept==="csv"){if(!d.ok)throw new u(Z(d.status),g||d.statusText,{status:d.status});return{status:d.status,data:g}}let y;if(g)try{y=JSON.parse(g)}catch{throw new u("server_error",`Expected JSON response, got: ${g.slice(0,200)}`)}if(!d.ok){let w=y;throw new u(Z(d.status),w?.message??`HTTP ${d.status}`,{status:d.status,api_code:w?.code})}return{status:d.status,data:y}};var et=e=>e.optsWithGlobals(),m=e=>{let t=et(e);return{globals:t,json:!!(t.json||t.quiet)}},f=(e,t={})=>{let o=X(e.apiKey,e.profile).value;if(t.requireUserToken){let n=z(e.userToken,e.profile).value;return{apiKey:o,userToken:n}}return{apiKey:o}},A=async e=>(await p(`/keys/${encodeURIComponent(e.apiKey)}`,{auth:e,method:"GET"})).data;var L=v(require("picocolors"),1);var _=()=>!!(process.stdin.isTTY&&process.stdout.isTTY),N=e=>e?!0:!process.stdout.isTTY;var c=(e,t={})=>{if(N(t.json||t.quiet)){process.stdout.write(`${JSON.stringify(e)}
4
+ `);return}if(t.human){process.stdout.write(`${t.human(e)}
5
+ `);return}process.stdout.write(`${JSON.stringify(e,null,2)}
6
+ `)},j=(e,t={})=>{N(t.json||t.quiet)?process.stdout.write(`${JSON.stringify({error:{code:e.code,message:e.message,...e.details?{details:e.details}:{}}})}
7
+ `):process.stderr.write(`${L.default.red("error")} ${L.default.gray(`[${e.code}]`)} ${e.message}
8
+ `),process.exit(1)},l=(e,t={})=>{if(e instanceof u)return j({code:e.code,message:e.message,details:e.details},t);let o=e instanceof Error?e.message:String(e);return j({code:"unexpected_error",message:o},t)};var P=v(require("@clack/prompts"),1),tt=(e="Cancelled.")=>{P.cancel(e),process.exit(1)},H=async(e,t)=>{let o=await P.password({message:e,validate:t});return P.isCancel(o)&&tt(),o};var ot=["auth_failed","forbidden","not_found"],nt=async(e,t)=>{try{return await A({apiKey:e,userToken:t})}catch(o){throw o instanceof u&&ot.includes(o.code)?new u("auth_failed",`Credentials rejected by API: ${o.message}`,o.details):o}},te=new ee.Command("login").description("Save Ideal Postcodes credentials (api_key and user_token)").option("--api-key <key>","API key to store").option("--user-token <token>","User token to store").action(async(e,t)=>{let{globals:o,json:n}=m(t),s=T(o.profile),r=e.apiKey??o.apiKey,i=e.userToken??o.userToken;try{if(!r||!i){if(!_()||n)return j({code:"invalid_input",message:"Non-interactive mode requires --api-key and --user-token."},{json:n});x.intro("Ideal Postcodes login"),x.log.info(`Find your API key at https://ideal-postcodes.co.uk/account/
9
+ User tokens are shown alongside each key and are required for /keys/* reads.`),r||(r=await H("Enter your API key:",y=>y?void 0:"API key required")),i||(i=await H("Enter your user token:",y=>y?void 0:"User token required"))}let a=!n&&_()?x.spinner():null;a?.start("Verifying credentials");let d;try{d=await nt(r,i),a?.stop("Credentials verified")}catch(y){throw a?.stop("Verification failed",1),y}let g=Q(s,{api_key:r,user_token:i});c({success:!0,profile:s,config_path:g,availability:d},{json:n}),!n&&_()&&x.outro(`Saved credentials for profile "${s}"`)}catch(a){l(a,{json:n})}});var oe=require("commander");var ne=new oe.Command("logout").description("Remove stored credentials (use --all to wipe the file)").option("--all","Remove the entire credentials file (all profiles)").action((e,t)=>{let{globals:o,json:n}=m(t),s=T(o.profile),r=e.all?D():V(s);c({success:!0,removed:r,scope:e.all?"all":s,config_path:b()},{json:n})});var re=require("commander");var se=new re.Command("whoami").description("Show resolved credentials and verify the API key").action(async(e,t)=>{let{globals:o,json:n}=m(t),s=U(o.apiKey,o.profile),r=I(o.userToken,o.profile),i={api_key:s?{source:s.source,profile:s.profile,preview:s.value.slice(0,6)+"\u2026"}:null,user_token:r?{source:r.source,profile:r.profile,preview:r.value.slice(0,6)+"\u2026"}:null};if(!s){c({...i,live:!1},{json:n});return}try{let a=await A(f(o));c({...i,live:!0,availability:a},{json:n})}catch(a){l(a,{json:n})}});var ae=new ie.Command("auth").description("Manage Ideal Postcodes credentials").addCommand(te).addCommand(ne).addCommand(se);var de=require("fs"),ce=require("commander");var rt=async()=>await new Promise((e,t)=>{let o="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",n=>{o+=n}),process.stdin.on("end",()=>e(o)),process.stdin.on("error",t)}),st=async(e,t)=>{if(t.file)return(0,de.readFileSync)(t.file,"utf-8").split(/\r?\n/).map(n=>n.trim()).filter(Boolean).map(n=>({query:n,context:t.context,tags:t.tags}));if(t.stdin)return(await rt()).split(/\r?\n/).map(n=>n.trim()).filter(Boolean).map(n=>({query:n,context:t.context,tags:t.tags}));if(!e)throw new u("missing_argument","Provide a query, --file <path>, or --stdin.");return[{query:e,context:t.context,tags:t.tags}]},me=new ce.Command("cleanse").description("Cleanse one or more addresses (POST /cleanse/addresses)").argument("[query]","Address string to cleanse").option("-f, --file <path>","Read one address per line from a file").option("--stdin","Read one address per line from stdin").option("--context <iso>","ISO country hint (e.g. GBR, USA)").option("--tags <tags>","Tags for this lookup (comma-separated)").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n),i=await st(e,t),a=[];for(let d of i){let g=await p("/cleanse/addresses",{auth:r,method:"POST",query:{context:d.context,tags:d.tags},body:{query:d.query}});a.push({query:d.query,response:g.data})}c(i.length===1?a[0]:{count:a.length,results:a},{json:s})}catch(r){l(r,{json:s})}});var le=require("commander"),k=v(require("picocolors"),1);var q="@ideal-postcodes/cli",K="0.0.0";var it=e=>{let t=[];t.push(k.default.bold(`${e.cli.name} v${e.cli.version}`)),t.push(` ${k.default.dim("node")} ${e.runtime.node} (${e.runtime.platform}/${e.runtime.arch})`),t.push(` ${k.default.dim("config")} ${e.config.path}`);let o=n=>n?`${k.default.green("\u2713")} ${n.source}${n.profile?` (${n.profile})`:""}`:k.default.gray("not set");return t.push(` ${k.default.dim("api key")} ${o(e.credentials.api_key)}`),t.push(` ${k.default.dim("token")} ${o(e.credentials.user_token)}`),e.connectivity.live===!0?t.push(` ${k.default.dim("api")} ${k.default.green("\u2713 reachable")}`):e.connectivity.live===!1?t.push(` ${k.default.dim("api")} ${k.default.red("\u2717")} ${e.connectivity.error??"unreachable"}`):t.push(` ${k.default.dim("api")} ${k.default.gray("skipped (no api key)")}`),t.join(`
10
+ `)},ue=new le.Command("doctor").description("Print environment info and verify API connectivity").action(async(e,t)=>{let{globals:o,json:n}=m(t),s=U(o.apiKey,o.profile),r=I(o.userToken,o.profile),i=null,a;if(s)try{await A({apiKey:s.value}),i=!0}catch(g){i=!1,a=g instanceof Error?g.message:String(g)}let d={cli:{name:q,version:K},runtime:{node:process.version,platform:process.platform,arch:process.arch},config:{path:b()},credentials:{api_key:s?{source:s.source,profile:s.profile}:null,user_token:r?{source:r.source,profile:r.profile}:null},connectivity:{live:i,error:a}};c(d,{json:n,human:it})});var C=v(require("@clack/prompts"),1),ge=require("commander"),S=v(require("picocolors"),1);var G=v(require("picocolors"),1),R=e=>{if(!e)return G.default.gray("no match");let t=[e.line_1,e.line_2,e.line_3].filter(n=>!!n).map(n=>` ${n}`),o=[e.post_town,e.postcode].filter(Boolean).join(" ");return o&&t.push(` ${G.default.bold(o)}`),e.country&&t.push(` ${G.default.dim(String(e.country))}`),t.join(`
11
+ `)};var at=e=>e.count===0?S.default.gray("no suggestions"):e.suggestions.map((t,o)=>` ${S.default.dim(String(o+1).padStart(2))} ${t.suggestion} ${S.default.dim(t.id)}`).join(`
12
+ `),dt=e=>e.results.map(t=>`${S.default.dim(t.suggestion.suggestion)}
13
+ ${R(t.address)}`).join(`
14
+
15
+ `),pe=async(e,t,o)=>(await p("/autocomplete/addresses",{auth:e,method:"GET",query:{query:t,country:o}})).data?.result?.hits??[],fe=async(e,t,o="gbr")=>{let n=`/autocomplete/addresses/${encodeURIComponent(t)}/${encodeURIComponent(o)}`;return(await p(n,{auth:e,method:"GET"})).data?.result?.hits?.[0]??null},ye=new ge.Command("find").description("Autocomplete addresses (GET /autocomplete/addresses). Interactive picker in TTY, JSON suggestions in non-TTY.").argument("[query]","Initial search string").option("--country <iso3>","ISO-3 country code (e.g. GBR, USA)").option("--resolve","In non-TTY: auto-resolve each suggestion's full address").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n);if(!_()||s){if(!e)throw new u("missing_argument","Non-interactive mode requires a query argument.");let y=await pe(r,e,t.country);if(t.resolve){let w=await Promise.all(y.map(async J=>({suggestion:J,address:await fe(r,J.id,t.country?.toLowerCase()??"gbr")})));c({count:w.length,results:w},{json:s,human:dt})}else c({count:y.length,suggestions:y},{json:s,human:at});return}let i=e??"";if(!i){let y=await C.text({message:"Search for an address:",placeholder:"e.g. 10 downing street"});C.isCancel(y)&&(C.cancel("Cancelled."),process.exit(1)),i=y}let a=await pe(r,i,t.country);if(a.length===0){C.log.warn("No suggestions."),c({count:0,suggestions:[]},{json:!1});return}let d=await C.select({message:"Select an address:",options:a.map(y=>({value:y.id,label:y.suggestion}))});C.isCancel(d)&&(C.cancel("Cancelled."),process.exit(1));let g=await fe(r,d,t.country?.toLowerCase()??"gbr");c(g,{json:!1,human:R})}catch(r){l(r,{json:s})}});var De=require("commander");var Ae=require("commander");var ke=require("commander");var ct=e=>e.split(",").map(t=>t.trim()).filter(Boolean),Ce=new ke.Command("create").description("Create a config (POST /keys/:key/configs)").argument("<config>","Config identifier").argument("[key]","API key (defaults to configured key)").option("--allowed-urls <csv>","Comma-separated allowed URLs").option("--json-body <json>","Raw JSON body (merged last)").action(async(e,t,o,n)=>{let{globals:s,json:r}=m(n);try{let i=f(s,{requireUserToken:!0}),a=t??i.apiKey,d={name:e};if(o.allowedUrls&&(d.allowed_urls=ct(o.allowedUrls)),o.jsonBody)try{Object.assign(d,JSON.parse(o.jsonBody))}catch{throw new u("invalid_input","--json-body must be valid JSON")}let g=await p(`/keys/${encodeURIComponent(a)}/configs`,{auth:i,method:"POST",body:d});c(g.data,{json:r})}catch(i){l(i,{json:r})}});var he=require("commander"),E=v(require("@clack/prompts"),1);var we=new he.Command("delete").description("Delete a config (DELETE /keys/:key/configs/:config)").argument("<config>","Config identifier").argument("[key]","API key (defaults to configured key)").option("-y, --yes","Skip confirmation").action(async(e,t,o,n)=>{let{globals:s,json:r}=m(n);try{let i=f(s,{requireUserToken:!0}),a=t??i.apiKey;if(!o.yes){if(!_()||r)throw new u("invalid_input","Destructive operation requires --yes in non-interactive mode.");let g=await E.confirm({message:`Delete config "${e}"?`,initialValue:!1});(E.isCancel(g)||!g)&&(E.cancel("Aborted."),process.exit(1))}let d=await p(`/keys/${encodeURIComponent(a)}/configs/${encodeURIComponent(e)}`,{auth:i,method:"DELETE"});c({success:!0,result:d.data},{json:r})}catch(i){l(i,{json:r})}});var ve=require("commander");var be=new ve.Command("get").description("Retrieve a specific config (GET /keys/:key/configs/:config)").argument("<config>","Config identifier").argument("[key]","API key (defaults to configured key)").action(async(e,t,o,n)=>{let{globals:s,json:r}=m(n);try{let i=f(s),a=t??i.apiKey,d=await p(`/keys/${encodeURIComponent(a)}/configs/${encodeURIComponent(e)}`,{auth:i,method:"GET"});c(d.data,{json:r})}catch(i){l(i,{json:r})}});var _e=require("commander");var xe=new _e.Command("list").description("List allowed-URL configs (GET /keys/:key/configs)").argument("[key]","API key (defaults to configured key)").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n,{requireUserToken:!0}),i=e??r.apiKey,a=await p(`/keys/${encodeURIComponent(i)}/configs`,{auth:r,method:"GET"});c(a.data,{json:s})}catch(r){l(r,{json:s})}});var Pe=require("commander");var mt=e=>e.split(",").map(t=>t.trim()).filter(Boolean),Te=new Pe.Command("update").description("Update a config (POST /keys/:key/configs/:config)").argument("<config>","Config identifier").argument("[key]","API key (defaults to configured key)").option("--allowed-urls <csv>","Comma-separated allowed URLs").option("--json-body <json>","Raw JSON body (merged last)").action(async(e,t,o,n)=>{let{globals:s,json:r}=m(n);try{let i=f(s,{requireUserToken:!0}),a=t??i.apiKey,d={};if(o.allowedUrls&&(d.allowed_urls=mt(o.allowedUrls)),o.jsonBody)try{Object.assign(d,JSON.parse(o.jsonBody))}catch{throw new u("invalid_input","--json-body must be valid JSON")}if(Object.keys(d).length===0)throw new u("invalid_input","Provide --allowed-urls or --json-body.");let g=await p(`/keys/${encodeURIComponent(a)}/configs/${encodeURIComponent(e)}`,{auth:i,method:"POST",body:d});c(g.data,{json:r})}catch(i){l(i,{json:r})}});var Ee=new Ae.Command("configs").description("Allowed-URL configs for a key").addCommand(xe).addCommand(be).addCommand(Ce).addCommand(Te).addCommand(we);var Oe=require("commander");var Ue=new Oe.Command("details").description("Private key details (GET /keys/:key/details) \u2014 requires user_token").argument("[key]","API key (defaults to configured key)").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n,{requireUserToken:!0}),i=e??r.apiKey,a=await p(`/keys/${encodeURIComponent(i)}/details`,{auth:r,method:"GET"});c(a.data,{json:s})}catch(r){l(r,{json:s})}});var Ie=require("commander");var Re=new Ie.Command("get").description("Public availability info for an API key (GET /keys/:key)").argument("[key]","API key to inspect (defaults to configured key)").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n),i=e??r.apiKey,a=await p(`/keys/${encodeURIComponent(i)}`,{auth:r,method:"GET"});c(a.data,{json:s})}catch(r){l(r,{json:s})}});var Se=require("commander");var $e=new Se.Command("logs").description("Paid lookup logs as CSV (GET /keys/:key/lookups)").argument("[key]","API key (defaults to configured key)").option("--start <date>","Start date").option("--end <date>","End date").option("--licensee <id>","Filter by licensee id").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n,{requireUserToken:!0}),i=e??r.apiKey,a=await p(`/keys/${encodeURIComponent(i)}/lookups`,{auth:r,method:"GET",accept:"csv",query:{start:t.start,end:t.end,licensee:t.licensee}});process.stdout.write(a.data),a.data.endsWith(`
16
+ `)||process.stdout.write(`
17
+ `)}catch(r){l(r,{json:s})}});var je=require("commander");var qe=new je.Command("update").description("Update key details (PUT /keys/:key/details) \u2014 requires user_token").argument("[key]","API key (defaults to configured key)").option("--notify-email <email>","Notification email").option("--automated-topup <bool>","Enable/disable automated topup (true|false)").option("--json-body <json>","Raw JSON body for fields not covered by flags (merged last)").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n,{requireUserToken:!0}),i=e??r.apiKey,a={};if(t.notifyEmail&&(a.notification_email=t.notifyEmail),t.automatedTopup!==void 0&&(a.automated_topup=t.automatedTopup==="true"),t.jsonBody)try{Object.assign(a,JSON.parse(t.jsonBody))}catch{throw new u("invalid_input","--json-body must be valid JSON")}if(Object.keys(a).length===0)throw new u("invalid_input","Provide at least one field to update (e.g. --notify-email or --json-body).");let d=await p(`/keys/${encodeURIComponent(i)}/details`,{auth:r,method:"PUT",body:a});c(d.data,{json:s})}catch(r){l(r,{json:s})}});var Ke=require("commander");var Ge=new Ke.Command("usage").description("Usage stats for a key (GET /keys/:key/usage)").argument("[key]","API key (defaults to configured key)").option("--start <date>","Start date (YYYY-MM-DD or ISO)").option("--end <date>","End date (YYYY-MM-DD or ISO)").option("--tags <tags>","Filter by tags (comma-separated)").option("--licensee <id>","Filter by licensee id").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n,{requireUserToken:!0}),i=e??r.apiKey,a=await p(`/keys/${encodeURIComponent(i)}/usage`,{auth:r,method:"GET",query:{start:t.start,end:t.end,tags:t.tags,licensee:t.licensee}});c(a.data,{json:s})}catch(r){l(r,{json:s})}});var Ne=new De.Command("keys").description("Manage and inspect API keys").addCommand(Re).addCommand(Ue).addCommand(qe).addCommand(Ge).addCommand($e).addCommand(Ee);var Le=require("commander");var lt=e=>R(e?.result?.hits?.[0]??null),He=new Le.Command("resolve").description("Resolve an autocomplete suggestion to a full address (GET /autocomplete/addresses/:id/:country)").argument("<id>","Suggestion id returned by `idpc find`").option("--country <iso3>","ISO-3 country code (default: gbr)","gbr").action(async(e,t,o)=>{let{globals:n,json:s}=m(o);try{let r=f(n),i=t.country.toLowerCase(),a=await p(`/autocomplete/addresses/${encodeURIComponent(e)}/${encodeURIComponent(i)}`,{auth:r,method:"GET"});c(a.data,{json:s,human:lt})}catch(r){l(r,{json:s})}});var ut=new Je.Command().name("idpc").description("Ideal Postcodes CLI \u2014 key management, address cleanse, autocomplete").configureOutput({writeErr:e=>{process.stderr.write(e.replace(/^error:/,()=>Fe.default.red("error:")))}}).version(`${q} v${K}`,"-v, --version").option("--api-key <key>","Ideal Postcodes API key").option("--user-token <token>","Ideal Postcodes user token").option("-p, --profile <name>","Profile to use").option("--json","Force JSON output").option("-q, --quiet","Suppress status output (implies --json)").option("--base-url <url>","Override API base URL").addCommand(ae).addCommand(Ne).addCommand(me).addCommand(ye).addCommand(He).addCommand(ue);ut.parseAsync(process.argv).catch(e=>{l(e)});
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@ideal-postcodes/cli",
3
+ "description": "Ideal Postcodes CLI — idpc",
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "bin": {
7
+ "idpc": "./dist/cli.cjs"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "skills"
12
+ ],
13
+ "scripts": {
14
+ "check-types": "tsgo --noEmit",
15
+ "test": "vitest run",
16
+ "test:watch": "vitest --watch",
17
+ "lint": "eslint src/",
18
+ "build": "tsup",
19
+ "clean": "rm -rf dist",
20
+ "dev": "tsx src/cli.ts",
21
+ "prepublishOnly": "pnpm test && pnpm build"
22
+ },
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "author": {
27
+ "name": "Ideal Postcodes",
28
+ "email": "support@ideal-postcodes.co.uk",
29
+ "url": "https://ideal-postcodes.co.uk"
30
+ },
31
+ "license": "SEE LICENSE IN LICENSE",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "homepage": "https://docs.ideal-postcodes.co.uk",
36
+ "bugs": {
37
+ "url": "https://github.com/ideal-postcodes/feedback/issues",
38
+ "email": "support@ideal-postcodes.co.uk"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/ideal-postcodes/feedback.git"
43
+ },
44
+ "keywords": [
45
+ "cli",
46
+ "ideal-postcodes",
47
+ "address",
48
+ "postcode",
49
+ "cleanse",
50
+ "autocomplete",
51
+ "llm",
52
+ "agent"
53
+ ],
54
+ "devDependencies": {
55
+ "@types/node": "catalog:",
56
+ "tsup": "catalog:",
57
+ "tsx": "~4.21.0",
58
+ "typescript": "catalog:",
59
+ "vitest": "catalog:"
60
+ },
61
+ "dependencies": {
62
+ "@clack/prompts": "~0.11.0",
63
+ "commander": "~14.0.0",
64
+ "picocolors": "~1.1.1"
65
+ }
66
+ }
@@ -0,0 +1,118 @@
1
+ ---
2
+ name: idpc-cli
3
+ description: >
4
+ Drive api.ideal-postcodes.co.uk from the terminal — manage API keys
5
+ (balance, usage, allowed-URL configs, lookup logs), cleanse messy addresses,
6
+ and resolve specific addresses from partial queries via the `idpc` CLI.
7
+ Use when the user wants to inspect or update an Ideal Postcodes account,
8
+ cleanse addresses in bulk, or pin down a specific address from a partial
9
+ query. Always load this skill before running `idpc` — it defines the
10
+ non-interactive flag contract and output shape that keep agent runs
11
+ deterministic.
12
+ license: SEE LICENSE IN LICENSE
13
+ metadata:
14
+ author: ideal-postcodes
15
+ source: https://github.com/ideal-postcodes/atlas/tree/main/packages/cli-ideal
16
+ envVars:
17
+ - name: IDPC_API_KEY
18
+ required: true
19
+ description: Ideal Postcodes API key
20
+ - name: IDPC_USER_TOKEN
21
+ required: false
22
+ description: Required for private key endpoints (details, usage, logs, configs)
23
+ - name: IDPC_PROFILE
24
+ required: false
25
+ description: Named profile for multi-account setups
26
+ references:
27
+ - auth.md
28
+ - keys.md
29
+ - cleanse.md
30
+ - find.md
31
+ ---
32
+
33
+ # Ideal Postcodes CLI (`idpc`)
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ npm install -g @ideal-postcodes/cli
39
+ idpc --version
40
+ ```
41
+
42
+ ## Agent Protocol
43
+
44
+ The CLI auto-detects non-TTY environments and emits JSON — no `--json` flag needed when piping or running headless.
45
+
46
+ **Rules for agents:**
47
+
48
+ - Supply ALL required flags. The CLI will NOT prompt when stdin is not a TTY.
49
+ - `-q / --quiet` suppresses any status output and implies `--json`.
50
+ - Exit `0` = success, `1` = error.
51
+ - Both success and error JSON go to **stdout** — parse it uniformly, then check for an `error` key and the exit code:
52
+ ```json
53
+ {"error":{"code":"...","message":"...","details":{...}}}
54
+ ```
55
+ - Destructive commands (e.g. `keys configs delete`) require `--yes` in non-TTY.
56
+ - Use env vars or flags. Never rely on `idpc auth login` from an agent.
57
+
58
+ ## Authentication
59
+
60
+ Two credentials: `api_key` (required) and `user_token` (required for `/keys/*` reads, configs, updates). Resolution precedence — per credential:
61
+
62
+ | Priority | Source |
63
+ |---|---|
64
+ | 1 (highest) | `--api-key <k>` / `--user-token <t>` |
65
+ | 2 | `IDPC_API_KEY` / `IDPC_USER_TOKEN` env var |
66
+ | 3 (lowest) | Active profile in `~/.config/ideal-postcodes/credentials.json` |
67
+
68
+ Missing api_key → error code `missing_api_key`. Missing user_token on a command that needs it → `missing_user_token`.
69
+
70
+ ## Global Flags
71
+
72
+ | Flag | Description |
73
+ |------|-------------|
74
+ | `--api-key <k>` | Override API key for this invocation |
75
+ | `--user-token <t>` | Override user token |
76
+ | `-p, --profile <name>` | Select a stored profile |
77
+ | `--json` | Force JSON (auto in non-TTY) |
78
+ | `-q, --quiet` | Suppress status, implies `--json` |
79
+ | `--base-url <url>` | Override API base (diagnostics only) |
80
+
81
+ ## Available Commands
82
+
83
+ | Group | Subcommands |
84
+ |---|---|
85
+ | `idpc auth` | `login`, `logout`, `whoami` |
86
+ | `idpc keys` | `get`, `details`, `update`, `usage`, `logs`, `configs {list,get,create,update,delete}` |
87
+ | `idpc cleanse` | Cleanse one address, a file, or stdin |
88
+ | `idpc find` / `resolve` | Autocomplete then resolve a suggestion id to a full address (paired; see `find.md`) |
89
+ | `idpc doctor` | Env + connectivity check |
90
+
91
+ Read the matching reference file for flags and example output.
92
+
93
+ ## Common Pitfalls
94
+
95
+ - **`user_token` is separate from `api_key`.** `keys details`, `keys usage`, `keys logs`, `keys update`, and all `configs` writes require both.
96
+ - **`cleanse` costs paid lookups.** Public test key `iddqd` will return `auth_failed` on `/cleanse/addresses`.
97
+ - **`find` without a query in non-TTY errors.** Always pass a query when scripting.
98
+ - **`keys logs` emits raw CSV**, not JSON. Redirect to a file or pipe into your CSV tooling.
99
+ - **Credentials file is `0600`.** If your umask is unusual, `idpc auth login` may fail with `write_failed`.
100
+
101
+ ## Quick Examples
102
+
103
+ ```bash
104
+ # Cleanse one address (JSON to stdout)
105
+ idpc cleanse "10 downing street, london"
106
+
107
+ # Batch cleanse
108
+ cat addresses.txt | idpc cleanse --stdin
109
+
110
+ # Find a specific address and resolve it
111
+ idpc find "10 downing" --resolve
112
+
113
+ # Inspect a key
114
+ idpc keys details
115
+
116
+ # Add an allowed URL
117
+ idpc keys configs update web --allowed-urls https://example.com,https://www.example.com
118
+ ```
@@ -0,0 +1,56 @@
1
+ # `idpc auth`
2
+
3
+ Manage stored credentials at `~/.config/ideal-postcodes/credentials.json` (or `%APPDATA%\ideal-postcodes\credentials.json` on Windows, or `$XDG_CONFIG_HOME/ideal-postcodes/...` if set). File is written with mode `0600`.
4
+
5
+ ## `idpc auth login`
6
+
7
+ Store an `api_key` and `user_token` for later reuse.
8
+
9
+ | Flag | Description |
10
+ |---|---|
11
+ | `--api-key <k>` | API key to store (required in non-interactive mode) |
12
+ | `--user-token <t>` | User token to store (required in non-interactive mode) |
13
+
14
+ Non-interactive (no TTY or `--json`): both flags required; missing either returns `invalid_input`.
15
+
16
+ Interactive: prompts for both via masked password input.
17
+
18
+ ### Output
19
+
20
+ ```json
21
+ { "success": true, "profile": "default", "config_path": "/home/you/.config/ideal-postcodes/credentials.json" }
22
+ ```
23
+
24
+ ### Error codes
25
+
26
+ - `invalid_input` — non-interactive mode missing `--api-key` or `--user-token`
27
+ - `write_failed` — unable to write credentials file
28
+
29
+ ## `idpc auth logout`
30
+
31
+ Remove the credentials file.
32
+
33
+ ### Output
34
+
35
+ ```json
36
+ { "success": true, "removed": true, "config_path": "..." }
37
+ ```
38
+
39
+ `removed: false` means there was no file to remove — not an error.
40
+
41
+ ## `idpc auth whoami`
42
+
43
+ Show where each credential was resolved from and call `GET /keys/{key}` to verify the api_key is live.
44
+
45
+ ### Output
46
+
47
+ ```json
48
+ {
49
+ "api_key": { "source": "env", "preview": "ak_xxx…" },
50
+ "user_token": { "source": "config", "profile": "default", "preview": "ut_xxx…" },
51
+ "live": true,
52
+ "availability": { /* GET /keys/{key} response */ }
53
+ }
54
+ ```
55
+
56
+ `source` is `flag`, `env`, or `config`.
@@ -0,0 +1,62 @@
1
+ # `idpc cleanse`
2
+
3
+ Clean messy address strings — `POST /cleanse/addresses`. Requires `api_key`. Each input counts as a paid lookup.
4
+
5
+ ## Usage
6
+
7
+ ```
8
+ idpc cleanse [options] [query]
9
+ idpc cleanse --file input.txt
10
+ idpc cleanse --stdin
11
+ ```
12
+
13
+ | Flag | Description |
14
+ |---|---|
15
+ | `-f, --file <path>` | Read one address per line |
16
+ | `--stdin` | Read one address per line from stdin |
17
+ | `--context <iso3>` | ISO-3 country hint (GBR, USA, …) |
18
+ | `--tags <csv>` | Tags recorded with the lookup |
19
+
20
+ Exactly one of: `[query]`, `--file`, `--stdin`.
21
+
22
+ ## Output
23
+
24
+ **Single input:**
25
+
26
+ ```json
27
+ {
28
+ "query": "10 downing street",
29
+ "response": { /* IDPC cleanse response */ }
30
+ }
31
+ ```
32
+
33
+ **Multiple inputs** (file or stdin):
34
+
35
+ ```json
36
+ {
37
+ "count": 3,
38
+ "results": [
39
+ { "query": "...", "response": { ... } },
40
+ { "query": "...", "response": { ... } },
41
+ { "query": "...", "response": { ... } }
42
+ ]
43
+ }
44
+ ```
45
+
46
+ Each `response` includes the IDPC `result` array and the confidence score. There is no absolute confidence threshold — decide per your dataset.
47
+
48
+ ## Agent patterns
49
+
50
+ ```bash
51
+ # Single
52
+ idpc cleanse "10 downing street, london" | jq .response.result[0]
53
+
54
+ # Batch
55
+ cat messy.txt | idpc cleanse --stdin > clean.json
56
+ ```
57
+
58
+ ## Error codes
59
+
60
+ - `auth_failed` — invalid key, or key lacks paid cleanse permission
61
+ - `rate_limited` — 30 req/sec per IP; back off
62
+ - `invalid_input` — malformed body or missing query
@@ -0,0 +1,59 @@
1
+ # `idpc find` & `idpc resolve`
2
+
3
+ Address autocomplete — two-step by design. Useful when you need to pin a specific address from partial info before using it downstream.
4
+
5
+ ## `idpc find [query]`
6
+
7
+ `GET /autocomplete/addresses`.
8
+
9
+ | Flag | Description |
10
+ |---|---|
11
+ | `--country <iso3>` | Filter by ISO-3 (e.g. GBR, USA) |
12
+ | `--resolve` | In non-TTY, auto-call resolve on each suggestion |
13
+
14
+ **TTY (human):** prompts for input if no query, shows a `select` picker, auto-resolves the chosen suggestion, prints the full address.
15
+
16
+ **Non-TTY (agent):** query is required. Emits suggestions as JSON:
17
+
18
+ ```json
19
+ {
20
+ "count": 2,
21
+ "suggestions": [
22
+ { "id": "ABC123", "suggestion": "10 Downing Street, London, SW1A" },
23
+ { "id": "DEF456", "suggestion": "11 Downing Street, London, SW1A" }
24
+ ]
25
+ }
26
+ ```
27
+
28
+ Adding `--resolve` pairs each suggestion with its full address in one call:
29
+
30
+ ```json
31
+ {
32
+ "count": 2,
33
+ "results": [
34
+ { "suggestion": { ... }, "address": { /* full */ } },
35
+ { "suggestion": { ... }, "address": { /* full */ } }
36
+ ]
37
+ }
38
+ ```
39
+
40
+ ## `idpc resolve <id>`
41
+
42
+ `GET /autocomplete/addresses/{id}/{country}`.
43
+
44
+ | Flag | Description |
45
+ |---|---|
46
+ | `--country <iso3>` | ISO-3 country code (default: `gbr`) |
47
+
48
+ Returns the resolved address object.
49
+
50
+ ## Agent pattern
51
+
52
+ ```bash
53
+ # Pick the top hit and resolve
54
+ ID=$(idpc find "10 downing" | jq -r '.suggestions[0].id')
55
+ idpc resolve "$ID"
56
+
57
+ # Or in one shot
58
+ idpc find "10 downing" --resolve | jq '.results[0].address'
59
+ ```
@@ -0,0 +1,91 @@
1
+ # `idpc keys`
2
+
3
+ Inspect and manage API keys.
4
+
5
+ Every subcommand accepts `[key]` as an optional first positional. If omitted, the resolved api_key is used — so `idpc keys details` and `idpc keys details ak_xxx` behave the same when your own key is configured.
6
+
7
+ ## `idpc keys get [key]`
8
+
9
+ Public availability info — `GET /keys/{key}`. No user_token required.
10
+
11
+ ## `idpc keys details [key]`
12
+
13
+ Private key details — `GET /keys/{key}/details`. **Requires user_token.**
14
+
15
+ ## `idpc keys update [key]`
16
+
17
+ Update key details — `PUT /keys/{key}/details`. **Requires user_token.**
18
+
19
+ | Flag | Description |
20
+ |---|---|
21
+ | `--notify-email <email>` | Set the notification email |
22
+ | `--automated-topup <bool>` | `true` or `false` |
23
+ | `--json-body <json>` | Raw JSON merged last — use for fields not covered above |
24
+
25
+ Must provide at least one field.
26
+
27
+ ## `idpc keys usage [key]`
28
+
29
+ Lookup counts over a date range — `GET /keys/{key}/usage`. **Requires user_token.**
30
+
31
+ | Flag | Description |
32
+ |---|---|
33
+ | `--start <date>` | Start date (YYYY-MM-DD or ISO) |
34
+ | `--end <date>` | End date |
35
+ | `--tags <csv>` | Comma-separated tag filter |
36
+ | `--licensee <id>` | Filter by licensee id |
37
+
38
+ ## `idpc keys logs [key]`
39
+
40
+ Paid lookup logs — `GET /keys/{key}/lookups`. Emits **raw CSV to stdout**. **Requires user_token.**
41
+
42
+ | Flag | Description |
43
+ |---|---|
44
+ | `--start <date>` | Start date |
45
+ | `--end <date>` | End date |
46
+ | `--licensee <id>` | Filter by licensee id |
47
+
48
+ Example:
49
+ ```bash
50
+ idpc keys logs --start 2026-01-01 --end 2026-01-31 > lookups.csv
51
+ ```
52
+
53
+ ## `idpc keys configs` — allowed-URL configs
54
+
55
+ All subcommands **require user_token** (except `get`).
56
+
57
+ ### `list [key]`
58
+
59
+ `GET /keys/{key}/configs` — list all configs.
60
+
61
+ ### `get <config> [key]`
62
+
63
+ `GET /keys/{key}/configs/{config}` — retrieve one.
64
+
65
+ ### `create <config> [key]`
66
+
67
+ `POST /keys/{key}/configs` — create a new config.
68
+
69
+ | Flag | Description |
70
+ |---|---|
71
+ | `--allowed-urls <csv>` | Comma-separated URLs |
72
+ | `--json-body <json>` | Raw JSON merged into body |
73
+
74
+ ### `update <config> [key]`
75
+
76
+ `POST /keys/{key}/configs/{config}` — update in place.
77
+
78
+ | Flag | Description |
79
+ |---|---|
80
+ | `--allowed-urls <csv>` | Replace allowed URLs |
81
+ | `--json-body <json>` | Raw JSON merged |
82
+
83
+ Must pass at least one.
84
+
85
+ ### `delete <config> [key]`
86
+
87
+ `DELETE /keys/{key}/configs/{config}`. Requires `--yes` in non-TTY.
88
+
89
+ | Flag | Description |
90
+ |---|---|
91
+ | `-y, --yes` | Skip confirmation |