@ideal-postcodes/cli 0.1.0 → 0.3.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/README.md CHANGED
@@ -33,8 +33,16 @@ idpc cleanse "10 downing street, london"
33
33
  # Batch cleanse from a file
34
34
  cat addresses.txt | idpc cleanse --stdin > cleaned.json
35
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
+
36
43
  # Autocomplete then resolve
37
- idpc find "10 downing" --resolve
44
+ ID=$(idpc find "10 downing" | jq -r '.suggestions[0].id')
45
+ idpc resolve "$ID"
38
46
 
39
47
  # Manage allowed URLs
40
48
  idpc keys configs create web --allowed-urls https://example.com,https://www.example.com
@@ -58,6 +66,8 @@ The bundled [`skills/idpc-cli/`](./skills/idpc-cli/SKILL.md) teaches agents the
58
66
  | `idpc auth` | `login`, `logout`, `whoami` |
59
67
  | `idpc keys` | `get`, `details`, `update`, `usage`, `logs`, `configs {list,get,create,update,delete}` |
60
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 |
61
71
  | `idpc find` | Autocomplete (interactive in TTY, JSON in non-TTY) |
62
72
  | `idpc resolve` | Resolve a suggestion id to a full address |
63
73
  | `idpc doctor` | Env + connectivity check |
package/dist/cli.cjs CHANGED
@@ -1,17 +1,25 @@
1
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)}
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)}
4
4
  `);return}if(t.human){process.stdout.write(`${t.human(e)}
5
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(`
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
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(`
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="0.3.0";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(`
16
23
  `)||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)});
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)});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ideal-postcodes/cli",
3
3
  "description": "Ideal Postcodes CLI — idpc",
4
- "version": "0.1.0",
4
+ "version": "0.3.0",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "idpc": "./dist/cli.cjs"
@@ -10,16 +10,6 @@
10
10
  "dist",
11
11
  "skills"
12
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
13
  "engines": {
24
14
  "node": ">=20"
25
15
  },
@@ -52,15 +42,27 @@
52
42
  "agent"
53
43
  ],
54
44
  "devDependencies": {
55
- "@types/node": "catalog:",
56
- "tsup": "catalog:",
45
+ "@types/node": "~22.10.0",
46
+ "execa": "~9.6.0",
47
+ "tsup": "~8.5.1",
57
48
  "tsx": "~4.21.0",
58
- "typescript": "catalog:",
59
- "vitest": "catalog:"
49
+ "typescript": "~5.7.2",
50
+ "vitest": "~4.0.0"
60
51
  },
61
52
  "dependencies": {
62
53
  "@clack/prompts": "~0.11.0",
63
54
  "commander": "~14.0.0",
55
+ "fast-csv": "~5.0.7",
64
56
  "picocolors": "~1.1.1"
57
+ },
58
+ "scripts": {
59
+ "check-types": "tsgo --noEmit",
60
+ "test": "vitest run",
61
+ "test:watch": "vitest --watch",
62
+ "test:e2e": "pnpm build && vitest run --config vitest.e2e.config.ts",
63
+ "lint": "eslint src/",
64
+ "build": "tsup",
65
+ "clean": "rm -rf dist",
66
+ "dev": "tsx src/cli.ts"
65
67
  }
66
- }
68
+ }
@@ -3,10 +3,12 @@ name: idpc-cli
3
3
  description: >
4
4
  Drive api.ideal-postcodes.co.uk from the terminal — manage API keys
5
5
  (balance, usage, allowed-URL configs, lookup logs), cleanse messy addresses,
6
- and resolve specific addresses from partial queries via the `idpc` CLI.
6
+ validate email addresses and phone numbers, and resolve specific addresses
7
+ from partial queries via the `idpc` CLI.
7
8
  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
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
10
12
  non-interactive flag contract and output shape that keep agent runs
11
13
  deterministic.
12
14
  license: SEE LICENSE IN LICENSE
@@ -20,13 +22,12 @@ metadata:
20
22
  - name: IDPC_USER_TOKEN
21
23
  required: false
22
24
  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
25
  references:
27
26
  - auth.md
28
27
  - keys.md
29
28
  - cleanse.md
29
+ - email.md
30
+ - phone.md
30
31
  - find.md
31
32
  ---
32
33
 
