@ideal-postcodes/cli 1.0.1 → 1.0.2

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/README.md CHANGED
@@ -2,78 +2,19 @@
2
2
 
3
3
  The official CLI for [Ideal Postcodes](https://ideal-postcodes.co.uk) — `idpc`.
4
4
 
5
- Built for LLM agents (Claude Code, Cursor, Codex) and CI/CD pipelines; usable from a terminal too.
6
-
7
- ## Install
5
+ Manage API keys, cleanse addresses, validate emails and phone numbers, and resolve addresses from partial queries. Built for LLM agents (Claude Code, Cursor, Codex) and CI/CD pipelines; usable from a terminal too.
8
6
 
9
7
  ```bash
10
8
  npm install -g @ideal-postcodes/cli
11
9
  idpc --version
12
10
  ```
13
11
 
14
- ## Authenticate
12
+ ## Documentation
15
13
 
16
- Two credentials — `api_key` (public) and `user_token` (private; needed for key reads, usage, logs, and configs).
14
+ Full documentation — authentication, every command, flags, output shapes, and the agent protocol — lives at **[docs.ideal-postcodes.co.uk/docs/cli](https://docs.ideal-postcodes.co.uk/docs/cli)**.
17
15
 
18
16
  ```bash
19
17
  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
18
  idpc cleanse "10 downing street, london"
32
-
33
- # Batch cleanse from a file
34
- cat addresses.txt | idpc cleanse --stdin > cleaned.json
35
-
36
- # Validate an email or phone number
37
- idpc email "support@example.com"
38
- idpc phone "+442071128019" --carrier
39
-
40
- # Batch validate from stdin to a CSV
41
- cat emails.txt | idpc email --stdin > emails.csv
42
-
43
- # Autocomplete then resolve
44
- ID=$(idpc find "10 downing" | jq -r '.suggestions[0].id')
45
- idpc resolve "$ID"
46
-
47
- # Manage allowed URLs
48
- idpc keys configs create web --allowed-urls https://example.com,https://www.example.com
49
-
50
- # Diagnose your setup
51
- idpc doctor
19
+ idpc <command> --help
52
20
  ```
53
-
54
- ## Agent protocol
55
-
56
- - Non-TTY (pipe, CI, agent run): output is always JSON; no prompts, no spinners.
57
- - 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":"..."}}`.
58
- - Destructive commands require `--yes` in non-TTY.
59
-
60
- The bundled [`skills/ideal-postcodes-cli/`](./skills/ideal-postcodes-cli/SKILL.md) teaches agents the flag contract and common gotchas.
61
-
62
- ## Commands
63
-
64
- | Group | Subcommands |
65
- |---|---|
66
- | `idpc auth` | `login`, `logout`, `whoami` |
67
- | `idpc keys` | `get`, `details`, `update`, `usage`, `logs`, `configs {list,get,create,update,delete}` |
68
- | `idpc cleanse` | Cleanse one address, a file, or stdin |
69
- | `idpc email` | Validate one email, a file, or stdin |
70
- | `idpc phone` | Validate one phone number, a file, or stdin |
71
- | `idpc find` | Autocomplete (interactive in TTY, JSON in non-TTY) |
72
- | `idpc resolve` | Resolve a suggestion id to a full address |
73
- | `idpc doctor` | Env + connectivity check |
74
-
75
- Run `idpc <command> --help` for full flags.
76
-
77
- ## Source
78
-
79
- Built in the [atlas monorepo](https://github.com/ideal-postcodes/atlas/tree/main/packages/cli-ideal).
package/dist/cli.cjs CHANGED
@@ -1,25 +1,18 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var xt=Object.create;var se=Object.defineProperty;var Et=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var At=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of St(t))!Tt.call(e,r)&&r!==o&&se(e,r,{get:()=>t[r],enumerable:!(n=Et(t,r))||n.enumerable});return e};var x=(e,t,o)=>(o=e!=null?xt(Rt(e)):{},At(t||!e||!e.__esModule?se(o,"default",{value:e,enumerable:!0}):o,e));var bt=require("commander"),vt=x(require("picocolors"),1);var ve=require("commander");var T=x(require("@clack/prompts"),1),fe=require("commander");var b=require("fs"),ie=require("os"),L=require("path");var c=class extends Error{constructor(o,n,r){super(n);this.code=o;this.details=r;this.name="CliError"}};var ae=()=>process.env.IDPC_CONFIG_DIR?process.env.IDPC_CONFIG_DIR:process.env.XDG_CONFIG_HOME?(0,L.join)(process.env.XDG_CONFIG_HOME,"ideal-postcodes"):process.platform==="win32"&&process.env.APPDATA?(0,L.join)(process.env.APPDATA,"ideal-postcodes"):(0,L.join)((0,ie.homedir)(),".config","ideal-postcodes"),S=()=>(0,L.join)(ae(),"credentials.json"),V=()=>{try{let e=(0,b.readFileSync)(S(),"utf-8"),t=JSON.parse(e);return!t.api_key&&!t.user_token?null:{...t.api_key?{api_key:t.api_key}:{},...t.user_token?{user_token:t.user_token}:{}}}catch{return null}},Pt=e=>{let t=ae();(0,b.mkdirSync)(t,{recursive:!0,mode:448});let o=S();try{(0,b.writeFileSync)(o,`${JSON.stringify(e,null,2)}
3
- `,{mode:384}),(0,b.chmodSync)(o,384)}catch(n){throw new c("write_failed",`Failed to write credentials file at ${o}: ${n instanceof Error?n.message:String(n)}`)}return o},de=()=>{try{return(0,b.rmSync)(S()),!0}catch{return!1}},G=e=>{if(e)return{value:e,source:"flag"};if(process.env.IDPC_API_KEY)return{value:process.env.IDPC_API_KEY,source:"env"};let t=V()?.api_key;return t?{value:t,source:"config"}:null},A=e=>{if(e)return{value:e,source:"flag"};if(process.env.IDPC_USER_TOKEN)return{value:process.env.IDPC_USER_TOKEN,source:"env"};let t=V()?.user_token;return t?{value:t,source:"config"}:null},ce=e=>{let t=G(e);if(!t)throw new c("missing_api_key","No API key found. Pass --api-key, set IDPC_API_KEY, or run `idpc auth login`.");return t},le=e=>{let t=A(e);if(!t)throw new c("missing_user_token","This command requires a user token. Pass --user-token, set IDPC_USER_TOKEN, or run `idpc auth login`.");return t},M=e=>{let t=V()??{};return Pt({...t,...e})};var W="https://api.ideal-postcodes.co.uk/v1",Ot=e=>{let t=[`api_key="${e.apiKey}"`];return e.userToken&&t.push(`user_token="${e.userToken}"`),t.join(" ")},Ut=(e,t,o)=>{let n=new URL(`${e}${t}`);if(o)for(let[r,s]of Object.entries(o))s!=null&&n.searchParams.set(r,String(s));return n.toString()},ue=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??W,n=Ut(o,e,t.query),r={Authorization:Ot(t.auth),Accept:t.accept==="csv"?"text/csv":"application/json","User-Agent":"idpc-cli"},s;t.body!==void 0&&(r["Content-Type"]="application/json",s=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:r,body:s,signal:i.signal})}catch(h){throw new c("network_error",`Request failed: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(a)}let f=await d.text();if(t.accept==="csv"){if(!d.ok)throw new c(ue(d.status),f||d.statusText,{status:d.status});return{status:d.status,data:f}}let w;if(f)try{w=JSON.parse(f)}catch{throw new c("server_error",`Expected JSON response, got: ${f.slice(0,200)}`)}if(!d.ok){let h=w;throw new c(ue(d.status),h?.message??`HTTP ${d.status}`,{status:d.status,api_code:h?.code})}return{status:d.status,data:w}};var $t=e=>e.optsWithGlobals(),l=e=>{let t=$t(e);return{globals:t,json:!!(t.json||t.quiet)}},g=(e,{includeUserToken:t=!0,requireUserToken:o=!1}={})=>{let n=ce(e.apiKey).value;if(!t)return{apiKey:n};if(o)return{apiKey:n,userToken:le(e.userToken).value};let r=A(e.userToken)?.value;return r?{apiKey:n,userToken:r}:{apiKey:n}},O=async e=>(await p(`/keys/${encodeURIComponent(e.apiKey)}`,{auth:e,method:"GET"})).data.result,me=async e=>(await p(`/keys/${encodeURIComponent(e.apiKey)}/details`,{auth:e,method:"GET"})).data.result;var X=x(require("picocolors"),1);var R=()=>!!(process.stdin.isTTY&&process.stdout.isTTY),Q=e=>e?!0:!process.stdout.isTTY;var m=(e,t={})=>{if(Q(t.json||t.quiet)){process.stdout.write(`${JSON.stringify(e)}
2
+ "use strict";var gt=Object.create;var ne=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var kt=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of yt(t))!Ct.call(e,r)&&r!==o&&ne(e,r,{get:()=>t[r],enumerable:!(n=ft(t,r))||n.enumerable});return e};var b=(e,t,o)=>(o=e!=null?gt(ht(e)):{},kt(t||!e||!e.__esModule?ne(o,"default",{value:e,enumerable:!0}):o,e));var nt=require("commander"),rt=b(require("picocolors"),1);var me=require("commander");var x=b(require("@clack/prompts"),1),ie=require("commander");var _=require("fs"),re=require("os"),q=require("path");var p=class extends Error{constructor(o,n,r){super(n);this.code=o;this.details=r;this.name="CliError"}};var G=e=>{let t=()=>process.env[e.env.configDir]?process.env[e.env.configDir]:process.env.XDG_CONFIG_HOME?(0,q.join)(process.env.XDG_CONFIG_HOME,e.configDirName):process.platform==="win32"&&process.env.APPDATA?(0,q.join)(process.env.APPDATA,e.configDirName):(0,q.join)((0,re.homedir)(),".config",e.configDirName),o=()=>(0,q.join)(t(),"credentials.json"),n=()=>{try{let C=(0,_.readFileSync)(o(),"utf-8"),h=JSON.parse(C);return!h.api_key&&!h.user_token?null:{...h.api_key?{api_key:h.api_key}:{},...h.user_token?{user_token:h.user_token}:{}}}catch{return null}},r=C=>{let h=t();(0,_.mkdirSync)(h,{recursive:!0,mode:448});let w=o();try{(0,_.writeFileSync)(w,`${JSON.stringify(C,null,2)}
3
+ `,{mode:384}),(0,_.chmodSync)(w,384)}catch(v){throw new p("write_failed",`Failed to write credentials file at ${w}: ${v instanceof Error?v.message:String(v)}`)}return w},a=()=>{try{return(0,_.rmSync)(o()),!0}catch{return!1}},s=C=>{if(C)return{value:C,source:"flag"};let h=process.env[e.env.apiKey];if(h)return{value:h,source:"env"};let w=n()?.api_key;return w?{value:w,source:"config"}:null},i=C=>{if(C)return{value:C,source:"flag"};let h=process.env[e.env.userToken];if(h)return{value:h,source:"env"};let w=n()?.user_token;return w?{value:w,source:"config"}:null};return{getConfigDir:t,getCredentialsPath:o,readCredentials:n,writeCredentials:r,clearCredentials:a,resolveApiKey:s,resolveUserToken:i,requireApiKey:C=>{let h=s(C);if(!h)throw new p("missing_api_key",`No API key found. Pass --api-key, set ${e.env.apiKey}, or run \`${e.binName} auth login\`.`);return h},requireUserToken:C=>{let h=i(C);if(!h)throw new p("missing_user_token",`This command requires a user token. Pass --user-token, set ${e.env.userToken}, or run \`${e.binName} auth login\`.`);return h},upsertCredentials:C=>{let h=n()??{};return r({...h,...C})}}};var wt=e=>{let t=[`api_key="${e.apiKey}"`];return e.userToken&&t.push(`user_token="${e.userToken}"`),t.join(" ")},_t=(e,t,o)=>{let n=new URL(`${e}${t}`);if(o)for(let[r,a]of Object.entries(o))a!=null&&n.searchParams.set(r,String(a));return n.toString()},se=e=>e===401?"auth_failed":e===403?"forbidden":e===404?"not_found":e===429?"rate_limited":e>=500?"server_error":"invalid_input",L=async(e,t)=>{let o=_t(t.baseUrl,e,t.query),n={Authorization:wt(t.auth),Accept:t.accept==="csv"?"text/csv":"application/json","User-Agent":t.userAgent},r;t.body!==void 0&&(n["Content-Type"]="application/json",r=JSON.stringify(t.body));let a=new AbortController,s=setTimeout(()=>a.abort(),t.timeoutMs??3e4),i;try{i=await fetch(o,{method:t.method??"GET",headers:n,body:r,signal:a.signal})}catch(y){throw new p("network_error",`Request failed: ${y instanceof Error?y.message:String(y)}`)}finally{clearTimeout(s)}let c=await i.text();if(t.accept==="csv"){if(!i.ok)throw new p(se(i.status),c||i.statusText,{status:i.status});return{status:i.status,data:c}}let d;if(c)try{d=JSON.parse(c)}catch{throw new p("server_error",`Expected JSON response, got: ${c.slice(0,200)}`)}if(!i.ok){let y=d;throw new p(se(i.status),y?.message??`HTTP ${i.status}`,{status:i.status,api_code:y?.code})}return{status:i.status,data:d}};var M=e=>({brand:e,cfg:G(e)}),bt=e=>e.optsWithGlobals(),l=e=>{let t=bt(e);return{globals:t,json:!!(t.json||t.quiet)}},g=(e,t,{includeUserToken:o=!0,requireUserToken:n=!1}={})=>{let r=e.cfg.requireApiKey(t.apiKey).value;if(!o)return{apiKey:r};if(n)return{apiKey:r,userToken:e.cfg.requireUserToken(t.userToken).value};let a=e.cfg.resolveUserToken(t.userToken)?.value;return a?{apiKey:r,userToken:a}:{apiKey:r}},f=(e,t,o,n)=>L(o,{...n,baseUrl:t.baseUrl??e.brand.baseUrl,userAgent:e.brand.userAgent}),S=async(e,t,o)=>(await f(e,t,`/keys/${encodeURIComponent(o.apiKey)}`,{auth:o,method:"GET"})).data.result,B=async(e,t,o)=>(await f(e,t,`/keys/${encodeURIComponent(o.apiKey)}/details`,{auth:o,method:"GET"})).data.result;var H=b(require("picocolors"),1);var A=()=>!!(process.stdin.isTTY&&process.stdout.isTTY),F=e=>e?!0:!process.stdout.isTTY;var m=(e,t={})=>{if(F(t.json||t.quiet)){process.stdout.write(`${JSON.stringify(e)}
4
4
  `);return}if(t.human){process.stdout.write(`${t.human(e)}
5
5
  `);return}process.stdout.write(`${JSON.stringify(e,null,2)}
6
- `)},U=(e,t={})=>{Q(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(`${X.default.red("error")} ${X.default.gray(`[${e.code}]`)} ${e.message}
8
- `),process.exit(t.exitCode??1)},u=(e,t={})=>{if(e instanceof c)return U({code:e.code,message:e.message,details:e.details},t);let o=e instanceof Error?e.message:String(e);return U({code:"unexpected_error",message:o},t)};var E=x(require("@clack/prompts"),1),pe=(e="Cancelled.")=>{E.cancel(e),process.exit(1)},z=async(e,t)=>{let o=await E.password({message:e,validate:t});return E.isCancel(o)&&pe(),o},ge=async(e,t)=>{let o=await E.text({message:e,placeholder:t});return E.isCancel(o)&&pe(),o};var It=["auth_failed","forbidden","not_found"],qt=async(e,t)=>{try{let{available:o}=await O({apiKey:e,userToken:t});return o}catch(o){throw o instanceof c&&It.includes(o.code)?new c("auth_failed",`Credentials rejected by API: ${o.message}`,o.details):o}},ye=new fe.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}=l(t),r=e.apiKey??o.apiKey,s=e.userToken??o.userToken;try{if(!r||!s)if(!R()||n){if(!r)return U({code:"invalid_input",message:"Non-interactive mode requires --api-key."},{json:n})}else T.intro("Ideal Postcodes login"),T.log.info(`Find your API key at https://ideal-postcodes.co.uk/account/
9
- User tokens are shown alongside each key and unlock /keys/* reads \u2014 optional, press enter to skip.`),r||(r=await z("Enter your API key:",f=>f?void 0:"API key required")),s||(s=await z("Enter your user token (optional):")||void 0);let i=!n&&R()?T.spinner():null;i?.start("Verifying credentials");let a;try{a=await qt(r,s),i?.stop("Credentials verified")}catch(f){throw i?.stop("Verification failed",1),f}let d=M({api_key:r,...s?{user_token:s}:{}});m({success:!0,config_path:d,available:a},{json:n}),!n&&R()&&T.outro("Saved credentials.")}catch(i){u(i,{json:n})}});var he=require("commander");var ke=new he.Command("logout").description("Remove stored credentials").action((e,t)=>{let{json:o}=l(t),n=de();m({success:!0,removed:n,config_path:S()},{json:o})});var $=x(require("@clack/prompts"),1),we=require("commander");var Dt=3e3,jt=1800*1e3,Kt=e=>{try{return JSON.parse(e)}catch{return}},Nt=async(e,t)=>{let o;try{o=await fetch(`${e}/signup-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":"idpc-cli"},body:JSON.stringify(t)})}catch(r){throw new c("network_error",`Signup request failed: ${r instanceof Error?r.message:String(r)}`)}let n=await o.text();if(o.status===429){let r=o.headers.get("Retry-After")??void 0;throw new c("rate_limited",r?`Signup rate-limited; retry after ${r}s.`:"Signup rate-limited.",{status:429,retry_after:r})}if(o.status===400){let r=Kt(n);throw new c("invalid_input",r?.message??"Invalid signup request.",{status:400})}if(!o.ok)throw new c("server_error",`Unexpected HTTP ${o.status}: ${n.slice(0,200)}`,{status:o.status});return JSON.parse(n)},Lt=async(e,t)=>{let o;try{o=await fetch(`${e}/signup-tokens/${encodeURIComponent(t)}`,{headers:{Accept:"application/json","User-Agent":"idpc-cli"}})}catch(r){throw new c("network_error",`Poll request failed: ${r instanceof Error?r.message:String(r)}`)}if(o.status===202)return{status:"pending"};if(o.status===410)return{status:"expired"};if(o.status===200)return{status:"ready",data:await o.json()};let n=await o.text();throw new c("server_error",`Unexpected HTTP ${o.status} while polling: ${n.slice(0,200)}`,{status:o.status})},P=(e,t)=>{if(!t||!t.trim())throw new c("invalid_input",`Missing required field: ${e}.`);return t.trim()},Gt=async(e,t)=>{let o=async(w,h,k,C)=>{if(k&&k.trim())return k.trim();if(!t)throw new c("invalid_input",`Non-interactive mode requires ${w}.`);return ge(h,C)};t&&$.intro("Ideal Postcodes signup");let n=await o("--email","Email address",e.email,"you@example.com"),r=await o("--name","Your full name",e.name),s=await o("--org-name","Organisation name",e.orgName),i=await o("--org-address-line-one","Organisation address line 1",e.orgAddressLineOne),a=await o("--org-post-town","Organisation post town",e.orgPostTown),d=await o("--org-postcode","Organisation postcode",e.orgPostcode),f=await o("--org-country-code","Organisation country code (ISO alpha-2)",e.orgCountryCode,"GB");return{email:P("email",n),name:P("name",r),org_name:P("org_name",s),org_address_line_one:P("org_address_line_one",i),org_address_line_two:e.orgAddressLineTwo?.trim()||void 0,org_address_line_three:e.orgAddressLineThree?.trim()||void 0,org_post_town:P("org_post_town",a),org_postcode:P("org_postcode",d),org_country_code:P("org_country_code",f)}},Mt=e=>{switch(e){case"invalid_input":case"rate_limited":return 2;case"network_error":return 3;case"signup_expired":case"timeout":return 4;case"interrupted":return 130;default:return 1}},Ht=(e,t)=>new Promise((o,n)=>{if(t.aborted)return n(t.reason??new Error("aborted"));let r=setTimeout(()=>{t.removeEventListener("abort",s),o()},e),s=()=>{clearTimeout(r),n(t.reason??new Error("aborted"))};t.addEventListener("abort",s,{once:!0})}),Jt=async(e,t)=>{let{baseUrl:o,json:n}=t,r=t.pollIntervalMs??Dt,s=t.pollTimeoutMs??jt,a=R()&&!n,d=new AbortController,f=!1,w=()=>{f=!0,d.abort()};process.on("SIGINT",w);let h=null;try{let k=await Gt(e,a),C=await Nt(o,k);n?process.stderr.write(`${JSON.stringify({event:"signup_url_issued",signup_url:C.signup_url,expires_at:C.expires_at})}
10
- `):process.stderr.write(`
11
- Open this URL in your browser to complete signup:
12
- ${C.signup_url}
13
- Link expires at ${C.expires_at}. This terminal will resume automatically.
14
-
15
- `),a&&(h=$.spinner(),h.start("Waiting for signup completion"));let _=Date.now(),v=_;for(;;){if(f)throw new c("interrupted","Signup interrupted. Re-run `idpc auth signup` to resume.");if(Date.now()-_>=s)throw new c("timeout",`Signup polling timed out after ${Math.round(s/1e3)}s.`);let K=await Lt(o,C.cli_token);if(K.status==="expired")throw new c("signup_expired","Signup link expired. Please re-run `idpc auth signup`.");if(K.status==="ready"){h?.stop("Signup complete");let N=M({api_key:K.data.test_api_key,user_token:K.data.user_token});m({success:!0,config_path:N,email:k.email,user_id:K.data.user_id},{json:n}),a&&$.outro(`Signed in as ${k.email}`);return}if(!a&&n){let N=Date.now();N-v>=3e4&&(v=N,process.stderr.write(`${JSON.stringify({event:"waiting",elapsed_sec:Math.round((N-_)/1e3)})}
16
- `))}try{await Ht(r,d.signal)}catch{}}}catch(k){if(h?.stop("Signup did not complete",1),k instanceof c){U({code:k.code,message:k.message,details:k.details},{json:n,exitCode:Mt(k.code)});return}u(k,{json:n})}finally{process.off("SIGINT",w)}},_e=new we.Command("signup").description("Create a new Ideal Postcodes account and store its test API key").option("--email <email>","Account holder email").option("--name <name>","Account holder full name").option("--org-name <name>","Organisation name").option("--org-address-line-one <line>","Organisation address line 1").option("--org-address-line-two <line>","Organisation address line 2").option("--org-address-line-three <line>","Organisation address line 3").option("--org-post-town <town>","Organisation post town").option("--org-postcode <postcode>","Organisation postcode").option("--org-country-code <iso2>","Organisation country code (ISO 3166-1 alpha-2)").action(async(e,t)=>{let{globals:o,json:n}=l(t),r=o.baseUrl??W;await Jt(e,{baseUrl:r,json:n})});var Ce=require("commander");var be=new Ce.Command("whoami").description("Show resolved credentials and verify the API key").action(async(e,t)=>{let{globals:o,json:n}=l(t),r=G(o.apiKey),s=A(o.userToken),i={api_key:r?{source:r.source,preview:r.value.slice(0,6)+"\u2026"}:null,user_token:s?{source:s.source,preview:s.value.slice(0,6)+"\u2026"}:null};if(!r){m({...i,live:!1},{json:n});return}try{let{available:a}=await O(g(o));m({...i,live:!0,available:a},{json:n})}catch(a){u(a,{json:n})}});var xe=new ve.Command("auth").description("Manage Ideal Postcodes credentials").addCommand(ye).addCommand(ke).addCommand(_e).addCommand(be);var Ue=require("commander");var Se=require("fs");var Ft=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)}),Ee=e=>e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),I=async(e,t)=>{if(t.file)return Ee((0,Se.readFileSync)(t.file,"utf-8"));if(t.stdin)return Ee(await Ft());if(!e)throw new c("missing_argument","Provide a query, --file <path>, or --stdin.");return[e]};var Pe=require("fs");var Te=require("fast-csv"),Bt=e=>e==null?"":String(e),Re=e=>e.map(Bt),Ae=async(e,t)=>(0,Te.writeToString)([Re(e),...t.map(Re)],{rowDelimiter:`\r
17
- `,includeEndRowDelimiter:!0});var Yt=new Set(["auth_failed","forbidden"]),Vt=e=>e instanceof c?{code:e.code,message:e.message}:{code:"unexpected_error",message:e instanceof Error?e.message:String(e)},q=async(e,t,o)=>{if(!o.batchMode){let r=await t(e[0]);m({query:e[0],response:r},{json:o.json});return}let n=[];for(let r of e)try{n.push({query:r,response:await t(r)})}catch(s){if(s instanceof c&&Yt.has(s.code))throw s;n.push({query:r,error:Vt(s)})}if(!o.json){let r=n.map(i=>"error"in i?o.errorRow(i.query,i.error.message):o.toRow(i.query,i.response)),s=await Ae(o.headers,r);o.out?((0,Pe.writeFileSync)(o.out,s,"utf-8"),process.stderr.write(`Wrote ${r.length} rows to ${o.out}
18
- `)):process.stdout.write(s);return}m(n.length===1?n[0]:{count:n.length,results:n},{json:o.json})};var Z=["query","status","full_address","confidence","fit","line_1","line_2","line_3","post_town","postcode","postcode_match","premise_match","thoroughfare_match","locality_match","post_town_match","organisation_match","latitude","longitude","uprn","udprn","id","language","country_iso","country_iso_2","organisation_name","department_name","po_box","premise","building_name","building_number","sub_building_name","county"],H=(e,t)=>typeof e=="number"&&Number.isFinite(e)?Number(e.toFixed(t)):e,Wt=e=>e==null?"":String(e),Qt=e=>[e.line_1,e.line_2,e.line_3,e.post_town,e.postcode].filter(t=>typeof t=="string"&&t.length>0).join(", "),Xt=()=>Array(Z.length).fill(""),ee=(e,t)=>{let o=Xt();return o[0]=e,o[1]=`Error: ${t}`,o},Oe=(e,t)=>{let o=t?.match;return!t||!o?ee(e,"No match"):[e,"Success",Qt(o),H(t.confidence,2),H(t.fit,2),o.line_1,o.line_2,o.line_3,o.post_town,o.postcode,t.postcode_match,t.premise_match,t.thoroughfare_match,t.locality_match,t.post_town_match,t.organisation_match,H(o.latitude,6),H(o.longitude,6),Wt(o.uprn),o.udprn,o.id,o.language,o.country_iso,o.country_iso_2,o.organisation_name,o.department_name,o.po_box,o.premise,o.building_name,o.building_number,o.sub_building_name,o.county]};var $e=new Ue.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("-o, --out <path>","Write CSV output to a file (batch mode only)").option("--context <iso>","ISO country hint (e.g. GBR, USA)").action(async(e,t,o)=>{let{globals:n,json:r}=l(o);try{let s=g(n),i=await I(e,t),a=!!t.file||!!t.stdin;await q(i,async d=>(await p("/cleanse/addresses",{auth:s,method:"POST",query:{context:t.context,tags:"cli"},body:{query:d}})).data,{json:r,batchMode:a,out:t.out,headers:Z,toRow:(d,f)=>Oe(d,f?.result),errorRow:ee})}catch(s){u(s,{json:r})}});var Ke=require("commander"),y=x(require("picocolors"),1);var qe="@ideal-postcodes/cli";var De="1.0.1";var J=qe,F=De;var je=e=>e instanceof Error?e.message:String(e),zt=e=>{let t=[];return e.lookups_remaining===0&&t.push("No lookups remaining \u2014 top up the key balance"),e.daily_limit.limit!==null&&e.daily_limit.consumed>=e.daily_limit.limit&&t.push(`Daily limit reached (${e.daily_limit.consumed}/${e.daily_limit.limit})`),e.monthly_limit.limit!==null&&e.monthly_limit.consumed>=e.monthly_limit.limit&&t.push(`Monthly limit reached (${e.monthly_limit.consumed}/${e.monthly_limit.limit})`),e.allowed_urls.length>0&&t.push(`Allowed URLs are set (${e.allowed_urls.length}); the CLI sends no Origin, so the key always reports unusable here. This is expected \u2014 the key still works from its permitted URLs.`),t.length===0&&t.push("Key reports unusable but no balance, limit, or allowed-URL cause was found."),t},Zt=e=>{let t=[];t.push(y.default.bold(`${e.cli.name} v${e.cli.version}`)),t.push(` ${y.default.dim("node")} ${e.runtime.node} (${e.runtime.platform}/${e.runtime.arch})`),t.push(` ${y.default.dim("config")} ${e.config.path}`);let o=n=>n?`${y.default.green("\u2713")} ${n.source}`:y.default.gray("not set");if(t.push(` ${y.default.dim("api key")} ${o(e.credentials.api_key)}`),t.push(` ${y.default.dim("token")} ${o(e.credentials.user_token)}`),e.connectivity.reachable===null)return t.push(` ${y.default.dim("api")} ${y.default.gray("skipped (no api key)")}`),t.join(`
19
- `);if(e.connectivity.reachable===!1)return t.push(` ${y.default.dim("api")} ${y.default.red("\u2717")} ${e.connectivity.error??"unreachable"}`),t.join(`
20
- `);e.key.available===!0?t.push(` ${y.default.dim("key")} ${y.default.green("\u2713 usable")}`):t.push(` ${y.default.dim("key")} ${y.default.red("\u2717 not usable")}`),e.key.lookups_remaining!==void 0&&t.push(` ${y.default.dim("balance")} ${e.key.lookups_remaining} lookups remaining`);for(let n of e.key.diagnosis)t.push(` ${y.default.red("\u2717")} ${n}`);for(let n of e.key.warnings)t.push(` ${y.default.yellow("!")} ${n}`);return t.join(`
21
- `)},Ne=new Ke.Command("doctor").description("Print environment info, verify connectivity, and check key usability").action(async(e,t)=>{let{globals:o,json:n}=l(t),r=G(o.apiKey),s=A(o.userToken),i=null,a,d=null,f,w=[],h=[];if(r)try{let C=await O({apiKey:r.value});if(i=!0,d=C.available,s)try{let _=await me({apiKey:r.value,userToken:s.value});f=_.lookups_remaining;let v=_.notifications.balance_threshold;_.lookups_remaining>0&&v!==null&&_.lookups_remaining<=v&&h.push(`Low balance: ${_.lookups_remaining} lookups remaining (threshold ${v})`),d||w.push(...zt(_))}catch(_){let v=`Could not read key details (user token rejected?): ${je(_)}`;d?h.push(v):w.push(v)}else h.push("No user token set \u2014 run `idpc auth login` with a user token to check balance, limits, and full key status.")}catch(C){i=!1,a=je(C)}let k={cli:{name:J,version:F},runtime:{node:process.version,platform:process.platform,arch:process.arch},config:{path:S()},credentials:{api_key:r?{source:r.source}:null,user_token:s?{source:s.source}:null},connectivity:{reachable:i,error:a},key:{available:d,lookups_remaining:f,diagnosis:w,warnings:h}};m(k,{json:n,human:Zt})});var Ge=require("commander");var te=["query","status","result","deliverable","disposable","free","role","catchall","suggestions"],eo=()=>Array(te.length).fill(""),oe=(e,t)=>{let o=eo();return o[0]=e,o[1]=`Error: ${t}`,o},Le=(e,t)=>t?[e,"Success",t.result,t.deliverable,t.disposable,t.free,t.role,t.catchall,(t.suggestions??[]).join("; ")]:oe(e,"No result");var Me=new Ge.Command("email").description("Validate one or more email addresses (GET /emails)").argument("[query]","Email address to validate").option("-f, --file <path>","Read one email per line from a file").option("--stdin","Read one email per line from stdin").option("-o, --out <path>","Write CSV output to a file (batch mode only)").action(async(e,t,o)=>{let{globals:n,json:r}=l(o);try{let s=g(n),i=await I(e,t),a=!!t.file||!!t.stdin;await q(i,async d=>(await p("/emails",{auth:s,method:"GET",query:{query:d,tags:"cli"}})).data,{json:r,batchMode:a,out:t.out,headers:te,toRow:(d,f)=>Le(d,f?.result),errorRow:oe})}catch(s){u(s,{json:r})}});var He=require("commander"),B=x(require("picocolors"),1);var to=e=>e.count===0?B.default.gray("no suggestions"):e.suggestions.map((t,o)=>` ${B.default.dim(String(o+1).padStart(2))} ${t.suggestion} ${B.default.dim(t.id)}`).join(`
22
- `),oo=async(e,t,o)=>(await p("/autocomplete/addresses",{auth:e,method:"GET",query:{query:t,country:o}})).data?.result?.hits??[],Je=new He.Command("find").description("Autocomplete addresses (GET /autocomplete/addresses)").argument("<query>","Search string").option("--country <iso3>","ISO-3 country code (e.g. GBR, USA)").action(async(e,t,o)=>{let{globals:n,json:r}=l(o);try{let s=g(n),i=await oo(s,e,t.country);m({count:i.length,suggestions:i},{json:r,human:to})}catch(s){u(s,{json:r})}});var pt=require("commander");var tt=require("commander");var Fe=require("commander");var Be=new Fe.Command("create").description("Create a config (POST /keys/:key/configs)").argument("<name>","Unique name for the config").argument("[key]","API key (defaults to configured key)").requiredOption("--payload <json>","Serialised config payload (JSON string)").action(async(e,t,o,n)=>{let{globals:r,json:s}=l(n);try{let i=g(r,{requireUserToken:!0}),a=t??i.apiKey;try{JSON.parse(o.payload)}catch{throw new c("invalid_input","--payload must be valid JSON")}let d=await p(`/keys/${encodeURIComponent(a)}/configs`,{auth:i,method:"POST",body:{name:e,payload:o.payload}});m(d.data,{json:s})}catch(i){u(i,{json:s})}});var Ye=require("commander"),D=x(require("@clack/prompts"),1);var Ve=new Ye.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:r,json:s}=l(n);try{let i=g(r,{requireUserToken:!0}),a=t??i.apiKey;if(!o.yes){if(!R()||s)throw new c("invalid_input","Destructive operation requires --yes in non-interactive mode.");let f=await D.confirm({message:`Delete config "${e}"?`,initialValue:!1});(D.isCancel(f)||!f)&&(D.cancel("Aborted."),process.exit(1))}let d=await p(`/keys/${encodeURIComponent(a)}/configs/${encodeURIComponent(e)}`,{auth:i,method:"DELETE"});m({success:!0,result:d.data},{json:s})}catch(i){u(i,{json:s})}});var We=require("commander");var Qe=new We.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:r,json:s}=l(n);try{let i=g(r,{requireUserToken:!0}),a=t??i.apiKey,d=await p(`/keys/${encodeURIComponent(a)}/configs/${encodeURIComponent(e)}`,{auth:i,method:"GET"});m(d.data,{json:s})}catch(i){u(i,{json:s})}});var Xe=require("commander");var ze=new Xe.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:r}=l(o);try{let s=g(n,{requireUserToken:!0}),i=e??s.apiKey,a=await p(`/keys/${encodeURIComponent(i)}/configs`,{auth:s,method:"GET"});m(a.data,{json:r})}catch(s){u(s,{json:r})}});var Ze=require("commander");var et=new Ze.Command("update").description("Update a config (POST /keys/:key/configs/:config)").argument("<config>","Config name").argument("[key]","API key (defaults to configured key)").requiredOption("--payload <json>","Serialised config payload (JSON string)").action(async(e,t,o,n)=>{let{globals:r,json:s}=l(n);try{let i=g(r,{requireUserToken:!0}),a=t??i.apiKey;try{JSON.parse(o.payload)}catch{throw new c("invalid_input","--payload must be valid JSON")}let d=await p(`/keys/${encodeURIComponent(a)}/configs/${encodeURIComponent(e)}`,{auth:i,method:"POST",body:{payload:o.payload}});m(d.data,{json:s})}catch(i){u(i,{json:s})}});var ot=new tt.Command("configs").description("Allowed-URL configs for a key").addCommand(ze).addCommand(Qe).addCommand(Be).addCommand(et).addCommand(Ve);var nt=require("commander");var rt=new nt.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:r}=l(o);try{let s=g(n,{requireUserToken:!0}),i=e??s.apiKey,a=await p(`/keys/${encodeURIComponent(i)}/details`,{auth:s,method:"GET"});m(a.data,{json:r})}catch(s){u(s,{json:r})}});var st=require("commander");var it=new st.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:r}=l(o);try{let s=g(n,{includeUserToken:!1}),i=e??s.apiKey,a=await p(`/keys/${encodeURIComponent(i)}`,{auth:s,method:"GET"});m(a.data,{json:r})}catch(s){u(s,{json:r})}});var at=require("commander");var j=e=>{if(e===void 0)return;let t=Date.parse(e);if(Number.isNaN(t))throw new c("invalid_input",`Invalid date "${e}". Use YYYY-MM-DD or ISO 8601.`);return t};var dt=new at.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:r}=l(o);try{if(r)throw new c("invalid_input","keys logs emits CSV and does not support --json or --quiet. Redirect to a file: `idpc keys logs > lookups.csv`.");let s=g(n,{requireUserToken:!0}),i=e??s.apiKey,a=await p(`/keys/${encodeURIComponent(i)}/lookups`,{auth:s,method:"GET",accept:"csv",query:{start:j(t.start),end:j(t.end),licensee:t.licensee}});process.stdout.write(a.data),a.data.endsWith(`
6
+ `)},U=(e,t={})=>{F(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(`${H.default.red("error")} ${H.default.gray(`[${e.code}]`)} ${e.message}
8
+ `),process.exit(t.exitCode??1)},u=(e,t={})=>{if(e instanceof p)return U({code:e.code,message:e.message,details:e.details},t);let o=e instanceof Error?e.message:String(e);return U({code:"unexpected_error",message:o},t)};var T=b(require("@clack/prompts"),1),vt=(e="Cancelled.")=>{T.cancel(e),process.exit(1)},J=async(e,t)=>{let o=await T.password({message:e,validate:t});return T.isCancel(o)&&vt(),o};var Rt=["auth_failed","forbidden","not_found"],ae=e=>{let{brand:t,cfg:o}=e,n=async(r,a,s)=>{try{let{available:i}=await S(e,r,{apiKey:a,userToken:s});return i}catch(i){throw i instanceof p&&Rt.includes(i.code)?new p("auth_failed",`Credentials rejected by API: ${i.message}`,i.details):i}};return new ie.Command("login").description(`Save ${t.displayName} credentials (api_key and user_token)`).option("--api-key <key>","API key to store").option("--user-token <token>","User token to store").action(async(r,a)=>{let{globals:s,json:i}=l(a),c=r.apiKey??s.apiKey,d=r.userToken??s.userToken;try{if(!c||!d)if(!A()||i){if(!c)return U({code:"invalid_input",message:"Non-interactive mode requires --api-key."},{json:i})}else x.intro(`${t.displayName} login`),x.log.info(`Find your API key at ${t.accountUrl}
9
+ User tokens are shown alongside each key and unlock /keys/* reads \u2014 optional, press enter to skip.`),c||(c=await J("Enter your API key:",w=>w?void 0:"API key required")),d||(d=await J("Enter your user token (optional):")||void 0);let y=!i&&A()?x.spinner():null;y?.start("Verifying credentials");let C;try{C=await n(s,c,d),y?.stop("Credentials verified")}catch(w){throw y?.stop("Verification failed",1),w}let h=o.upsertCredentials({api_key:c,...d?{user_token:d}:{}});m({success:!0,config_path:h,available:C},{json:i}),!i&&A()&&x.outro("Saved credentials.")}catch(y){u(y,{json:i})}})};var ce=require("commander");var le=e=>new ce.Command("logout").description("Remove stored credentials").action((t,o)=>{let{json:n}=l(o),r=e.cfg.clearCredentials();m({success:!0,removed:r,config_path:e.cfg.getCredentialsPath()},{json:n})});var ue=require("commander");var de=e=>new ue.Command("whoami").description("Show resolved credentials and verify the API key").action(async(t,o)=>{let{globals:n,json:r}=l(o),a=e.cfg.resolveApiKey(n.apiKey),s=e.cfg.resolveUserToken(n.userToken),i={api_key:a?{source:a.source,preview:a.value.slice(0,6)+"\u2026"}:null,user_token:s?{source:s.source,preview:s.value.slice(0,6)+"\u2026"}:null};if(!a){m({...i,live:!1},{json:r});return}try{let{available:c}=await S(e,n,g(e,n));m({...i,live:!0,available:c},{json:r})}catch(c){u(c,{json:r})}});var pe=e=>new me.Command("auth").description(`Manage ${e.brand.displayName} credentials`).addCommand(ae(e)).addCommand(le(e)).addCommand(de(e));var fe=require("commander"),k=b(require("picocolors"),1);var ge=e=>e instanceof Error?e.message:String(e),xt=e=>{let t=[];return e.lookups_remaining===0&&t.push("No lookups remaining \u2014 top up the key balance"),e.daily_limit.limit!==null&&e.daily_limit.consumed>=e.daily_limit.limit&&t.push(`Daily limit reached (${e.daily_limit.consumed}/${e.daily_limit.limit})`),e.monthly_limit.limit!==null&&e.monthly_limit.consumed>=e.monthly_limit.limit&&t.push(`Monthly limit reached (${e.monthly_limit.consumed}/${e.monthly_limit.limit})`),e.allowed_urls.length>0&&t.push(`Allowed URLs are set (${e.allowed_urls.length}); the CLI sends no Origin, so the key always reports unusable here. This is expected \u2014 the key still works from its permitted URLs.`),t.length===0&&t.push("Key reports unusable but no balance, limit, or allowed-URL cause was found."),t},St=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}`:k.default.gray("not set");if(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.reachable===null)return t.push(` ${k.default.dim("api")} ${k.default.gray("skipped (no api key)")}`),t.join(`
10
+ `);if(e.connectivity.reachable===!1)return t.push(` ${k.default.dim("api")} ${k.default.red("\u2717")} ${e.connectivity.error??"unreachable"}`),t.join(`
11
+ `);e.key.available===!0?t.push(` ${k.default.dim("key")} ${k.default.green("\u2713 usable")}`):t.push(` ${k.default.dim("key")} ${k.default.red("\u2717 not usable")}`),e.key.lookups_remaining!==void 0&&t.push(` ${k.default.dim("balance")} ${e.key.lookups_remaining} lookups remaining`);for(let n of e.key.diagnosis)t.push(` ${k.default.red("\u2717")} ${n}`);for(let n of e.key.warnings)t.push(` ${k.default.yellow("!")} ${n}`);return t.join(`
12
+ `)},ye=e=>new fe.Command("doctor").description("Print environment info, verify connectivity, and check key usability").action(async(t,o)=>{let{globals:n,json:r}=l(o),{brand:a,cfg:s}=e,i=s.resolveApiKey(n.apiKey),c=s.resolveUserToken(n.userToken),d=null,y,C=null,h,w=[],v=[];if(i)try{let K=await S(e,n,{apiKey:i.value});if(d=!0,C=K.available,c)try{let R=await B(e,n,{apiKey:i.value,userToken:c.value});h=R.lookups_remaining;let $=R.notifications.balance_threshold;R.lookups_remaining>0&&$!==null&&R.lookups_remaining<=$&&v.push(`Low balance: ${R.lookups_remaining} lookups remaining (threshold ${$})`),C||w.push(...xt(R))}catch(R){let $=`Could not read key details (user token rejected?): ${ge(R)}`;C?v.push($):w.push($)}else v.push(`No user token set \u2014 run \`${a.binName} auth login\` with a user token to check balance, limits, and full key status.`)}catch(K){d=!1,y=ge(K)}let pt={cli:{name:a.packageName,version:a.version},runtime:{node:process.version,platform:process.platform,arch:process.arch},config:{path:s.getCredentialsPath()},credentials:{api_key:i?{source:i.source}:null,user_token:c?{source:c.source}:null},connectivity:{reachable:d,error:y},key:{available:C,lookups_remaining:h,diagnosis:w,warnings:v}};m(pt,{json:r,human:St})});var ve=require("commander");var Ce=require("fs");var At=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)}),he=e=>e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),E=async(e,t)=>{if(t.file)return he((0,Ce.readFileSync)(t.file,"utf-8"));if(t.stdin)return he(await At());if(!e)throw new p("missing_argument","Provide a query, --file <path>, or --stdin.");return[e]};var _e=require("fs");var we=require("fast-csv"),Tt=e=>e==null?"":String(e),ke=e=>e.map(Tt),Y=async(e,t)=>(0,we.writeToString)([ke(e),...t.map(ke)],{rowDelimiter:`\r
13
+ `,includeEndRowDelimiter:!0});var Et=new Set(["auth_failed","forbidden"]),Dt=e=>e instanceof p?{code:e.code,message:e.message}:{code:"unexpected_error",message:e instanceof Error?e.message:String(e)},D=async(e,t,o)=>{if(!o.batchMode){let r=await t(e[0]);m({query:e[0],response:r},{json:o.json});return}let n=[];for(let r of e)try{n.push({query:r,response:await t(r)})}catch(a){if(a instanceof p&&Et.has(a.code))throw a;n.push({query:r,error:Dt(a)})}if(!o.json){let r=n.map(s=>"error"in s?o.errorRow(s.query,s.error.message):o.toRow(s.query,s.response)),a=await Y(o.headers,r);o.out?((0,_e.writeFileSync)(o.out,a,"utf-8"),process.stderr.write(`Wrote ${r.length} rows to ${o.out}
14
+ `)):process.stdout.write(a);return}m(n.length===1?n[0]:{count:n.length,results:n},{json:o.json})};var V=["query","status","result","deliverable","disposable","free","role","catchall","suggestions"],Ot=()=>Array(V.length).fill(""),W=(e,t)=>{let o=Ot();return o[0]=e,o[1]=`Error: ${t}`,o},be=(e,t)=>t?[e,"Success",t.result,t.deliverable,t.disposable,t.free,t.role,t.catchall,(t.suggestions??[]).join("; ")]:W(e,"No result");var Re=e=>new ve.Command("email").description("Validate one or more email addresses (GET /emails)").argument("[query]","Email address to validate").option("-f, --file <path>","Read one email per line from a file").option("--stdin","Read one email per line from stdin").option("-o, --out <path>","Write CSV output to a file (batch mode only)").action(async(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r),i=await E(t,o),c=!!o.file||!!o.stdin;await D(i,async d=>(await f(e,r,"/emails",{auth:s,method:"GET",query:{query:d,tags:"cli"}})).data,{json:a,batchMode:c,out:o.out,headers:V,toRow:(d,y)=>be(d,y?.result),errorRow:W})}catch(s){u(s,{json:a})}});var xe=require("commander"),I=b(require("picocolors"),1);var $t=e=>e.count===0?I.default.gray("no suggestions"):e.suggestions.map((t,o)=>` ${I.default.dim(String(o+1).padStart(2))} ${t.suggestion} ${I.default.dim(t.id)}`).join(`
15
+ `),Se=e=>new xe.Command("find").description("Autocomplete addresses (GET /autocomplete/addresses)").argument("<query>","Search string").option("--country <iso3>","ISO-3 country code (e.g. GBR, USA)").action(async(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r),c=(await f(e,r,"/autocomplete/addresses",{auth:s,method:"GET",query:{query:t,country:o.country}})).data?.result?.hits??[];m({count:c.length,suggestions:c},{json:a,human:$t})}catch(s){u(s,{json:a})}});var We=require("commander");var Ne=require("commander");var Ae=require("commander");var Te=e=>new Ae.Command("create").description("Create a config (POST /keys/:key/configs)").argument("<name>","Unique name for the config").argument("[key]","API key (defaults to configured key)").requiredOption("--payload <json>","Serialised config payload (JSON string)").action(async(t,o,n,r)=>{let{globals:a,json:s}=l(r);try{let i=g(e,a,{requireUserToken:!0}),c=o??i.apiKey;try{JSON.parse(n.payload)}catch{throw new p("invalid_input","--payload must be valid JSON")}let d=await f(e,a,`/keys/${encodeURIComponent(c)}/configs`,{auth:i,method:"POST",body:{name:t,payload:n.payload}});m(d.data,{json:s})}catch(i){u(i,{json:s})}});var P=b(require("@clack/prompts"),1),Ee=require("commander");var De=e=>new Ee.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(t,o,n,r)=>{let{globals:a,json:s}=l(r);try{let i=g(e,a,{requireUserToken:!0}),c=o??i.apiKey;if(!n.yes){if(!A()||s)throw new p("invalid_input","Destructive operation requires --yes in non-interactive mode.");let y=await P.confirm({message:`Delete config "${t}"?`,initialValue:!1});(P.isCancel(y)||!y)&&(P.cancel("Aborted."),process.exit(1))}let d=await f(e,a,`/keys/${encodeURIComponent(c)}/configs/${encodeURIComponent(t)}`,{auth:i,method:"DELETE"});m({success:!0,result:d.data},{json:s})}catch(i){u(i,{json:s})}});var Oe=require("commander");var $e=e=>new Oe.Command("get").description("Retrieve one config (GET /keys/:key/configs/:config)").argument("<config>","Config name").argument("[key]","API key (defaults to configured key)").action(async(t,o,n,r)=>{let{globals:a,json:s}=l(r);try{let i=g(e,a,{requireUserToken:!0}),c=o??i.apiKey,d=await f(e,a,`/keys/${encodeURIComponent(c)}/configs/${encodeURIComponent(t)}`,{auth:i,method:"GET"});m(d.data,{json:s})}catch(i){u(i,{json:s})}});var Ue=require("commander");var Pe=e=>new Ue.Command("list").description("List allowed-URL configs (GET /keys/:key/configs)").argument("[key]","API key (defaults to configured key)").action(async(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r,{requireUserToken:!0}),i=t??s.apiKey,c=await f(e,r,`/keys/${encodeURIComponent(i)}/configs`,{auth:s,method:"GET"});m(c.data,{json:a})}catch(s){u(s,{json:a})}});var qe=require("commander");var Ie=e=>new qe.Command("update").description("Update a config (POST /keys/:key/configs/:config)").argument("<config>","Config name").argument("[key]","API key (defaults to configured key)").requiredOption("--payload <json>","Serialised config payload (JSON string)").action(async(t,o,n,r)=>{let{globals:a,json:s}=l(r);try{let i=g(e,a,{requireUserToken:!0}),c=o??i.apiKey;try{JSON.parse(n.payload)}catch{throw new p("invalid_input","--payload must be valid JSON")}let d=await f(e,a,`/keys/${encodeURIComponent(c)}/configs/${encodeURIComponent(t)}`,{auth:i,method:"POST",body:{payload:n.payload}});m(d.data,{json:s})}catch(i){u(i,{json:s})}});var je=e=>new Ne.Command("configs").description("Allowed-URL configs for a key").addCommand(Pe(e)).addCommand($e(e)).addCommand(Te(e)).addCommand(Ie(e)).addCommand(De(e));var Ke=require("commander");var Ge=e=>new Ke.Command("details").description("Private key details (GET /keys/:key/details) \u2014 requires user_token").argument("[key]","API key (defaults to configured key)").action(async(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r,{requireUserToken:!0}),i=t??s.apiKey,c=await f(e,r,`/keys/${encodeURIComponent(i)}/details`,{auth:s,method:"GET"});m(c.data,{json:a})}catch(s){u(s,{json:a})}});var Le=require("commander");var Me=e=>new Le.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(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r,{includeUserToken:!1}),i=t??s.apiKey,c=await f(e,r,`/keys/${encodeURIComponent(i)}`,{auth:s,method:"GET"});m(c.data,{json:a})}catch(s){u(s,{json:a})}});var Be=require("commander");var O=e=>{if(e===void 0)return;let t=Date.parse(e);if(Number.isNaN(t))throw new p("invalid_input",`Invalid date "${e}". Use YYYY-MM-DD or ISO 8601.`);return t};var Fe=e=>new Be.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(t,o,n)=>{let{globals:r,json:a}=l(n);try{if(a)throw new p("invalid_input",`${e.brand.binName} keys logs emits CSV and does not support --json or --quiet. Redirect to a file: \`${e.brand.binName} keys logs > lookups.csv\`.`);let s=g(e,r,{requireUserToken:!0}),i=t??s.apiKey,c=await f(e,r,`/keys/${encodeURIComponent(i)}/lookups`,{auth:s,method:"GET",accept:"csv",query:{start:O(o.start),end:O(o.end),licensee:o.licensee}});process.stdout.write(c.data),c.data.endsWith(`
23
16
  `)||process.stdout.write(`
24
- `)}catch(s){u(s,{json:r})}});var ct=require("commander");var lt=new ct.Command("update").description("Update key details (PUT /keys/:key/details) \u2014 requires user_token").argument("[key]","API key (defaults to configured key)").requiredOption("--json-body <json>","Raw JSON body of fields to update").action(async(e,t,o)=>{let{globals:n,json:r}=l(o);try{let s=g(n,{requireUserToken:!0}),i=e??s.apiKey,a;try{a=JSON.parse(t.jsonBody)}catch{throw new c("invalid_input","--json-body must be valid JSON")}let d=await p(`/keys/${encodeURIComponent(i)}/details`,{auth:s,method:"PUT",body:a});m(d.data,{json:r})}catch(s){u(s,{json:r})}});var ut=require("commander");var mt=new ut.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:r}=l(o);try{let s=g(n,{requireUserToken:!0}),i=e??s.apiKey,a=await p(`/keys/${encodeURIComponent(i)}/usage`,{auth:s,method:"GET",query:{start:j(t.start),end:j(t.end),tags:t.tags,licensee:t.licensee}});m(a.data,{json:r})}catch(s){u(s,{json:r})}});var gt=new pt.Command("keys").description("Manage and inspect API keys").addCommand(it).addCommand(rt).addCommand(lt).addCommand(mt).addCommand(dt).addCommand(ot);var ht=require("commander");var ne=["query","status","valid","national_format","international_format","iso_country","iso_country_2","country","current_carrier","original_carrier"],ft=e=>typeof e=="string"?e:e?.name??"",no=()=>Array(ne.length).fill(""),re=(e,t)=>{let o=no();return o[0]=e,o[1]=`Error: ${t}`,o},yt=(e,t)=>t?[e,"Success",t.valid,t.national_format,t.international_format,t.iso_country,t.iso_country_2,t.country,ft(t.current_carrier),ft(t.original_carrier)]:re(e,"No result");var kt=new ht.Command("phone").description("Validate one or more phone numbers (GET /phone_numbers)").argument("[query]","Phone number to validate").option("-f, --file <path>","Read one phone number per line from a file").option("--stdin","Read one phone number per line from stdin").option("-o, --out <path>","Write CSV output to a file (batch mode only)").option("--carrier","Look up the current network carrier (slower)").action(async(e,t,o)=>{let{globals:n,json:r}=l(o);try{let s=g(n),i=await I(e,t),a=!!t.file||!!t.stdin;await q(i,async d=>(await p("/phone_numbers",{auth:s,method:"GET",query:{query:d,tags:"cli",current_carrier:t.carrier?"true":void 0}})).data,{json:r,batchMode:a,out:t.out,headers:ne,toRow:(d,f)=>yt(d,f?.result),errorRow:re})}catch(s){u(s,{json:r})}});var _t=require("commander");var Y=x(require("picocolors"),1),wt=e=>{if(!e)return Y.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(` ${Y.default.bold(o)}`),e.country&&t.push(` ${Y.default.dim(String(e.country))}`),t.join(`
25
- `)};var ro=e=>wt(e?.result?.hits?.[0]??null),Ct=new _t.Command("resolve").description("Resolve an autocomplete suggestion to a full address (GET /autocomplete/addresses/:id/gbr)").argument("<id>","Suggestion id returned by `idpc find`").action(async(e,t,o)=>{let{globals:n,json:r}=l(o);try{let s=g(n),i=await p(`/autocomplete/addresses/${encodeURIComponent(e)}/gbr`,{auth:s,method:"GET",query:{tags:"cli"}});m(i.data,{json:r,human:ro})}catch(s){u(s,{json:r})}});var so=new bt.Command().name("idpc").description("Ideal Postcodes CLI \u2014 key management, address cleanse, email & phone validation, autocomplete").configureOutput({writeErr:e=>{process.stderr.write(e.replace(/^error:/,()=>vt.default.red("error:")))}}).version(`${J} v${F}`,"-v, --version").option("--api-key <key>","Ideal Postcodes API key").option("--user-token <token>","Ideal Postcodes user token").option("--json","Force JSON output").option("-q, --quiet","Suppress status output (implies --json)").option("--base-url <url>","Override API base URL").addCommand(xe).addCommand(gt).addCommand($e).addCommand(Me).addCommand(kt).addCommand(Je).addCommand(Ct).addCommand(Ne);so.parseAsync(process.argv).catch(e=>{u(e)});
17
+ `)}catch(s){u(s,{json:a})}});var He=require("commander");var Je=e=>new He.Command("update").description("Update key details (PUT /keys/:key/details) \u2014 requires user_token").argument("[key]","API key (defaults to configured key)").requiredOption("--json-body <json>","Raw JSON body of fields to update").action(async(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r,{requireUserToken:!0}),i=t??s.apiKey,c;try{c=JSON.parse(o.jsonBody)}catch{throw new p("invalid_input","--json-body must be valid JSON")}let d=await f(e,r,`/keys/${encodeURIComponent(i)}/details`,{auth:s,method:"PUT",body:c});m(d.data,{json:a})}catch(s){u(s,{json:a})}});var Ye=require("commander");var Ve=e=>new Ye.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(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r,{requireUserToken:!0}),i=t??s.apiKey,c=await f(e,r,`/keys/${encodeURIComponent(i)}/usage`,{auth:s,method:"GET",query:{start:O(o.start),end:O(o.end),tags:o.tags,licensee:o.licensee}});m(c.data,{json:a})}catch(s){u(s,{json:a})}});var Qe=e=>new We.Command("keys").description("Manage and inspect API keys").addCommand(Me(e)).addCommand(Ge(e)).addCommand(Je(e)).addCommand(Ve(e)).addCommand(Fe(e)).addCommand(je(e));var Ze=require("commander");var Q=["query","status","valid","national_format","international_format","iso_country","iso_country_2","country","current_carrier","original_carrier"],ze=e=>typeof e=="string"?e:e?.name??"",Ut=()=>Array(Q.length).fill(""),z=(e,t)=>{let o=Ut();return o[0]=e,o[1]=`Error: ${t}`,o},Xe=(e,t)=>t?[e,"Success",t.valid,t.national_format,t.international_format,t.iso_country,t.iso_country_2,t.country,ze(t.current_carrier),ze(t.original_carrier)]:z(e,"No result");var et=e=>new Ze.Command("phone").description("Validate one or more phone numbers (GET /phone_numbers)").argument("[query]","Phone number to validate").option("-f, --file <path>","Read one phone number per line from a file").option("--stdin","Read one phone number per line from stdin").option("-o, --out <path>","Write CSV output to a file (batch mode only)").option("--carrier","Look up the current network carrier (slower)").action(async(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r),i=await E(t,o),c=!!o.file||!!o.stdin;await D(i,async d=>(await f(e,r,"/phone_numbers",{auth:s,method:"GET",query:{query:d,tags:"cli",current_carrier:o.carrier?"true":void 0}})).data,{json:a,batchMode:c,out:o.out,headers:Q,toRow:(d,y)=>Xe(d,y?.result),errorRow:z})}catch(s){u(s,{json:a})}});var tt=require("commander");var N=b(require("picocolors"),1),Pt=e=>typeof e=="string"?e:"",X=e=>{if(!e)return N.default.gray("no match");let t=[e.address_line_one??e.line_1,e.address_line_two??e.line_2,e.line_3].filter(r=>!!r).map(r=>` ${r}`),o=[e.city??e.post_town,e.state,e.zip_code??e.postcode].map(Pt).filter(Boolean).join(" ");o&&t.push(` ${N.default.bold(o)}`);let n=e.country??e.country_iso_2;return n&&t.push(` ${N.default.dim(String(n))}`),t.join(`
18
+ `)};var qt=e=>X(e?.result?.hits?.[0]??null),ot=e=>new tt.Command("resolve").description("Resolve an autocomplete suggestion to a full address (GET /autocomplete/addresses/:id/:country)").argument("<id>",`Suggestion id returned by \`${e.brand.binName} find\``).option("--country <iso3>","Resolution dataset",e.brand.defaultResolveCountry).action(async(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r),i=String(o.country).toLowerCase(),c=await f(e,r,`/autocomplete/addresses/${encodeURIComponent(t)}/${encodeURIComponent(i)}`,{auth:s,method:"GET",query:{tags:"cli"}});m(c.data,{json:a,human:qt})}catch(s){u(s,{json:a})}});var st=(e,t=[])=>{let o=M(e),n=new nt.Command().name(e.binName).description(e.description).configureOutput({writeErr:r=>{process.stderr.write(r.replace(/^error:/,()=>rt.default.red("error:")))}}).version(`${e.packageName} v${e.version}`,"-v, --version").option("--api-key <key>",`${e.displayName} API key`).option("--user-token <token>",`${e.displayName} user token`).option("--json","Force JSON output").option("-q, --quiet","Suppress status output (implies --json)").option("--base-url <url>","Override API base URL").addCommand(pe(o)).addCommand(Qe(o));for(let r of t)n.addCommand(r(o));return n.addCommand(Re(o)).addCommand(et(o)).addCommand(Se(o)).addCommand(ot(o)).addCommand(ye(o)),n},Z=(e,t=[])=>{st(e,t).parseAsync(process.argv).catch(n=>{u(n)})};var ee=b(require("@clack/prompts"),1),It=require("commander");var dr=1800*1e3;var at="@ideal-postcodes/cli";var ct="1.0.2";var lt={binName:"idpc",packageName:at,version:ct,displayName:"Ideal Postcodes",description:"Ideal Postcodes CLI \u2014 key management, address cleanse, email & phone validation, autocomplete",baseUrl:"https://api.ideal-postcodes.co.uk/v1",userAgent:"idpc-cli",configDirName:"ideal-postcodes",env:{apiKey:"IDPC_API_KEY",userToken:"IDPC_USER_TOKEN",configDir:"IDPC_CONFIG_DIR"},accountUrl:"https://ideal-postcodes.co.uk/account/",defaultResolveCountry:"gbr"};var dt=require("commander");var te=["query","status","full_address","confidence","fit","line_1","line_2","line_3","post_town","postcode","postcode_match","premise_match","thoroughfare_match","locality_match","post_town_match","organisation_match","latitude","longitude","uprn","udprn","id","language","country_iso","country_iso_2","organisation_name","department_name","po_box","premise","building_name","building_number","sub_building_name","county"],j=(e,t)=>typeof e=="number"&&Number.isFinite(e)?Number(e.toFixed(t)):e,Nt=e=>e==null?"":String(e),jt=e=>[e.line_1,e.line_2,e.line_3,e.post_town,e.postcode].filter(t=>typeof t=="string"&&t.length>0).join(", "),Kt=()=>Array(te.length).fill(""),oe=(e,t)=>{let o=Kt();return o[0]=e,o[1]=`Error: ${t}`,o},ut=(e,t)=>{let o=t?.match;return!t||!o?oe(e,"No match"):[e,"Success",jt(o),j(t.confidence,2),j(t.fit,2),o.line_1,o.line_2,o.line_3,o.post_town,o.postcode,t.postcode_match,t.premise_match,t.thoroughfare_match,t.locality_match,t.post_town_match,t.organisation_match,j(o.latitude,6),j(o.longitude,6),Nt(o.uprn),o.udprn,o.id,o.language,o.country_iso,o.country_iso_2,o.organisation_name,o.department_name,o.po_box,o.premise,o.building_name,o.building_number,o.sub_building_name,o.county]};var mt=e=>new dt.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("-o, --out <path>","Write CSV output to a file (batch mode only)").option("--context <iso>","ISO country hint (e.g. GBR, USA)").action(async(t,o,n)=>{let{globals:r,json:a}=l(n);try{let s=g(e,r),i=await E(t,o),c=!!o.file||!!o.stdin;await D(i,async d=>(await f(e,r,"/cleanse/addresses",{auth:s,method:"POST",query:{context:o.context,tags:"cli"},body:{query:d}})).data,{json:a,batchMode:c,out:o.out,headers:te,toRow:(d,y)=>ut(d,y?.result),errorRow:oe})}catch(s){u(s,{json:a})}});Z(lt,[mt]);
package/package.json CHANGED
@@ -1,14 +1,13 @@
1
1
  {
2
2
  "name": "@ideal-postcodes/cli",
3
3
  "description": "Ideal Postcodes CLI — idpc",
4
- "version": "1.0.1",
4
+ "version": "1.0.2",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "idpc": "./dist/cli.cjs"
8
8
  },
9
9
  "files": [
10
- "dist",
11
- "skills"
10
+ "dist"
12
11
  ],
13
12
  "engines": {
14
13
  "node": ">=20"
@@ -47,7 +46,8 @@
47
46
  "tsup": "~8.5.1",
48
47
  "tsx": "~4.21.0",
49
48
  "typescript": "~5.7.2",
50
- "vitest": "~4.0.0"
49
+ "vitest": "~4.0.0",
50
+ "@atlas/cli-core": "0.0.0"
51
51
  },
52
52
  "dependencies": {
53
53
  "@clack/prompts": "~0.11.0",
@@ -1,171 +0,0 @@
1
- ---
2
- name: ideal-postcodes-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
- validate email addresses and phone numbers, and resolve specific addresses
7
- from partial queries via the `idpc` CLI.
8
- Use when the user wants to inspect or update an Ideal Postcodes account,
9
- cleanse addresses in bulk, validate emails or phone numbers, or pin down a
10
- specific address from a partial query. Always load this skill before running
11
- `idpc` — it defines the
12
- non-interactive flag contract and output shape that keep agent runs
13
- deterministic.
14
- license: SEE LICENSE IN LICENSE
15
- metadata:
16
- author: ideal-postcodes
17
- source: https://github.com/ideal-postcodes/atlas/tree/main/packages/cli-ideal
18
- envVars:
19
- - name: IDPC_API_KEY
20
- required: true
21
- description: Ideal Postcodes API key
22
- - name: IDPC_USER_TOKEN
23
- required: false
24
- description: Required for private key endpoints (details, usage, logs, configs)
25
- references:
26
- - auth.md
27
- - keys.md
28
- - cleanse.md
29
- - email.md
30
- - phone.md
31
- - find.md
32
- ---
33
-
34
- # Ideal Postcodes CLI (`idpc`)
35
-
36
- ## Installation
37
-
38
- ```bash
39
- npm install -g @ideal-postcodes/cli
40
- idpc --version
41
- ```
42
-
43
- ## Agent Protocol
44
-
45
- The CLI auto-detects non-TTY environments and emits JSON — no `--json` flag needed when piping or running headless.
46
-
47
- **Rules for agents:**
48
-
49
- - Supply ALL required flags. The CLI will NOT prompt when stdin is not a TTY.
50
- - `-q / --quiet` suppresses any status output and implies `--json`.
51
- - Exit `0` = success, `1` = error.
52
- - Both success and error JSON go to **stdout** — parse it uniformly, then check for an `error` key and the exit code:
53
- ```json
54
- {"error":{"code":"...","message":"...","details":{...}}}
55
- ```
56
- - Destructive commands (e.g. `keys configs delete`) require `--yes` in non-TTY.
57
- - Use env vars or flags. Never rely on `idpc auth login` from an agent.
58
-
59
- ## Authentication
60
-
61
- Two credentials: `api_key` (required) and `user_token` (required for `/keys/*` reads, configs, updates). Resolution precedence — per credential:
62
-
63
- | Priority | Source |
64
- |---|---|
65
- | 1 (highest) | `--api-key <k>` / `--user-token <t>` |
66
- | 2 | `IDPC_API_KEY` / `IDPC_USER_TOKEN` env var |
67
- | 3 (lowest) | `~/.config/ideal-postcodes/credentials.json` (written by `idpc auth login` / `idpc auth signup`) |
68
-
69
- Missing api_key → error code `missing_api_key`. Missing user_token on a command that needs it → `missing_user_token`.
70
-
71
- ## Global Flags
72
-
73
- | Flag | Description |
74
- |------|-------------|
75
- | `--api-key <k>` | Override API key for this invocation |
76
- | `--user-token <t>` | Override user token |
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`, `signup`, `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 email` | Validate one email, a file, or stdin |
89
- | `idpc phone` | Validate one phone number, a file, or stdin |
90
- | `idpc find` / `resolve` | Autocomplete then resolve a suggestion id to a full address (paired; see `find.md`) |
91
- | `idpc doctor` | Env + connectivity check |
92
-
93
- Read the matching reference file for flags and example output.
94
-
95
- ## Standing up a brand-new account: `idpc auth signup`
96
-
97
- `idpc auth signup` mints a one-shot `cli_token`, prints the prefilled Rails signup URL, and polls until the new account propagates. **The command intentionally pauses for a human step**: a person (the user, not the agent) must open the URL in a browser and complete the captcha + ToS. The CLI resumes automatically and writes credentials to the same store `idpc auth login` uses — `whoami` works after with no extra step.
98
-
99
- Required flags (non-interactive — supply all when scripting):
100
- `--email`, `--name`, `--org-name`, `--org-address-line-one`, `--org-post-town`, `--org-postcode`, `--org-country-code`.
101
-
102
- Optional: `--org-address-line-two`, `--org-address-line-three`. Polling is fixed at 3s with a 30-minute ceiling.
103
-
104
- Progress signals while polling (in JSON / non-TTY mode), one NDJSON event per line on **stderr**:
105
-
106
- ```jsonl
107
- {"event":"signup_url_issued","signup_url":"https://ideal-postcodes.co.uk/users/sign_up?...","expires_at":"..."}
108
- {"event":"waiting","elapsed_sec":30}
109
- {"event":"waiting","elapsed_sec":60}
110
- ```
111
-
112
- Final success JSON on stdout:
113
-
114
- ```json
115
- {"success":true,"config_path":"/home/you/.config/ideal-postcodes/credentials.json","email":"you@example.com","user_id":"..."}
116
- ```
117
-
118
- Exit codes: `0` success, `2` invalid input or rate-limited (`429` is not retried — bulk minting is what the limit prevents), `3` network error, `4` link expired or polling timeout, `130` SIGINT.
119
-
120
- Example invocation an agent can copy:
121
-
122
- ```bash
123
- idpc auth signup \
124
- --email you@example.com \
125
- --name "Your Name" \
126
- --org-name "Your Company Ltd" \
127
- --org-address-line-one "1 Example Street" \
128
- --org-post-town London \
129
- --org-postcode SW1A1AA \
130
- --org-country-code GB
131
- ```
132
-
133
- ## Common Pitfalls
134
-
135
- - **`user_token` is separate from `api_key`.** `keys details`, `keys usage`, `keys logs`, `keys update`, and all `configs` writes require both.
136
- - **`cleanse`, `email`, and `phone` cost paid lookups.** Public test key `iddqd` will return `auth_failed`.
137
- - **`cleanse` / `email` / `phone` batch mode emits CSV** unless `--json` is passed; a single query always emits JSON.
138
- - **`find` without a query in non-TTY errors.** Always pass a query when scripting.
139
- - **`keys logs` emits raw CSV**, not JSON, and rejects `--json` / `-q` with `invalid_input`. Redirect to a file or pipe into your CSV tooling.
140
- - **Credentials file is `0600`.** If your umask is unusual, `idpc auth login` may fail with `write_failed`.
141
-
142
- ## Quick Examples
143
-
144
- ```bash
145
- # Cleanse one address (JSON to stdout)
146
- idpc cleanse "10 downing street, london"
147
-
148
- # Batch cleanse
149
- cat addresses.txt | idpc cleanse --stdin
150
-
151
- # Validate an email or phone number
152
- idpc email "support@example.com"
153
- idpc phone "+442071128019" --carrier
154
-
155
- # Batch validate emails to a CSV
156
- cat emails.txt | idpc email --stdin > emails.csv
157
-
158
- # Find a specific address and resolve it
159
- ID=$(idpc find "10 downing" | jq -r '.suggestions[0].id')
160
- idpc resolve "$ID"
161
-
162
- # Inspect a key
163
- idpc keys details
164
-
165
- # Add an allowed URL
166
- idpc keys configs update web --allowed-urls https://example.com,https://www.example.com
167
- ```
168
-
169
- ## Full documentation
170
-
171
- The full Ideal Postcodes documentation — every guide, API reference, and integration — is available as a single file at [llms.txt](https://docs.ideal-postcodes.co.uk/llms.txt). Point your agent there for anything this skill doesn't cover.
@@ -1,126 +0,0 @@
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 signup`
6
-
7
- Mint a one-shot `cli_token`, print a prefilled signup URL, then poll the api until the new account propagates. On success, the test API key + user token are written to the same store `idpc auth login` uses.
8
-
9
- The command **pauses for a human step**: someone must open the printed URL in a browser and complete the captcha + ToS. The terminal resumes automatically when Rails finishes propagating the user.
10
-
11
- | Flag | Description |
12
- | --------------------------------- | ----------------------------------------------------------- |
13
- | `--email <email>` | Account holder email (required in non-interactive mode) |
14
- | `--name <name>` | Account holder full name (required in non-interactive mode) |
15
- | `--org-name <name>` | Organisation name (required) |
16
- | `--org-address-line-one <line>` | Organisation address line 1 (required) |
17
- | `--org-address-line-two <line>` | Optional address line 2 |
18
- | `--org-address-line-three <line>` | Optional address line 3 |
19
- | `--org-post-town <town>` | Organisation post town (required) |
20
- | `--org-postcode <postcode>` | Organisation postcode (required) |
21
- | `--org-country-code <iso2>` | Organisation country code, ISO 3166-1 alpha-2 (required) |
22
-
23
- Polling runs every 3 seconds and gives up after 30 minutes — both are fixed. Override the api host (rarely needed) with the global `--base-url`.
24
-
25
- Non-interactive (no TTY or `--json`): every required flag must be present; missing one returns `invalid_input` and exits 2. Interactive: prompts for missing required flags.
26
-
27
- ### Progress signals (JSON / non-TTY mode)
28
-
29
- NDJSON events on **stderr** so the final result on stdout stays a single JSON document:
30
-
31
- ```jsonl
32
- {"event":"signup_url_issued","signup_url":"https://ideal-postcodes.co.uk/users/sign_up?...","expires_at":"2026-05-18T18:30:00Z"}
33
- {"event":"waiting","elapsed_sec":30}
34
- ```
35
-
36
- ### Success output (stdout)
37
-
38
- ```json
39
- {
40
- "success": true,
41
- "config_path": "/home/you/.config/ideal-postcodes/credentials.json",
42
- "email": "you@example.com",
43
- "user_id": "..."
44
- }
45
- ```
46
-
47
- ### Exit codes
48
-
49
- - `0` — success
50
- - `2` — `invalid_input` (bad flags or 400 from api), `rate_limited` (429; not retried)
51
- - `3` — `network_error`
52
- - `4` — `signup_expired` (410 from api) or `timeout` (polling ceiling reached)
53
- - `130` — SIGINT (re-run the command to resume; the existing link is not recoverable)
54
-
55
- ### Example
56
-
57
- ```bash
58
- idpc auth signup \
59
- --email you@example.com \
60
- --name "Your Name" \
61
- --org-name "Your Company Ltd" \
62
- --org-address-line-one "1 Example Street" \
63
- --org-post-town London \
64
- --org-postcode SW1A1AA \
65
- --org-country-code GB
66
- ```
67
-
68
- ## `idpc auth login`
69
-
70
- Store an `api_key` (required) and `user_token` (optional) for later reuse. The api_key is verified against `GET /keys/{key}` before being written.
71
-
72
- | Flag | Description |
73
- | ------------------ | ------------------------------------------------------------- |
74
- | `--api-key <k>` | **Required** in non-interactive mode; prompted interactively. |
75
- | `--user-token <t>` | Optional. Unlocks `/keys/*` reads when present. |
76
-
77
- Non-interactive (no TTY or `--json`): `--api-key` is required; missing it returns `invalid_input`. `--user-token` is optional and stored only if supplied.
78
-
79
- Interactive: prompts for the api_key (required) then the user_token (press enter to skip). Both inputs are masked.
80
-
81
- ### Output
82
-
83
- ```json
84
- {
85
- "success": true,
86
- "config_path": "/home/you/.config/ideal-postcodes/credentials.json",
87
- "available": true
88
- }
89
- ```
90
-
91
- ### Error codes
92
-
93
- - `invalid_input` — non-interactive mode missing `--api-key`
94
- - `auth_failed` — API rejected the supplied credentials during verification
95
- - `write_failed` — unable to write credentials file
96
-
97
- ## `idpc auth logout`
98
-
99
- Remove the credentials file.
100
-
101
- ### Output
102
-
103
- ```json
104
- { "success": true, "removed": true, "config_path": "..." }
105
- ```
106
-
107
- `removed: false` means there was no file to remove — not an error.
108
-
109
- ## `idpc auth whoami`
110
-
111
- Show where each credential was resolved from and call `GET /keys/{key}` to verify the api_key is live.
112
-
113
- ### Output
114
-
115
- ```json
116
- {
117
- "api_key": { "source": "env", "preview": "ak_mpl…" },
118
- "user_token": { "source": "config", "preview": "uk_jc6…" },
119
- "live": true,
120
- "available": true
121
- }
122
- ```
123
-
124
- `source` is `flag`, `env`, or `config`. `preview` is the first 6 characters of the credential followed by `…`.
125
-
126
- Either credential may be `null` if it isn't configured. When `api_key` is `null` the API check is skipped — output omits `available` and reports `"live": false`.
@@ -1,69 +0,0 @@
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
- | `-o, --out <path>` | Write CSV to a file (batch mode only) |
18
- | `--context <iso3>` | ISO-3 country hint (GBR, USA, …) |
19
-
20
- Exactly one of: `[query]`, `--file`, `--stdin`. Requests are tagged `cli`.
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
- Multiple inputs emit CSV by default; pass `--json` for the shape above. A row
49
- that fails its lookup doesn't abort the batch: in CSV its `status` becomes
50
- `Error: <message>`; in JSON its entry is `{ query, error: { code, message } }`.
51
- The batch still exits `0`. Auth/permission failures (`auth_failed`,
52
- `forbidden`) are the exception: they abort the whole run.
53
-
54
- ## Agent patterns
55
-
56
- ```bash
57
- # Single
58
- idpc cleanse "10 downing street, london" | jq .response.result[0]
59
-
60
- # Batch
61
- cat messy.txt | idpc cleanse --stdin > clean.json
62
- ```
63
-
64
- ## Error codes
65
-
66
- - `missing_argument` — no `[query]`, `--file`, or `--stdin` supplied
67
- - `auth_failed` — invalid key, or key lacks paid cleanse permission
68
- - `rate_limited` — 30 req/sec per IP; back off
69
- - `invalid_input` — malformed body rejected by the API
@@ -1,75 +0,0 @@
1
- # `idpc email`
2
-
3
- Validate email addresses — `GET /emails`. Requires `api_key`. Each input counts as a paid lookup.
4
-
5
- ## Usage
6
-
7
- ```
8
- idpc email [options] [query]
9
- idpc email --file input.txt
10
- idpc email --stdin
11
- ```
12
-
13
- | Flag | Description |
14
- |---|---|
15
- | `-f, --file <path>` | Read one email per line |
16
- | `--stdin` | Read one email per line from stdin |
17
- | `-o, --out <path>` | Write CSV to a file (batch mode only) |
18
-
19
- Exactly one of: `[query]`, `--file`, `--stdin`. Requests are tagged `cli`.
20
-
21
- ## Output
22
-
23
- **Single input** (always JSON):
24
-
25
- ```json
26
- {
27
- "query": "support@example.com",
28
- "response": {
29
- "result": {
30
- "result": "deliverable",
31
- "deliverable": true,
32
- "disposable": false,
33
- "free": false,
34
- "role": true,
35
- "catchall": false,
36
- "suggestions": []
37
- }
38
- }
39
- }
40
- ```
41
-
42
- `result` is `"deliverable"` or `"not_deliverable"`. `suggestions` lists corrected spellings (e.g. a fixed typo'd domain).
43
-
44
- **Multiple inputs** (file or stdin) emit CSV by default; pass `--json` for the
45
- `{ count, results: [{ query, response }] }` shape. CSV columns:
46
-
47
- ```
48
- query,status,result,deliverable,disposable,free,role,catchall,suggestions
49
- ```
50
-
51
- A row that fails its lookup doesn't abort the batch: in CSV its `status`
52
- becomes `Error: <message>`; in JSON its entry is `{ query, error: { code, message } }`.
53
- The batch still exits `0` — filter on `status` / the `error` key to find failures.
54
- Auth/permission failures (`auth_failed`, `forbidden`) are the exception: they
55
- abort the whole run since every row would fail identically.
56
-
57
- ## Agent patterns
58
-
59
- ```bash
60
- # Single — is it deliverable?
61
- idpc email "support@example.com" | jq -r .response.result.result
62
-
63
- # Batch to CSV
64
- cat emails.txt | idpc email --stdin > emails.csv
65
-
66
- # Batch as JSON
67
- cat emails.txt | idpc email --stdin --json | jq '.results[] | select(.response.result.result != "deliverable")'
68
- ```
69
-
70
- ## Error codes
71
-
72
- - `missing_argument` — no `[query]`, `--file`, or `--stdin` supplied
73
- - `auth_failed` — invalid key, or key lacks paid email validation permission
74
- - `rate_limited` — back off and retry
75
- - `invalid_input` — malformed request rejected by the API
@@ -1,39 +0,0 @@
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
-
13
- **TTY (human):** prompts for input if no query, shows a `select` picker, auto-resolves the chosen suggestion, prints the full address.
14
-
15
- **Non-TTY (agent):** query is required. Emits suggestions as JSON:
16
-
17
- ```json
18
- {
19
- "count": 2,
20
- "suggestions": [
21
- { "id": "ABC123", "suggestion": "10 Downing Street, London, SW1A" },
22
- { "id": "DEF456", "suggestion": "11 Downing Street, London, SW1A" }
23
- ]
24
- }
25
- ```
26
-
27
- ## `idpc resolve <id>`
28
-
29
- `GET /autocomplete/addresses/{id}/gbr`.
30
-
31
- Returns the resolved address object.
32
-
33
- ## Agent pattern
34
-
35
- ```bash
36
- # Pick the top hit and resolve
37
- ID=$(idpc find "10 downing" | jq -r '.suggestions[0].id')
38
- idpc resolve "$ID"
39
- ```
@@ -1,96 +0,0 @@
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
- All subcommands except `keys get` **require a user_token**. The CLI preflights this before any HTTP call: if no user_token is found via `--user-token`, `IDPC_USER_TOKEN`, or `idpc auth login`, the command exits with `code: missing_user_token` and a hint pointing to those three sources.
8
-
9
- ## `idpc keys get [key]`
10
-
11
- Public availability info — `GET /keys/{key}`. No user_token attached (the response shape changes if one is present, so the CLI explicitly omits it even when available).
12
-
13
- ## `idpc keys details [key]`
14
-
15
- Private key details — `GET /keys/{key}/details`. **Requires user_token.**
16
-
17
- ## `idpc keys update [key]`
18
-
19
- Update key details — `PUT /keys/{key}/details`. **Requires user_token.**
20
-
21
- | Flag | Description |
22
- |---|---|
23
- | `--json-body <json>` | **Required.** Raw JSON body of fields to update. |
24
-
25
- ```bash
26
- idpc keys update --json-body '{"notifications":{"email":"ops@example.com"}}'
27
- ```
28
-
29
- ## `idpc keys usage [key]`
30
-
31
- Lookup counts over a date range — `GET /keys/{key}/usage`. **Requires user_token.**
32
-
33
- | Flag | Description |
34
- |---|---|
35
- | `--start <date>` | Start date (YYYY-MM-DD or ISO) |
36
- | `--end <date>` | End date |
37
- | `--tags <csv>` | Comma-separated tag filter |
38
- | `--licensee <id>` | Filter by licensee id |
39
-
40
- ## `idpc keys logs [key]`
41
-
42
- Paid lookup logs — `GET /keys/{key}/lookups`. Emits **raw CSV to stdout**. **Requires user_token.**
43
-
44
- | Flag | Description |
45
- |---|---|
46
- | `--start <date>` | Start date |
47
- | `--end <date>` | End date |
48
- | `--licensee <id>` | Filter by licensee id |
49
-
50
- This command is CSV-only and does not support `--json` / `-q` — passing either errors with `invalid_input`. Redirect to a file or pipe into CSV tooling:
51
-
52
- ```bash
53
- idpc keys logs --start 2026-01-01 --end 2026-01-31 > lookups.csv
54
- ```
55
-
56
- ## `idpc keys configs`
57
-
58
- All subcommands **require user_token** (including `get` and `list`).
59
-
60
- A config's `payload` is an opaque serialised-JSON **string** (matching the API's `ConfigNewParam` / `ConfigUpdateParam`). The CLI validates that it parses as JSON but does not interpret its contents.
61
-
62
- ### `list [key]`
63
-
64
- `GET /keys/{key}/configs` — list all configs.
65
-
66
- ### `get <config> [key]`
67
-
68
- `GET /keys/{key}/configs/{config}` — retrieve one.
69
-
70
- ### `create <name> [key]`
71
-
72
- `POST /keys/{key}/configs` — create a new config.
73
-
74
- | Flag | Description |
75
- |---|---|
76
- | `--payload <json>` | **Required.** Serialised config payload (JSON string). |
77
-
78
- ```bash
79
- idpc keys configs create my-site --payload '{"allowedUrls":["https://example.com"]}'
80
- ```
81
-
82
- ### `update <config> [key]`
83
-
84
- `POST /keys/{key}/configs/{config}` — update in place.
85
-
86
- | Flag | Description |
87
- |---|---|
88
- | `--payload <json>` | **Required.** Serialised config payload (JSON string). Replaces the existing payload. |
89
-
90
- ### `delete <config> [key]`
91
-
92
- `DELETE /keys/{key}/configs/{config}`. Requires `--yes` in non-TTY (or `--json`).
93
-
94
- | Flag | Description |
95
- |---|---|
96
- | `-y, --yes` | Skip confirmation |
@@ -1,80 +0,0 @@
1
- # `idpc phone`
2
-
3
- Validate phone numbers — `GET /phone_numbers`. Requires `api_key`. Each input counts as a paid lookup.
4
-
5
- ## Usage
6
-
7
- ```
8
- idpc phone [options] [query]
9
- idpc phone --file input.txt
10
- idpc phone --stdin
11
- ```
12
-
13
- | Flag | Description |
14
- |---|---|
15
- | `-f, --file <path>` | Read one phone number per line |
16
- | `--stdin` | Read one phone number per line from stdin |
17
- | `-o, --out <path>` | Write CSV to a file (batch mode only) |
18
- | `--carrier` | Look up the current network carrier (slower) |
19
-
20
- Exactly one of: `[query]`, `--file`, `--stdin`. Requests are tagged `cli`.
21
-
22
- Include the country code (e.g. `+442071128019`) for reliable parsing.
23
-
24
- ## Output
25
-
26
- **Single input** (always JSON):
27
-
28
- ```json
29
- {
30
- "query": "+442071128019",
31
- "response": {
32
- "result": {
33
- "valid": true,
34
- "national_format": "020 7112 8019",
35
- "international_format": "+44 20 7112 8019",
36
- "iso_country": "GBR",
37
- "iso_country_2": "GB",
38
- "country": "United Kingdom",
39
- "current_carrier": { "name": null },
40
- "original_carrier": { "name": "Invomo Ltd", "network_type": "landline" }
41
- }
42
- }
43
- }
44
- ```
45
-
46
- `current_carrier` is only populated when `--carrier` is passed (an HLR lookup that is slower and may cost more). Unparseable numbers return `"valid": false` with the format fields blank.
47
-
48
- **Multiple inputs** (file or stdin) emit CSV by default; pass `--json` for the
49
- `{ count, results: [{ query, response }] }` shape. CSV columns (carriers
50
- flattened to their name):
51
-
52
- ```
53
- query,status,valid,national_format,international_format,iso_country,iso_country_2,country,current_carrier,original_carrier
54
- ```
55
-
56
- A row that fails its lookup doesn't abort the batch: in CSV its `status`
57
- becomes `Error: <message>`; in JSON its entry is `{ query, error: { code, message } }`.
58
- The batch still exits `0` — filter on `status` / the `error` key to find failures.
59
- Auth/permission failures (`auth_failed`, `forbidden`) are the exception: they
60
- abort the whole run since every row would fail identically.
61
-
62
- ## Agent patterns
63
-
64
- ```bash
65
- # Single — is it valid?
66
- idpc phone "+442071128019" | jq .response.result.valid
67
-
68
- # Batch to CSV
69
- cat numbers.txt | idpc phone --stdin > numbers.csv
70
-
71
- # Filter invalid numbers from a batch
72
- cat numbers.txt | idpc phone --stdin --json | jq '.results[] | select(.response.result.valid == false) | .query'
73
- ```
74
-
75
- ## Error codes
76
-
77
- - `missing_argument` — no `[query]`, `--file`, or `--stdin` supplied
78
- - `auth_failed` — invalid key, or key lacks paid phone validation permission
79
- - `rate_limited` — back off and retry
80
- - `invalid_input` — malformed request rejected by the API