@@ -63,7 +64,7 @@ Two credentials: `api_key` (required) and `user_token` (required for `/keys/*` r
63
64
  |---|---|
64
65
  | 1 (highest) | `--api-key <k>` / `--user-token <t>` |
65
66
  | 2 | `IDPC_API_KEY` / `IDPC_USER_TOKEN` env var |
66
- | 3 (lowest) | Active profile in `~/.config/ideal-postcodes/credentials.json` |
67
+ | 3 (lowest) | `~/.config/ideal-postcodes/credentials.json` (written by `idpc auth login` / `idpc auth signup`) |
67
68
 
68
69
  Missing api_key → error code `missing_api_key`. Missing user_token on a command that needs it → `missing_user_token`.
69
70
 
@@ -73,7 +74,6 @@ Missing api_key → error code `missing_api_key`. Missing user_token on a comman
73
74
  |------|-------------|
74
75
  | `--api-key <k>` | Override API key for this invocation |
75
76
  | `--user-token <t>` | Override user token |
76
- | `-p, --profile <name>` | Select a stored profile |
77
77
  | `--json` | Force JSON (auto in non-TTY) |
78
78
  | `-q, --quiet` | Suppress status, implies `--json` |
79
79
  | `--base-url <url>` | Override API base (diagnostics only) |
@@ -82,20 +82,61 @@ Missing api_key → error code `missing_api_key`. Missing user_token on a comman
82
82
 
83
83
  | Group | Subcommands |
84
84
  |---|---|
85
- | `idpc auth` | `login`, `logout`, `whoami` |
85
+ | `idpc auth` | `login`, `logout`, `signup`, `whoami` |
86
86
  | `idpc keys` | `get`, `details`, `update`, `usage`, `logs`, `configs {list,get,create,update,delete}` |
87
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 |
88
90
  | `idpc find` / `resolve` | Autocomplete then resolve a suggestion id to a full address (paired; see `find.md`) |
89
91
  | `idpc doctor` | Env + connectivity check |
90
92
 
91
93
  Read the matching reference file for flags and example output.
92
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
+
93
133
  ## Common Pitfalls
94
134
 
95
135
  - **`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`.
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.
97
138
  - **`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.
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.
99
140
  - **Credentials file is `0600`.** If your umask is unusual, `idpc auth login` may fail with `write_failed`.
100
141
 
101
142
  ## Quick Examples
@@ -107,8 +148,16 @@ idpc cleanse "10 downing street, london"
107
148
  # Batch cleanse
108
149
  cat addresses.txt | idpc cleanse --stdin
109
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
+
110
158
  # Find a specific address and resolve it
111
- idpc find "10 downing" --resolve
159
+ ID=$(idpc find "10 downing" | jq -r '.suggestions[0].id')
160
+ idpc resolve "$ID"
112
161
 
113
162
  # Inspect a key
114
163
  idpc keys details
@@ -2,28 +2,96 @@
2
2
 
3
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
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
+
5
68
  ## `idpc auth login`
6
69
 
7
- Store an `api_key` and `user_token` for later reuse.
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.
8
71
 
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) |
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. |
13
76
 
14
- Non-interactive (no TTY or `--json`): both flags required; missing either returns `invalid_input`.
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.
15
78
 
16
- Interactive: prompts for both via masked password input.
79
+ Interactive: prompts for the api_key (required) then the user_token (press enter to skip). Both inputs are masked.
17
80
 
18
81
  ### Output
19
82
 
20
83
  ```json
21
- { "success": true, "profile": "default", "config_path": "/home/you/.config/ideal-postcodes/credentials.json" }
84
+ {
85
+ "success": true,
86
+ "config_path": "/home/you/.config/ideal-postcodes/credentials.json",
87
+ "available": true
88
+ }
22
89
  ```
23
90
 
24
91
  ### Error codes
25
92
 
26
- - `invalid_input` — non-interactive mode missing `--api-key` or `--user-token`
93
+ - `invalid_input` — non-interactive mode missing `--api-key`
94
+ - `auth_failed` — API rejected the supplied credentials during verification
27
95
  - `write_failed` — unable to write credentials file
28
96
 
29
97
  ## `idpc auth logout`
@@ -46,11 +114,13 @@ Show where each credential was resolved from and call `GET /keys/{key}` to verif
46
114
 
47
115
  ```json
48
116
  {
49
- "api_key": { "source": "env", "preview": "ak_xxx…" },
50
- "user_token": { "source": "config", "profile": "default", "preview": "ut_xxx…" },
117
+ "api_key": { "source": "env", "preview": "ak_mpl…" },
118
+ "user_token": { "source": "config", "preview": "uk_jc6…" },
51
119
  "live": true,
52
- "availability": { /* GET /keys/{key} response */ }
120
+ "available": true
53
121
  }
54
122
  ```
55
123
 
56
- `source` is `flag`, `env`, or `config`.
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`.
@@ -14,10 +14,10 @@ idpc cleanse --stdin
14
14
  |---|---|
15
15
  | `-f, --file <path>` | Read one address per line |
16
16
  | `--stdin` | Read one address per line from stdin |
17
+ | `-o, --out <path>` | Write CSV to a file (batch mode only) |
17
18
  | `--context <iso3>` | ISO-3 country hint (GBR, USA, …) |
18
- | `--tags <csv>` | Tags recorded with the lookup |
19
19
 
20
- Exactly one of: `[query]`, `--file`, `--stdin`.
20
+ Exactly one of: `[query]`, `--file`, `--stdin`. Requests are tagged `cli`.
21
21
 
22
22
  ## Output
23
23
 
@@ -45,6 +45,12 @@ Exactly one of: `[query]`, `--file`, `--stdin`.
45
45
 
46
46
  Each `response` includes the IDPC `result` array and the confidence score. There is no absolute confidence threshold — decide per your dataset.
47
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
+
48
54
  ## Agent patterns
49
55
 
50
56
  ```bash
@@ -57,6 +63,7 @@ cat messy.txt | idpc cleanse --stdin > clean.json
57
63
 
58
64
  ## Error codes
59
65
 
66
+ - `missing_argument` — no `[query]`, `--file`, or `--stdin` supplied
60
67
  - `auth_failed` — invalid key, or key lacks paid cleanse permission
61
68
  - `rate_limited` — 30 req/sec per IP; back off
62
- - `invalid_input` — malformed body or missing query
69
+ - `invalid_input` — malformed body rejected by the API
@@ -0,0 +1,75 @@
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
@@ -9,7 +9,6 @@ Address autocomplete — two-step by design. Useful when you need to pin a speci
9
9
  | Flag | Description |
10
10
  |---|---|
11
11
  | `--country <iso3>` | Filter by ISO-3 (e.g. GBR, USA) |
12
- | `--resolve` | In non-TTY, auto-call resolve on each suggestion |
13
12
 
14
13
  **TTY (human):** prompts for input if no query, shows a `select` picker, auto-resolves the chosen suggestion, prints the full address.
15
14
 
@@ -25,25 +24,9 @@ Address autocomplete — two-step by design. Useful when you need to pin a speci
25
24
  }
26
25
  ```
27
26
 
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
27
  ## `idpc resolve <id>`
41
28
 
42
- `GET /autocomplete/addresses/{id}/{country}`.
43
-
44
- | Flag | Description |
45
- |---|---|
46
- | `--country <iso3>` | ISO-3 country code (default: `gbr`) |
29
+ `GET /autocomplete/addresses/{id}/gbr`.
47
30
 
48
31
  Returns the resolved address object.
49
32
 
@@ -53,7 +36,4 @@ Returns the resolved address object.
53
36
  # Pick the top hit and resolve
54
37
  ID=$(idpc find "10 downing" | jq -r '.suggestions[0].id')
55
38
  idpc resolve "$ID"
56
-
57
- # Or in one shot
58
- idpc find "10 downing" --resolve | jq '.results[0].address'
59
39
  ```
@@ -4,9 +4,11 @@ Inspect and manage API keys.
4
4
 
5
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
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
+
7
9
  ## `idpc keys get [key]`
8
10
 
9
- Public availability info — `GET /keys/{key}`. No user_token required.
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).
10
12
 
11
13
  ## `idpc keys details [key]`
12
14
 
@@ -18,11 +20,11 @@ Update key details — `PUT /keys/{key}/details`. **Requires user_token.**
18
20
 
19
21
  | Flag | Description |
20
22
  |---|---|
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 |
23
+ | `--json-body <json>` | **Required.** Raw JSON body of fields to update. |
24
24
 
25
- Must provide at least one field.
25
+ ```bash
26
+ idpc keys update --json-body '{"notifications":{"email":"ops@example.com"}}'
27
+ ```
26
28
 
27
29
  ## `idpc keys usage [key]`
28
30
 
@@ -45,14 +47,17 @@ Paid lookup logs — `GET /keys/{key}/lookups`. Emits **raw CSV to stdout**. **R
45
47
  | `--end <date>` | End date |
46
48
  | `--licensee <id>` | Filter by licensee id |
47
49
 
48
- Example:
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
+
49
52
  ```bash
50
53
  idpc keys logs --start 2026-01-01 --end 2026-01-31 > lookups.csv
51
54
  ```
52
55
 
53
- ## `idpc keys configs` — allowed-URL configs
56
+ ## `idpc keys configs`
57
+
58
+ All subcommands **require user_token** (including `get` and `list`).
54
59
 
55
- All subcommands **require user_token** (except `get`).
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.
56
61
 
57
62
  ### `list [key]`
58
63
 
@@ -62,14 +67,17 @@ All subcommands **require user_token** (except `get`).
62
67
 
63
68
  `GET /keys/{key}/configs/{config}` — retrieve one.
64
69
 
65
- ### `create <config> [key]`
70
+ ### `create <name> [key]`
66
71
 
67
72
  `POST /keys/{key}/configs` — create a new config.
68
73
 
69
74
  | Flag | Description |
70
75
  |---|---|
71
- | `--allowed-urls <csv>` | Comma-separated URLs |
72
- | `--json-body <json>` | Raw JSON merged into body |
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
+ ```
73
81
 
74
82
  ### `update <config> [key]`
75
83
 
@@ -77,14 +85,11 @@ All subcommands **require user_token** (except `get`).
77
85
 
78
86
  | Flag | Description |
79
87
  |---|---|
80
- | `--allowed-urls <csv>` | Replace allowed URLs |
81
- | `--json-body <json>` | Raw JSON merged |
82
-
83
- Must pass at least one.
88
+ | `--payload <json>` | **Required.** Serialised config payload (JSON string). Replaces the existing payload. |
84
89
 
85
90
  ### `delete <config> [key]`
86
91
 
87
- `DELETE /keys/{key}/configs/{config}`. Requires `--yes` in non-TTY.
92
+ `DELETE /keys/{key}/configs/{config}`. Requires `--yes` in non-TTY (or `--json`).
88
93
 
89
94
  | Flag | Description |
90
95
  |---|---|
@@ -0,0 +1,80 @@
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