├── .editorconfig ├── .eslintignore ├── .eslintrc.yml ├── .github └── workflows │ ├── main.yml │ └── release-please.yml ├── .gitignore ├── .prettierignore ├── .vscode ├── extensions.json └── settings.json ├── .yarn ├── plugins │ └── @yarnpkg │ │ ├── plugin-interactive-tools.cjs │ │ └── plugin-typescript.cjs ├── releases │ └── yarn-3.5.0.cjs └── sdks │ ├── eslint │ ├── bin │ │ └── eslint.js │ ├── lib │ │ └── api.js │ └── package.json │ ├── integrations.yml │ ├── prettier │ ├── index.js │ └── package.json │ └── typescript │ ├── bin │ ├── tsc │ └── tsserver │ ├── lib │ ├── tsc.js │ ├── tsserver.js │ ├── tsserverlibrary.js │ └── typescript.js │ └── package.json ├── .yarnrc.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package.json ├── src ├── index.ts ├── payloads │ ├── error.ts │ ├── index.ts │ └── v2 │ │ ├── auth.ts │ │ ├── index.ts │ │ ├── payment.ts │ │ └── usage.ts ├── rest │ ├── error.ts │ ├── index.ts │ └── v2 │ │ ├── auth.ts │ │ ├── index.ts │ │ ├── payment.ts │ │ └── usage.ts ├── routes │ ├── error.ts │ ├── index.ts │ ├── routify.ts │ └── v2 │ │ ├── auth.ts │ │ ├── index.ts │ │ ├── payment.ts │ │ └── usage.ts └── utils │ ├── index.ts │ └── language-code.ts ├── tsconfig.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | insert_final_newline = true 7 | trim_trailing_whitespace = true 8 | max_line_length = 120 9 | indent_style = tab 10 | indent_size = 2 11 | tab_width = 2 12 | quote_type = single 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false 16 | 17 | [*.yml] 18 | indent_style = space -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /.eslintrc.yml: -------------------------------------------------------------------------------- 1 | root: true 2 | extends: 3 | - '@pinetwork-js' 4 | - prettier 5 | plugins: 6 | - prettier 7 | parserOptions: 8 | project: tsconfig.json 9 | rules: 10 | prettier/prettier: error 11 | env: 12 | node: true 13 | es2022: true 14 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Continuous Integration 2 | on: 3 | push: 4 | branches: 5 | - main 6 | paths-ignore: 7 | - "*.{md,txt}" 8 | - LICENSE 9 | - .*config 10 | - .vscode 11 | tags-ignore: 12 | - "*" 13 | pull_request: 14 | branches: 15 | - "*" 16 | paths-ignore: 17 | - "*.{md,txt}" 18 | - LICENSE 19 | - .*config 20 | - .vscode 21 | 22 | jobs: 23 | main: 24 | runs-on: ubuntu-latest 25 | strategy: 26 | matrix: 27 | node-version: 28 | - "18" 29 | - "19" 30 | steps: 31 | - uses: actions/checkout@v2 32 | 33 | - name: Use Node.js v${{ matrix.node-version }} 34 | uses: actions/setup-node@v2 35 | with: 36 | node-version: ${{ matrix.node-version }} 37 | 38 | - name: Install dependencies 39 | run: yarn install --immutable 40 | 41 | - name: Build 42 | run: yarn build --noEmit 43 | 44 | - name: Lint 45 | run: yarn lint 46 | -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | name: Release Please 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | jobs: 8 | release-please: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: GoogleCloudPlatform/release-please-action@v2 12 | id: release 13 | with: 14 | token: ${{ secrets.GITHUB_TOKEN }} 15 | release-type: node 16 | default-branch: main 17 | pull-request-title-pattern: "chore${scope}: release${component} v${version}" 18 | bump-minor-pre-major: true 19 | changelog-types: '[{"type":"feat","section":"Features"},{"type":"fix","section":"Bug 20 | Fixes"},{"type":"perf","section":"Performance 21 | Improvements"},{"type":"deps","section":"Dependencies"},{"type":"revert","section":"Reverts"},{"type":"docs","section":"Documentation"},{"type":"style","section":"Styles","hidden":true},{"type":"chore","section":"Miscellaneous 22 | Chores","hidden":true},{"type":"refactor","section":"Code 23 | Refactoring","hidden":true},{"type":"test","section":"Tests","hidden":true},{"type":"ci","section":"Continuous 24 | Integration","hidden":true}]' 25 | 26 | - uses: actions/checkout@v2 27 | if: ${{ steps.release.outputs.release_created }} 28 | 29 | - name: Use Node.js v18 30 | uses: actions/setup-node@v2 31 | with: 32 | node-version: "18" 33 | registry-url: https://registry.npmjs.org 34 | if: ${{ steps.release.outputs.release_created }} 35 | 36 | - name: Install dependencies 37 | run: yarn install --immutable 38 | if: ${{ steps.release.outputs.release_created }} 39 | 40 | - name: Publish to NPM 41 | run: yarn npm publish --access public 42 | env: 43 | YARN_NPM_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 44 | if: ${{ steps.release.outputs.release_created }} 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Yarn 2 2 | .yarn/* 3 | !.yarn/patches 4 | !.yarn/plugins 5 | !.yarn/releases 6 | !.yarn/sdks 7 | !.yarn/versions 8 | .pnp.* 9 | 10 | # Logs 11 | logs 12 | *.log 13 | npm-debug.log* 14 | yarn-debug.log* 15 | yarn-error.log* 16 | lerna-debug.log* 17 | 18 | # Diagnostic reports (https://nodejs.org/api/report.html) 19 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 20 | 21 | # Runtime data 22 | pids 23 | *.pid 24 | *.seed 25 | *.pid.lock 26 | 27 | # Optional npm cache directory 28 | .npm 29 | 30 | # Optional eslint cache 31 | .eslintcache 32 | 33 | # Optional REPL history 34 | .node_repl_history 35 | 36 | # Output of 'npm pack' 37 | *.tgz 38 | 39 | # TypeScript 40 | *.tsbuildinfo 41 | build 42 | # Dependency directories 43 | node_modules -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | build 3 | .yarn 4 | .yarnrc.yml 5 | .pnp.* 6 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "arcanis.vscode-zipfs", 4 | "dbaeumer.vscode-eslint", 5 | "esbenp.prettier-vscode" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "search.exclude": { 3 | "**/.yarn": true, 4 | "**/.pnp.*": true 5 | }, 6 | "eslint.nodePath": ".yarn/sdks", 7 | "prettier.prettierPath": ".yarn/sdks/prettier/index.js", 8 | "typescript.tsdk": ".yarn/sdks/typescript/lib", 9 | "typescript.enablePromptUseWorkspaceTsdk": true 10 | } 11 | -------------------------------------------------------------------------------- /.yarn/plugins/@yarnpkg/plugin-typescript.cjs: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | //prettier-ignore 3 | module.exports = { 4 | name: "@yarnpkg/plugin-typescript", 5 | factory: function (require) { 6 | var plugin=(()=>{var Ft=Object.create,H=Object.defineProperty,Bt=Object.defineProperties,Kt=Object.getOwnPropertyDescriptor,zt=Object.getOwnPropertyDescriptors,Gt=Object.getOwnPropertyNames,Q=Object.getOwnPropertySymbols,$t=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,De=Object.prototype.propertyIsEnumerable;var Re=(e,t,r)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,u=(e,t)=>{for(var r in t||(t={}))ne.call(t,r)&&Re(e,r,t[r]);if(Q)for(var r of Q(t))De.call(t,r)&&Re(e,r,t[r]);return e},g=(e,t)=>Bt(e,zt(t)),Lt=e=>H(e,"__esModule",{value:!0});var R=(e,t)=>{var r={};for(var s in e)ne.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(e!=null&&Q)for(var s of Q(e))t.indexOf(s)<0&&De.call(e,s)&&(r[s]=e[s]);return r};var I=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vt=(e,t)=>{for(var r in t)H(e,r,{get:t[r],enumerable:!0})},Qt=(e,t,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Gt(t))!ne.call(e,s)&&s!=="default"&&H(e,s,{get:()=>t[s],enumerable:!(r=Kt(t,s))||r.enumerable});return e},C=e=>Qt(Lt(H(e!=null?Ft($t(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);var xe=I(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});function _(e){let t=[...e.caches],r=t.shift();return r===void 0?ve():{get(s,n,a={miss:()=>Promise.resolve()}){return r.get(s,n,a).catch(()=>_({caches:t}).get(s,n,a))},set(s,n){return r.set(s,n).catch(()=>_({caches:t}).set(s,n))},delete(s){return r.delete(s).catch(()=>_({caches:t}).delete(s))},clear(){return r.clear().catch(()=>_({caches:t}).clear())}}}function ve(){return{get(e,t,r={miss:()=>Promise.resolve()}){return t().then(n=>Promise.all([n,r.miss(n)])).then(([n])=>n)},set(e,t){return Promise.resolve(t)},delete(e){return Promise.resolve()},clear(){return Promise.resolve()}}}J.createFallbackableCache=_;J.createNullCache=ve});var Ee=I(($s,qe)=>{qe.exports=xe()});var Te=I(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});function Jt(e={serializable:!0}){let t={};return{get(r,s,n={miss:()=>Promise.resolve()}){let a=JSON.stringify(r);if(a in t)return Promise.resolve(e.serializable?JSON.parse(t[a]):t[a]);let o=s(),d=n&&n.miss||(()=>Promise.resolve());return o.then(y=>d(y)).then(()=>o)},set(r,s){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(s):s,Promise.resolve(s)},delete(r){return delete t[JSON.stringify(r)],Promise.resolve()},clear(){return t={},Promise.resolve()}}}ae.createInMemoryCache=Jt});var we=I((Vs,Me)=>{Me.exports=Te()});var Ce=I(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});function Xt(e,t,r){let s={"x-algolia-api-key":r,"x-algolia-application-id":t};return{headers(){return e===oe.WithinHeaders?s:{}},queryParameters(){return e===oe.WithinQueryParameters?s:{}}}}function Yt(e){let t=0,r=()=>(t++,new Promise(s=>{setTimeout(()=>{s(e(r))},Math.min(100*t,1e3))}));return e(r)}function ke(e,t=(r,s)=>Promise.resolve()){return Object.assign(e,{wait(r){return ke(e.then(s=>Promise.all([t(s,r),s])).then(s=>s[1]))}})}function Zt(e){let t=e.length-1;for(t;t>0;t--){let r=Math.floor(Math.random()*(t+1)),s=e[t];e[t]=e[r],e[r]=s}return e}function er(e,t){return Object.keys(t!==void 0?t:{}).forEach(r=>{e[r]=t[r](e)}),e}function tr(e,...t){let r=0;return e.replace(/%s/g,()=>encodeURIComponent(t[r++]))}var rr="4.2.0",sr=e=>()=>e.transporter.requester.destroy(),oe={WithinQueryParameters:0,WithinHeaders:1};M.AuthMode=oe;M.addMethods=er;M.createAuth=Xt;M.createRetryablePromise=Yt;M.createWaitablePromise=ke;M.destroy=sr;M.encode=tr;M.shuffle=Zt;M.version=rr});var F=I((Js,Ue)=>{Ue.exports=Ce()});var Ne=I(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});var nr={Delete:"DELETE",Get:"GET",Post:"POST",Put:"PUT"};ie.MethodEnum=nr});var B=I((Ys,We)=>{We.exports=Ne()});var Ze=I(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});var He=B();function ce(e,t){let r=e||{},s=r.data||{};return Object.keys(r).forEach(n=>{["timeout","headers","queryParameters","data","cacheable"].indexOf(n)===-1&&(s[n]=r[n])}),{data:Object.entries(s).length>0?s:void 0,timeout:r.timeout||t,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var X={Read:1,Write:2,Any:3},U={Up:1,Down:2,Timeouted:3},_e=2*60*1e3;function ue(e,t=U.Up){return g(u({},e),{status:t,lastUpdate:Date.now()})}function Fe(e){return e.status===U.Up||Date.now()-e.lastUpdate>_e}function Be(e){return e.status===U.Timeouted&&Date.now()-e.lastUpdate<=_e}function le(e){return{protocol:e.protocol||"https",url:e.url,accept:e.accept||X.Any}}function ar(e,t){return Promise.all(t.map(r=>e.get(r,()=>Promise.resolve(ue(r))))).then(r=>{let s=r.filter(d=>Fe(d)),n=r.filter(d=>Be(d)),a=[...s,...n],o=a.length>0?a.map(d=>le(d)):t;return{getTimeout(d,y){return(n.length===0&&d===0?1:n.length+3+d)*y},statelessHosts:o}})}var or=({isTimedOut:e,status:t})=>!e&&~~t==0,ir=e=>{let t=e.status;return e.isTimedOut||or(e)||~~(t/100)!=2&&~~(t/100)!=4},cr=({status:e})=>~~(e/100)==2,ur=(e,t)=>ir(e)?t.onRetry(e):cr(e)?t.onSucess(e):t.onFail(e);function Qe(e,t,r,s){let n=[],a=$e(r,s),o=Le(e,s),d=r.method,y=r.method!==He.MethodEnum.Get?{}:u(u({},r.data),s.data),b=u(u(u({"x-algolia-agent":e.userAgent.value},e.queryParameters),y),s.queryParameters),f=0,p=(h,S)=>{let O=h.pop();if(O===void 0)throw Ve(de(n));let P={data:a,headers:o,method:d,url:Ge(O,r.path,b),connectTimeout:S(f,e.timeouts.connect),responseTimeout:S(f,s.timeout)},x=j=>{let T={request:P,response:j,host:O,triesLeft:h.length};return n.push(T),T},v={onSucess:j=>Ke(j),onRetry(j){let T=x(j);return j.isTimedOut&&f++,Promise.all([e.logger.info("Retryable failure",pe(T)),e.hostsCache.set(O,ue(O,j.isTimedOut?U.Timeouted:U.Down))]).then(()=>p(h,S))},onFail(j){throw x(j),ze(j,de(n))}};return e.requester.send(P).then(j=>ur(j,v))};return ar(e.hostsCache,t).then(h=>p([...h.statelessHosts].reverse(),h.getTimeout))}function lr(e){let{hostsCache:t,logger:r,requester:s,requestsCache:n,responsesCache:a,timeouts:o,userAgent:d,hosts:y,queryParameters:b,headers:f}=e,p={hostsCache:t,logger:r,requester:s,requestsCache:n,responsesCache:a,timeouts:o,userAgent:d,headers:f,queryParameters:b,hosts:y.map(h=>le(h)),read(h,S){let O=ce(S,p.timeouts.read),P=()=>Qe(p,p.hosts.filter(j=>(j.accept&X.Read)!=0),h,O);if((O.cacheable!==void 0?O.cacheable:h.cacheable)!==!0)return P();let v={request:h,mappedRequestOptions:O,transporter:{queryParameters:p.queryParameters,headers:p.headers}};return p.responsesCache.get(v,()=>p.requestsCache.get(v,()=>p.requestsCache.set(v,P()).then(j=>Promise.all([p.requestsCache.delete(v),j]),j=>Promise.all([p.requestsCache.delete(v),Promise.reject(j)])).then(([j,T])=>T)),{miss:j=>p.responsesCache.set(v,j)})},write(h,S){return Qe(p,p.hosts.filter(O=>(O.accept&X.Write)!=0),h,ce(S,p.timeouts.write))}};return p}function dr(e){let t={value:`Algolia for JavaScript (${e})`,add(r){let s=`; ${r.segment}${r.version!==void 0?` (${r.version})`:""}`;return t.value.indexOf(s)===-1&&(t.value=`${t.value}${s}`),t}};return t}function Ke(e){try{return JSON.parse(e.content)}catch(t){throw Je(t.message,e)}}function ze({content:e,status:t},r){let s=e;try{s=JSON.parse(e).message}catch(n){}return Xe(s,t,r)}function pr(e,...t){let r=0;return e.replace(/%s/g,()=>encodeURIComponent(t[r++]))}function Ge(e,t,r){let s=Ye(r),n=`${e.protocol}://${e.url}/${t.charAt(0)==="/"?t.substr(1):t}`;return s.length&&(n+=`?${s}`),n}function Ye(e){let t=r=>Object.prototype.toString.call(r)==="[object Object]"||Object.prototype.toString.call(r)==="[object Array]";return Object.keys(e).map(r=>pr("%s=%s",r,t(e[r])?JSON.stringify(e[r]):e[r])).join("&")}function $e(e,t){if(e.method===He.MethodEnum.Get||e.data===void 0&&t.data===void 0)return;let r=Array.isArray(e.data)?e.data:u(u({},e.data),t.data);return JSON.stringify(r)}function Le(e,t){let r=u(u({},e.headers),t.headers),s={};return Object.keys(r).forEach(n=>{let a=r[n];s[n.toLowerCase()]=a}),s}function de(e){return e.map(t=>pe(t))}function pe(e){let t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return g(u({},e),{request:g(u({},e.request),{headers:u(u({},e.request.headers),t)})})}function Xe(e,t,r){return{name:"ApiError",message:e,status:t,transporterStackTrace:r}}function Je(e,t){return{name:"DeserializationError",message:e,response:t}}function Ve(e){return{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.",transporterStackTrace:e}}A.CallEnum=X;A.HostStatusEnum=U;A.createApiError=Xe;A.createDeserializationError=Je;A.createMappedRequestOptions=ce;A.createRetryError=Ve;A.createStatefulHost=ue;A.createStatelessHost=le;A.createTransporter=lr;A.createUserAgent=dr;A.deserializeFailure=ze;A.deserializeSuccess=Ke;A.isStatefulHostTimeouted=Be;A.isStatefulHostUp=Fe;A.serializeData=$e;A.serializeHeaders=Le;A.serializeQueryParameters=Ye;A.serializeUrl=Ge;A.stackFrameWithoutCredentials=pe;A.stackTraceWithoutCredentials=de});var K=I((en,et)=>{et.exports=Ze()});var tt=I(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});var N=F(),mr=K(),z=B(),hr=e=>{let t=e.region||"us",r=N.createAuth(N.AuthMode.WithinHeaders,e.appId,e.apiKey),s=mr.createTransporter(g(u({hosts:[{url:`analytics.${t}.algolia.com`}]},e),{headers:u(g(u({},r.headers()),{"content-type":"application/json"}),e.headers),queryParameters:u(u({},r.queryParameters()),e.queryParameters)})),n=e.appId;return N.addMethods({appId:n,transporter:s},e.methods)},yr=e=>(t,r)=>e.transporter.write({method:z.MethodEnum.Post,path:"2/abtests",data:t},r),gr=e=>(t,r)=>e.transporter.write({method:z.MethodEnum.Delete,path:N.encode("2/abtests/%s",t)},r),fr=e=>(t,r)=>e.transporter.read({method:z.MethodEnum.Get,path:N.encode("2/abtests/%s",t)},r),br=e=>t=>e.transporter.read({method:z.MethodEnum.Get,path:"2/abtests"},t),Pr=e=>(t,r)=>e.transporter.write({method:z.MethodEnum.Post,path:N.encode("2/abtests/%s/stop",t)},r);w.addABTest=yr;w.createAnalyticsClient=hr;w.deleteABTest=gr;w.getABTest=fr;w.getABTests=br;w.stopABTest=Pr});var st=I((rn,rt)=>{rt.exports=tt()});var at=I(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});var me=F(),jr=K(),nt=B(),Or=e=>{let t=e.region||"us",r=me.createAuth(me.AuthMode.WithinHeaders,e.appId,e.apiKey),s=jr.createTransporter(g(u({hosts:[{url:`recommendation.${t}.algolia.com`}]},e),{headers:u(g(u({},r.headers()),{"content-type":"application/json"}),e.headers),queryParameters:u(u({},r.queryParameters()),e.queryParameters)}));return me.addMethods({appId:e.appId,transporter:s},e.methods)},Ir=e=>t=>e.transporter.read({method:nt.MethodEnum.Get,path:"1/strategies/personalization"},t),Ar=e=>(t,r)=>e.transporter.write({method:nt.MethodEnum.Post,path:"1/strategies/personalization",data:t},r);G.createRecommendationClient=Or;G.getPersonalizationStrategy=Ir;G.setPersonalizationStrategy=Ar});var it=I((nn,ot)=>{ot.exports=at()});var jt=I(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0});var l=F(),q=K(),m=B(),Sr=require("crypto");function Y(e){let t=r=>e.request(r).then(s=>{if(e.batch!==void 0&&e.batch(s.hits),!e.shouldStop(s))return s.cursor?t({cursor:s.cursor}):t({page:(r.page||0)+1})});return t({})}var Dr=e=>{let t=e.appId,r=l.createAuth(e.authMode!==void 0?e.authMode:l.AuthMode.WithinHeaders,t,e.apiKey),s=q.createTransporter(g(u({hosts:[{url:`${t}-dsn.algolia.net`,accept:q.CallEnum.Read},{url:`${t}.algolia.net`,accept:q.CallEnum.Write}].concat(l.shuffle([{url:`${t}-1.algolianet.com`},{url:`${t}-2.algolianet.com`},{url:`${t}-3.algolianet.com`}]))},e),{headers:u(g(u({},r.headers()),{"content-type":"application/x-www-form-urlencoded"}),e.headers),queryParameters:u(u({},r.queryParameters()),e.queryParameters)})),n={transporter:s,appId:t,addAlgoliaAgent(a,o){s.userAgent.add({segment:a,version:o})},clearCache(){return Promise.all([s.requestsCache.clear(),s.responsesCache.clear()]).then(()=>{})}};return l.addMethods(n,e.methods)};function ct(){return{name:"MissingObjectIDError",message:"All objects must have an unique objectID (like a primary key) to be valid. Algolia is also able to generate objectIDs automatically but *it's not recommended*. To do it, use the `{'autoGenerateObjectIDIfNotExist': true}` option."}}function ut(){return{name:"ObjectNotFoundError",message:"Object not found."}}function lt(){return{name:"ValidUntilNotFoundError",message:"ValidUntil not found in given secured api key."}}var Rr=e=>(t,r)=>{let d=r||{},{queryParameters:s}=d,n=R(d,["queryParameters"]),a=u({acl:t},s!==void 0?{queryParameters:s}:{}),o=(y,b)=>l.createRetryablePromise(f=>$(e)(y.key,b).catch(p=>{if(p.status!==404)throw p;return f()}));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:"1/keys",data:a},n),o)},vr=e=>(t,r,s)=>{let n=q.createMappedRequestOptions(s);return n.queryParameters["X-Algolia-User-ID"]=t,e.transporter.write({method:m.MethodEnum.Post,path:"1/clusters/mapping",data:{cluster:r}},n)},xr=e=>(t,r,s)=>e.transporter.write({method:m.MethodEnum.Post,path:"1/clusters/mapping/batch",data:{users:t,cluster:r}},s),Z=e=>(t,r,s)=>{let n=(a,o)=>L(e)(t,{methods:{waitTask:D}}).waitTask(a.taskID,o);return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/operation",t),data:{operation:"copy",destination:r}},s),n)},qr=e=>(t,r,s)=>Z(e)(t,r,g(u({},s),{scope:[ee.Rules]})),Er=e=>(t,r,s)=>Z(e)(t,r,g(u({},s),{scope:[ee.Settings]})),Tr=e=>(t,r,s)=>Z(e)(t,r,g(u({},s),{scope:[ee.Synonyms]})),Mr=e=>(t,r)=>{let s=(n,a)=>l.createRetryablePromise(o=>$(e)(t,a).then(o).catch(d=>{if(d.status!==404)throw d}));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Delete,path:l.encode("1/keys/%s",t)},r),s)},wr=()=>(e,t)=>{let r=q.serializeQueryParameters(t),s=Sr.createHmac("sha256",e).update(r).digest("hex");return Buffer.from(s+r).toString("base64")},$=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/keys/%s",t)},r),kr=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/logs"},t),Cr=()=>e=>{let t=Buffer.from(e,"base64").toString("ascii"),r=/validUntil=(\d+)/,s=t.match(r);if(s===null)throw lt();return parseInt(s[1],10)-Math.round(new Date().getTime()/1e3)},Ur=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/clusters/mapping/top"},t),Nr=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/clusters/mapping/%s",t)},r),Wr=e=>t=>{let n=t||{},{retrieveMappings:r}=n,s=R(n,["retrieveMappings"]);return r===!0&&(s.getClusters=!0),e.transporter.read({method:m.MethodEnum.Get,path:"1/clusters/mapping/pending"},s)},L=e=>(t,r={})=>{let s={transporter:e.transporter,appId:e.appId,indexName:t};return l.addMethods(s,r.methods)},Hr=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/keys"},t),_r=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/clusters"},t),Fr=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/indexes"},t),Br=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/clusters/mapping"},t),Kr=e=>(t,r,s)=>{let n=(a,o)=>L(e)(t,{methods:{waitTask:D}}).waitTask(a.taskID,o);return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/operation",t),data:{operation:"move",destination:r}},s),n)},zr=e=>(t,r)=>{let s=(n,a)=>Promise.all(Object.keys(n.taskID).map(o=>L(e)(o,{methods:{waitTask:D}}).waitTask(n.taskID[o],a)));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:"1/indexes/*/batch",data:{requests:t}},r),s)},Gr=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:"1/indexes/*/objects",data:{requests:t}},r),$r=e=>(t,r)=>{let s=t.map(n=>g(u({},n),{params:q.serializeQueryParameters(n.params||{})}));return e.transporter.read({method:m.MethodEnum.Post,path:"1/indexes/*/queries",data:{requests:s},cacheable:!0},r)},Lr=e=>(t,r)=>Promise.all(t.map(s=>{let d=s.params,{facetName:n,facetQuery:a}=d,o=R(d,["facetName","facetQuery"]);return L(e)(s.indexName,{methods:{searchForFacetValues:dt}}).searchForFacetValues(n,a,u(u({},r),o))})),Vr=e=>(t,r)=>{let s=q.createMappedRequestOptions(r);return s.queryParameters["X-Algolia-User-ID"]=t,e.transporter.write({method:m.MethodEnum.Delete,path:"1/clusters/mapping"},s)},Qr=e=>(t,r)=>{let s=(n,a)=>l.createRetryablePromise(o=>$(e)(t,a).catch(d=>{if(d.status!==404)throw d;return o()}));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/keys/%s/restore",t)},r),s)},Jr=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:"1/clusters/mapping/search",data:{query:t}},r),Xr=e=>(t,r)=>{let s=Object.assign({},r),f=r||{},{queryParameters:n}=f,a=R(f,["queryParameters"]),o=n?{queryParameters:n}:{},d=["acl","indexes","referers","restrictSources","queryParameters","description","maxQueriesPerIPPerHour","maxHitsPerQuery"],y=p=>Object.keys(s).filter(h=>d.indexOf(h)!==-1).every(h=>p[h]===s[h]),b=(p,h)=>l.createRetryablePromise(S=>$(e)(t,h).then(O=>y(O)?Promise.resolve():S()));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Put,path:l.encode("1/keys/%s",t),data:o},a),b)},pt=e=>(t,r)=>{let s=(n,a)=>D(e)(n.taskID,a);return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/batch",e.indexName),data:{requests:t}},r),s)},Yr=e=>t=>Y(g(u({},t),{shouldStop:r=>r.cursor===void 0,request:r=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/browse",e.indexName),data:r},t)})),Zr=e=>t=>{let r=u({hitsPerPage:1e3},t);return Y(g(u({},r),{shouldStop:s=>s.hits.lengthg(u({},n),{hits:n.hits.map(a=>(delete a._highlightResult,a))}))}}))},es=e=>t=>{let r=u({hitsPerPage:1e3},t);return Y(g(u({},r),{shouldStop:s=>s.hits.lengthg(u({},n),{hits:n.hits.map(a=>(delete a._highlightResult,a))}))}}))},te=e=>(t,r,s)=>{let y=s||{},{batchSize:n}=y,a=R(y,["batchSize"]),o={taskIDs:[],objectIDs:[]},d=(b=0)=>{let f=[],p;for(p=b;p({action:r,body:h})),a).then(h=>(o.objectIDs=o.objectIDs.concat(h.objectIDs),o.taskIDs.push(h.taskID),p++,d(p)))};return l.createWaitablePromise(d(),(b,f)=>Promise.all(b.taskIDs.map(p=>D(e)(p,f))))},ts=e=>t=>l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/clear",e.indexName)},t),(r,s)=>D(e)(r.taskID,s)),rs=e=>t=>{let a=t||{},{forwardToReplicas:r}=a,s=R(a,["forwardToReplicas"]),n=q.createMappedRequestOptions(s);return r&&(n.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/rules/clear",e.indexName)},n),(o,d)=>D(e)(o.taskID,d))},ss=e=>t=>{let a=t||{},{forwardToReplicas:r}=a,s=R(a,["forwardToReplicas"]),n=q.createMappedRequestOptions(s);return r&&(n.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/synonyms/clear",e.indexName)},n),(o,d)=>D(e)(o.taskID,d))},ns=e=>(t,r)=>l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/deleteByQuery",e.indexName),data:t},r),(s,n)=>D(e)(s.taskID,n)),as=e=>t=>l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Delete,path:l.encode("1/indexes/%s",e.indexName)},t),(r,s)=>D(e)(r.taskID,s)),os=e=>(t,r)=>l.createWaitablePromise(yt(e)([t],r).then(s=>({taskID:s.taskIDs[0]})),(s,n)=>D(e)(s.taskID,n)),yt=e=>(t,r)=>{let s=t.map(n=>({objectID:n}));return te(e)(s,k.DeleteObject,r)},is=e=>(t,r)=>{let o=r||{},{forwardToReplicas:s}=o,n=R(o,["forwardToReplicas"]),a=q.createMappedRequestOptions(n);return s&&(a.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Delete,path:l.encode("1/indexes/%s/rules/%s",e.indexName,t)},a),(d,y)=>D(e)(d.taskID,y))},cs=e=>(t,r)=>{let o=r||{},{forwardToReplicas:s}=o,n=R(o,["forwardToReplicas"]),a=q.createMappedRequestOptions(n);return s&&(a.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Delete,path:l.encode("1/indexes/%s/synonyms/%s",e.indexName,t)},a),(d,y)=>D(e)(d.taskID,y))},us=e=>t=>gt(e)(t).then(()=>!0).catch(r=>{if(r.status!==404)throw r;return!1}),ls=e=>(t,r)=>{let y=r||{},{query:s,paginate:n}=y,a=R(y,["query","paginate"]),o=0,d=()=>ft(e)(s||"",g(u({},a),{page:o})).then(b=>{for(let[f,p]of Object.entries(b.hits))if(t(p))return{object:p,position:parseInt(f,10),page:o};if(o++,n===!1||o>=b.nbPages)throw ut();return d()});return d()},ds=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/%s",e.indexName,t)},r),ps=()=>(e,t)=>{for(let[r,s]of Object.entries(e.hits))if(s.objectID===t)return parseInt(r,10);return-1},ms=e=>(t,r)=>{let o=r||{},{attributesToRetrieve:s}=o,n=R(o,["attributesToRetrieve"]),a=t.map(d=>u({indexName:e.indexName,objectID:d},s?{attributesToRetrieve:s}:{}));return e.transporter.read({method:m.MethodEnum.Post,path:"1/indexes/*/objects",data:{requests:a}},n)},hs=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/rules/%s",e.indexName,t)},r),gt=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/settings",e.indexName),data:{getVersion:2}},t),ys=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/synonyms/%s",e.indexName,t)},r),bt=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/task/%s",e.indexName,t.toString())},r),gs=e=>(t,r)=>l.createWaitablePromise(Pt(e)([t],r).then(s=>({objectID:s.objectIDs[0],taskID:s.taskIDs[0]})),(s,n)=>D(e)(s.taskID,n)),Pt=e=>(t,r)=>{let o=r||{},{createIfNotExists:s}=o,n=R(o,["createIfNotExists"]),a=s?k.PartialUpdateObject:k.PartialUpdateObjectNoCreate;return te(e)(t,a,n)},fs=e=>(t,r)=>{let O=r||{},{safe:s,autoGenerateObjectIDIfNotExist:n,batchSize:a}=O,o=R(O,["safe","autoGenerateObjectIDIfNotExist","batchSize"]),d=(P,x,v,j)=>l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/operation",P),data:{operation:v,destination:x}},j),(T,V)=>D(e)(T.taskID,V)),y=Math.random().toString(36).substring(7),b=`${e.indexName}_tmp_${y}`,f=he({appId:e.appId,transporter:e.transporter,indexName:b}),p=[],h=d(e.indexName,b,"copy",g(u({},o),{scope:["settings","synonyms","rules"]}));p.push(h);let S=(s?h.wait(o):h).then(()=>{let P=f(t,g(u({},o),{autoGenerateObjectIDIfNotExist:n,batchSize:a}));return p.push(P),s?P.wait(o):P}).then(()=>{let P=d(b,e.indexName,"move",o);return p.push(P),s?P.wait(o):P}).then(()=>Promise.all(p)).then(([P,x,v])=>({objectIDs:x.objectIDs,taskIDs:[P.taskID,...x.taskIDs,v.taskID]}));return l.createWaitablePromise(S,(P,x)=>Promise.all(p.map(v=>v.wait(x))))},bs=e=>(t,r)=>ye(e)(t,g(u({},r),{clearExistingRules:!0})),Ps=e=>(t,r)=>ge(e)(t,g(u({},r),{replaceExistingSynonyms:!0})),js=e=>(t,r)=>l.createWaitablePromise(he(e)([t],r).then(s=>({objectID:s.objectIDs[0],taskID:s.taskIDs[0]})),(s,n)=>D(e)(s.taskID,n)),he=e=>(t,r)=>{let o=r||{},{autoGenerateObjectIDIfNotExist:s}=o,n=R(o,["autoGenerateObjectIDIfNotExist"]),a=s?k.AddObject:k.UpdateObject;if(a===k.UpdateObject){for(let d of t)if(d.objectID===void 0)return l.createWaitablePromise(Promise.reject(ct()))}return te(e)(t,a,n)},Os=e=>(t,r)=>ye(e)([t],r),ye=e=>(t,r)=>{let d=r||{},{forwardToReplicas:s,clearExistingRules:n}=d,a=R(d,["forwardToReplicas","clearExistingRules"]),o=q.createMappedRequestOptions(a);return s&&(o.queryParameters.forwardToReplicas=1),n&&(o.queryParameters.clearExistingRules=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/rules/batch",e.indexName),data:t},o),(y,b)=>D(e)(y.taskID,b))},Is=e=>(t,r)=>ge(e)([t],r),ge=e=>(t,r)=>{let d=r||{},{forwardToReplicas:s,replaceExistingSynonyms:n}=d,a=R(d,["forwardToReplicas","replaceExistingSynonyms"]),o=q.createMappedRequestOptions(a);return s&&(o.queryParameters.forwardToReplicas=1),n&&(o.queryParameters.replaceExistingSynonyms=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/synonyms/batch",e.indexName),data:t},o),(y,b)=>D(e)(y.taskID,b))},ft=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/query",e.indexName),data:{query:t},cacheable:!0},r),dt=e=>(t,r,s)=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/facets/%s/query",e.indexName,t),data:{facetQuery:r},cacheable:!0},s),mt=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/rules/search",e.indexName),data:{query:t}},r),ht=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/synonyms/search",e.indexName),data:{query:t}},r),As=e=>(t,r)=>{let o=r||{},{forwardToReplicas:s}=o,n=R(o,["forwardToReplicas"]),a=q.createMappedRequestOptions(n);return s&&(a.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Put,path:l.encode("1/indexes/%s/settings",e.indexName),data:t},a),(d,y)=>D(e)(d.taskID,y))},D=e=>(t,r)=>l.createRetryablePromise(s=>bt(e)(t,r).then(n=>n.status!=="published"?s():void 0)),Ss={AddObject:"addObject",Analytics:"analytics",Browser:"browse",DeleteIndex:"deleteIndex",DeleteObject:"deleteObject",EditSettings:"editSettings",ListIndexes:"listIndexes",Logs:"logs",Recommendation:"recommendation",Search:"search",SeeUnretrievableAttributes:"seeUnretrievableAttributes",Settings:"settings",Usage:"usage"},k={AddObject:"addObject",UpdateObject:"updateObject",PartialUpdateObject:"partialUpdateObject",PartialUpdateObjectNoCreate:"partialUpdateObjectNoCreate",DeleteObject:"deleteObject"},ee={Settings:"settings",Synonyms:"synonyms",Rules:"rules"},Ds={None:"none",StopIfEnoughMatches:"stopIfEnoughMatches"},Rs={Synonym:"synonym",OneWaySynonym:"oneWaySynonym",AltCorrection1:"altCorrection1",AltCorrection2:"altCorrection2",Placeholder:"placeholder"};i.ApiKeyACLEnum=Ss;i.BatchActionEnum=k;i.ScopeEnum=ee;i.StrategyEnum=Ds;i.SynonymEnum=Rs;i.addApiKey=Rr;i.assignUserID=vr;i.assignUserIDs=xr;i.batch=pt;i.browseObjects=Yr;i.browseRules=Zr;i.browseSynonyms=es;i.chunkedBatch=te;i.clearObjects=ts;i.clearRules=rs;i.clearSynonyms=ss;i.copyIndex=Z;i.copyRules=qr;i.copySettings=Er;i.copySynonyms=Tr;i.createBrowsablePromise=Y;i.createMissingObjectIDError=ct;i.createObjectNotFoundError=ut;i.createSearchClient=Dr;i.createValidUntilNotFoundError=lt;i.deleteApiKey=Mr;i.deleteBy=ns;i.deleteIndex=as;i.deleteObject=os;i.deleteObjects=yt;i.deleteRule=is;i.deleteSynonym=cs;i.exists=us;i.findObject=ls;i.generateSecuredApiKey=wr;i.getApiKey=$;i.getLogs=kr;i.getObject=ds;i.getObjectPosition=ps;i.getObjects=ms;i.getRule=hs;i.getSecuredApiKeyRemainingValidity=Cr;i.getSettings=gt;i.getSynonym=ys;i.getTask=bt;i.getTopUserIDs=Ur;i.getUserID=Nr;i.hasPendingMappings=Wr;i.initIndex=L;i.listApiKeys=Hr;i.listClusters=_r;i.listIndices=Fr;i.listUserIDs=Br;i.moveIndex=Kr;i.multipleBatch=zr;i.multipleGetObjects=Gr;i.multipleQueries=$r;i.multipleSearchForFacetValues=Lr;i.partialUpdateObject=gs;i.partialUpdateObjects=Pt;i.removeUserID=Vr;i.replaceAllObjects=fs;i.replaceAllRules=bs;i.replaceAllSynonyms=Ps;i.restoreApiKey=Qr;i.saveObject=js;i.saveObjects=he;i.saveRule=Os;i.saveRules=ye;i.saveSynonym=Is;i.saveSynonyms=ge;i.search=ft;i.searchForFacetValues=dt;i.searchRules=mt;i.searchSynonyms=ht;i.searchUserIDs=Jr;i.setSettings=As;i.updateApiKey=Xr;i.waitTask=D});var It=I((on,Ot)=>{Ot.exports=jt()});var At=I(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});function vs(){return{debug(e,t){return Promise.resolve()},info(e,t){return Promise.resolve()},error(e,t){return Promise.resolve()}}}var xs={Debug:1,Info:2,Error:3};re.LogLevelEnum=xs;re.createNullLogger=vs});var Dt=I((un,St)=>{St.exports=At()});var xt=I(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});var Rt=require("http"),vt=require("https"),qs=require("url");function Es(){let e={keepAlive:!0},t=new Rt.Agent(e),r=new vt.Agent(e);return{send(s){return new Promise(n=>{let a=qs.parse(s.url),o=a.query===null?a.pathname:`${a.pathname}?${a.query}`,d=u({agent:a.protocol==="https:"?r:t,hostname:a.hostname,path:o,method:s.method,headers:s.headers},a.port!==void 0?{port:a.port||""}:{}),y=(a.protocol==="https:"?vt:Rt).request(d,h=>{let S="";h.on("data",O=>S+=O),h.on("end",()=>{clearTimeout(f),clearTimeout(p),n({status:h.statusCode||0,content:S,isTimedOut:!1})})}),b=(h,S)=>setTimeout(()=>{y.abort(),n({status:0,content:S,isTimedOut:!0})},h*1e3),f=b(s.connectTimeout,"Connection timeout"),p;y.on("error",h=>{clearTimeout(f),clearTimeout(p),n({status:0,content:h.message,isTimedOut:!1})}),y.once("response",()=>{clearTimeout(f),p=b(s.responseTimeout,"Socket timeout")}),s.data!==void 0&&y.write(s.data),y.end()})},destroy(){return t.destroy(),r.destroy(),Promise.resolve()}}}fe.createNodeHttpRequester=Es});var Et=I((dn,qt)=>{qt.exports=xt()});var kt=I((pn,Tt)=>{"use strict";var Mt=Ee(),Ts=we(),W=st(),be=F(),Pe=it(),c=It(),Ms=Dt(),ws=Et(),ks=K();function wt(e,t,r){let s={appId:e,apiKey:t,timeouts:{connect:2,read:5,write:30},requester:ws.createNodeHttpRequester(),logger:Ms.createNullLogger(),responsesCache:Mt.createNullCache(),requestsCache:Mt.createNullCache(),hostsCache:Ts.createInMemoryCache(),userAgent:ks.createUserAgent(be.version).add({segment:"Node.js",version:process.versions.node})};return c.createSearchClient(g(u(u({},s),r),{methods:{search:c.multipleQueries,searchForFacetValues:c.multipleSearchForFacetValues,multipleBatch:c.multipleBatch,multipleGetObjects:c.multipleGetObjects,multipleQueries:c.multipleQueries,copyIndex:c.copyIndex,copySettings:c.copySettings,copyRules:c.copyRules,copySynonyms:c.copySynonyms,moveIndex:c.moveIndex,listIndices:c.listIndices,getLogs:c.getLogs,listClusters:c.listClusters,multipleSearchForFacetValues:c.multipleSearchForFacetValues,getApiKey:c.getApiKey,addApiKey:c.addApiKey,listApiKeys:c.listApiKeys,updateApiKey:c.updateApiKey,deleteApiKey:c.deleteApiKey,restoreApiKey:c.restoreApiKey,assignUserID:c.assignUserID,assignUserIDs:c.assignUserIDs,getUserID:c.getUserID,searchUserIDs:c.searchUserIDs,listUserIDs:c.listUserIDs,getTopUserIDs:c.getTopUserIDs,removeUserID:c.removeUserID,hasPendingMappings:c.hasPendingMappings,generateSecuredApiKey:c.generateSecuredApiKey,getSecuredApiKeyRemainingValidity:c.getSecuredApiKeyRemainingValidity,destroy:be.destroy,initIndex:n=>a=>c.initIndex(n)(a,{methods:{batch:c.batch,delete:c.deleteIndex,getObject:c.getObject,getObjects:c.getObjects,saveObject:c.saveObject,saveObjects:c.saveObjects,search:c.search,searchForFacetValues:c.searchForFacetValues,waitTask:c.waitTask,setSettings:c.setSettings,getSettings:c.getSettings,partialUpdateObject:c.partialUpdateObject,partialUpdateObjects:c.partialUpdateObjects,deleteObject:c.deleteObject,deleteObjects:c.deleteObjects,deleteBy:c.deleteBy,clearObjects:c.clearObjects,browseObjects:c.browseObjects,getObjectPosition:c.getObjectPosition,findObject:c.findObject,exists:c.exists,saveSynonym:c.saveSynonym,saveSynonyms:c.saveSynonyms,getSynonym:c.getSynonym,searchSynonyms:c.searchSynonyms,browseSynonyms:c.browseSynonyms,deleteSynonym:c.deleteSynonym,clearSynonyms:c.clearSynonyms,replaceAllObjects:c.replaceAllObjects,replaceAllSynonyms:c.replaceAllSynonyms,searchRules:c.searchRules,getRule:c.getRule,deleteRule:c.deleteRule,saveRule:c.saveRule,saveRules:c.saveRules,replaceAllRules:c.replaceAllRules,browseRules:c.browseRules,clearRules:c.clearRules}}),initAnalytics:()=>n=>W.createAnalyticsClient(g(u(u({},s),n),{methods:{addABTest:W.addABTest,getABTest:W.getABTest,getABTests:W.getABTests,stopABTest:W.stopABTest,deleteABTest:W.deleteABTest}})),initRecommendation:()=>n=>Pe.createRecommendationClient(g(u(u({},s),n),{methods:{getPersonalizationStrategy:Pe.getPersonalizationStrategy,setPersonalizationStrategy:Pe.setPersonalizationStrategy}}))}}))}wt.version=be.version;Tt.exports=wt});var Ut=I((mn,je)=>{var Ct=kt();je.exports=Ct;je.exports.default=Ct});var Ws={};Vt(Ws,{default:()=>Ks});var Oe=C(require("@yarnpkg/core")),E=C(require("@yarnpkg/core")),Ie=C(require("@yarnpkg/plugin-essentials")),Ht=C(require("semver"));var se=C(require("@yarnpkg/core")),Nt=C(Ut()),Cs="e8e1bd300d860104bb8c58453ffa1eb4",Us="OFCNCOG2CU",Wt=async(e,t)=>{var a;let r=se.structUtils.stringifyIdent(e),n=Ns(t).initIndex("npm-search");try{return((a=(await n.getObject(r,{attributesToRetrieve:["types"]})).types)==null?void 0:a.ts)==="definitely-typed"}catch(o){return!1}},Ns=e=>(0,Nt.default)(Us,Cs,{requester:{async send(r){try{let s=await se.httpUtils.request(r.url,r.data||null,{configuration:e,headers:r.headers});return{content:s.body,isTimedOut:!1,status:s.statusCode}}catch(s){return{content:s.response.body,isTimedOut:!1,status:s.response.statusCode}}}}});var _t=e=>e.scope?`${e.scope}__${e.name}`:`${e.name}`,Hs=async(e,t,r,s)=>{if(r.scope==="types")return;let{project:n}=e,{configuration:a}=n,o=a.makeResolver(),d={project:n,resolver:o,report:new E.ThrowReport};if(!await Wt(r,a))return;let b=_t(r),f=E.structUtils.parseRange(r.range).selector;if(!E.semverUtils.validRange(f)){let P=await o.getCandidates(r,new Map,d);f=E.structUtils.parseRange(P[0].reference).selector}let p=Ht.default.coerce(f);if(p===null)return;let h=`${Ie.suggestUtils.Modifier.CARET}${p.major}`,S=E.structUtils.makeDescriptor(E.structUtils.makeIdent("types",b),h),O=E.miscUtils.mapAndFind(n.workspaces,P=>{var T,V;let x=(T=P.manifest.dependencies.get(r.identHash))==null?void 0:T.descriptorHash,v=(V=P.manifest.devDependencies.get(r.identHash))==null?void 0:V.descriptorHash;if(x!==r.descriptorHash&&v!==r.descriptorHash)return E.miscUtils.mapAndFind.skip;let j=[];for(let Ae of Oe.Manifest.allDependencies){let Se=P.manifest[Ae].get(S.identHash);typeof Se!="undefined"&&j.push([Ae,Se])}return j.length===0?E.miscUtils.mapAndFind.skip:j});if(typeof O!="undefined")for(let[P,x]of O)e.manifest[P].set(x.identHash,x);else{try{if((await o.getCandidates(S,new Map,d)).length===0)return}catch{return}e.manifest[Ie.suggestUtils.Target.DEVELOPMENT].set(S.identHash,S)}},_s=async(e,t,r)=>{if(r.scope==="types")return;let s=_t(r),n=E.structUtils.makeIdent("types",s);for(let a of Oe.Manifest.allDependencies)typeof e.manifest[a].get(n.identHash)!="undefined"&&e.manifest[a].delete(n.identHash)},Fs=(e,t)=>{t.publishConfig&&t.publishConfig.typings&&(t.typings=t.publishConfig.typings),t.publishConfig&&t.publishConfig.types&&(t.types=t.publishConfig.types)},Bs={hooks:{afterWorkspaceDependencyAddition:Hs,afterWorkspaceDependencyRemoval:_s,beforeWorkspacePacking:Fs}},Ks=Bs;return Ws;})(); 7 | return plugin; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /.yarn/sdks/eslint/bin/eslint.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require eslint/bin/eslint.js 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real eslint/bin/eslint.js your application uses 20 | module.exports = absRequire(`eslint/bin/eslint.js`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/eslint/lib/api.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require eslint 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real eslint your application uses 20 | module.exports = absRequire(`eslint`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/eslint/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eslint", 3 | "version": "8.38.0-sdk", 4 | "main": "./lib/api.js", 5 | "type": "commonjs" 6 | } 7 | -------------------------------------------------------------------------------- /.yarn/sdks/integrations.yml: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by @yarnpkg/sdks. 2 | # Manual changes might be lost! 3 | 4 | integrations: 5 | - vscode 6 | -------------------------------------------------------------------------------- /.yarn/sdks/prettier/index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require prettier/index.js 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real prettier/index.js your application uses 20 | module.exports = absRequire(`prettier/index.js`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/prettier/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "prettier", 3 | "version": "2.8.7-sdk", 4 | "main": "./index.js", 5 | "type": "commonjs" 6 | } 7 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/bin/tsc: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require typescript/bin/tsc 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real typescript/bin/tsc your application uses 20 | module.exports = absRequire(`typescript/bin/tsc`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/bin/tsserver: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require typescript/bin/tsserver 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real typescript/bin/tsserver your application uses 20 | module.exports = absRequire(`typescript/bin/tsserver`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/lib/tsc.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require typescript/lib/tsc.js 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real typescript/lib/tsc.js your application uses 20 | module.exports = absRequire(`typescript/lib/tsc.js`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/lib/tsserver.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | const moduleWrapper = tsserver => { 13 | if (!process.versions.pnp) { 14 | return tsserver; 15 | } 16 | 17 | const {isAbsolute} = require(`path`); 18 | const pnpApi = require(`pnpapi`); 19 | 20 | const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//); 21 | const isPortal = str => str.startsWith("portal:/"); 22 | const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`); 23 | 24 | const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => { 25 | return `${locator.name}@${locator.reference}`; 26 | })); 27 | 28 | // VSCode sends the zip paths to TS using the "zip://" prefix, that TS 29 | // doesn't understand. This layer makes sure to remove the protocol 30 | // before forwarding it to TS, and to add it back on all returned paths. 31 | 32 | function toEditorPath(str) { 33 | // We add the `zip:` prefix to both `.zip/` paths and virtual paths 34 | if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) { 35 | // We also take the opportunity to turn virtual paths into physical ones; 36 | // this makes it much easier to work with workspaces that list peer 37 | // dependencies, since otherwise Ctrl+Click would bring us to the virtual 38 | // file instances instead of the real ones. 39 | // 40 | // We only do this to modules owned by the the dependency tree roots. 41 | // This avoids breaking the resolution when jumping inside a vendor 42 | // with peer dep (otherwise jumping into react-dom would show resolution 43 | // errors on react). 44 | // 45 | const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str; 46 | if (resolved) { 47 | const locator = pnpApi.findPackageLocator(resolved); 48 | if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) { 49 | str = resolved; 50 | } 51 | } 52 | 53 | str = normalize(str); 54 | 55 | if (str.match(/\.zip\//)) { 56 | switch (hostInfo) { 57 | // Absolute VSCode `Uri.fsPath`s need to start with a slash. 58 | // VSCode only adds it automatically for supported schemes, 59 | // so we have to do it manually for the `zip` scheme. 60 | // The path needs to start with a caret otherwise VSCode doesn't handle the protocol 61 | // 62 | // Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910 63 | // 64 | // 2021-10-08: VSCode changed the format in 1.61. 65 | // Before | ^zip:/c:/foo/bar.zip/package.json 66 | // After | ^/zip//c:/foo/bar.zip/package.json 67 | // 68 | // 2022-04-06: VSCode changed the format in 1.66. 69 | // Before | ^/zip//c:/foo/bar.zip/package.json 70 | // After | ^/zip/c:/foo/bar.zip/package.json 71 | // 72 | // 2022-05-06: VSCode changed the format in 1.68 73 | // Before | ^/zip/c:/foo/bar.zip/package.json 74 | // After | ^/zip//c:/foo/bar.zip/package.json 75 | // 76 | case `vscode <1.61`: { 77 | str = `^zip:${str}`; 78 | } break; 79 | 80 | case `vscode <1.66`: { 81 | str = `^/zip/${str}`; 82 | } break; 83 | 84 | case `vscode <1.68`: { 85 | str = `^/zip${str}`; 86 | } break; 87 | 88 | case `vscode`: { 89 | str = `^/zip/${str}`; 90 | } break; 91 | 92 | // To make "go to definition" work, 93 | // We have to resolve the actual file system path from virtual path 94 | // and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip) 95 | case `coc-nvim`: { 96 | str = normalize(resolved).replace(/\.zip\//, `.zip::`); 97 | str = resolve(`zipfile:${str}`); 98 | } break; 99 | 100 | // Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server) 101 | // We have to resolve the actual file system path from virtual path, 102 | // everything else is up to neovim 103 | case `neovim`: { 104 | str = normalize(resolved).replace(/\.zip\//, `.zip::`); 105 | str = `zipfile://${str}`; 106 | } break; 107 | 108 | default: { 109 | str = `zip:${str}`; 110 | } break; 111 | } 112 | } else { 113 | str = str.replace(/^\/?/, process.platform === `win32` ? `` : `/`); 114 | } 115 | } 116 | 117 | return str; 118 | } 119 | 120 | function fromEditorPath(str) { 121 | switch (hostInfo) { 122 | case `coc-nvim`: { 123 | str = str.replace(/\.zip::/, `.zip/`); 124 | // The path for coc-nvim is in format of //zipfile://.yarn/... 125 | // So in order to convert it back, we use .* to match all the thing 126 | // before `zipfile:` 127 | return process.platform === `win32` 128 | ? str.replace(/^.*zipfile:\//, ``) 129 | : str.replace(/^.*zipfile:/, ``); 130 | } break; 131 | 132 | case `neovim`: { 133 | str = str.replace(/\.zip::/, `.zip/`); 134 | // The path for neovim is in format of zipfile:////.yarn/... 135 | return str.replace(/^zipfile:\/\//, ``); 136 | } break; 137 | 138 | case `vscode`: 139 | default: { 140 | return str.replace(/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/, process.platform === `win32` ? `` : `/`) 141 | } break; 142 | } 143 | } 144 | 145 | // Force enable 'allowLocalPluginLoads' 146 | // TypeScript tries to resolve plugins using a path relative to itself 147 | // which doesn't work when using the global cache 148 | // https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238 149 | // VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but 150 | // TypeScript already does local loads and if this code is running the user trusts the workspace 151 | // https://github.com/microsoft/vscode/issues/45856 152 | const ConfiguredProject = tsserver.server.ConfiguredProject; 153 | const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype; 154 | ConfiguredProject.prototype.enablePluginsWithOptions = function() { 155 | this.projectService.allowLocalPluginLoads = true; 156 | return originalEnablePluginsWithOptions.apply(this, arguments); 157 | }; 158 | 159 | // And here is the point where we hijack the VSCode <-> TS communications 160 | // by adding ourselves in the middle. We locate everything that looks 161 | // like an absolute path of ours and normalize it. 162 | 163 | const Session = tsserver.server.Session; 164 | const {onMessage: originalOnMessage, send: originalSend} = Session.prototype; 165 | let hostInfo = `unknown`; 166 | 167 | Object.assign(Session.prototype, { 168 | onMessage(/** @type {string | object} */ message) { 169 | const isStringMessage = typeof message === 'string'; 170 | const parsedMessage = isStringMessage ? JSON.parse(message) : message; 171 | 172 | if ( 173 | parsedMessage != null && 174 | typeof parsedMessage === `object` && 175 | parsedMessage.arguments && 176 | typeof parsedMessage.arguments.hostInfo === `string` 177 | ) { 178 | hostInfo = parsedMessage.arguments.hostInfo; 179 | if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) { 180 | const [, major, minor] = (process.env.VSCODE_IPC_HOOK.match( 181 | // The RegExp from https://semver.org/ but without the caret at the start 182 | /(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/ 183 | ) ?? []).map(Number) 184 | 185 | if (major === 1) { 186 | if (minor < 61) { 187 | hostInfo += ` <1.61`; 188 | } else if (minor < 66) { 189 | hostInfo += ` <1.66`; 190 | } else if (minor < 68) { 191 | hostInfo += ` <1.68`; 192 | } 193 | } 194 | } 195 | } 196 | 197 | const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => { 198 | return typeof value === 'string' ? fromEditorPath(value) : value; 199 | }); 200 | 201 | return originalOnMessage.call( 202 | this, 203 | isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON) 204 | ); 205 | }, 206 | 207 | send(/** @type {any} */ msg) { 208 | return originalSend.call(this, JSON.parse(JSON.stringify(msg, (key, value) => { 209 | return typeof value === `string` ? toEditorPath(value) : value; 210 | }))); 211 | } 212 | }); 213 | 214 | return tsserver; 215 | }; 216 | 217 | if (existsSync(absPnpApiPath)) { 218 | if (!process.versions.pnp) { 219 | // Setup the environment to be able to require typescript/lib/tsserver.js 220 | require(absPnpApiPath).setup(); 221 | } 222 | } 223 | 224 | // Defer to the real typescript/lib/tsserver.js your application uses 225 | module.exports = moduleWrapper(absRequire(`typescript/lib/tsserver.js`)); 226 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/lib/tsserverlibrary.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | const moduleWrapper = tsserver => { 13 | if (!process.versions.pnp) { 14 | return tsserver; 15 | } 16 | 17 | const {isAbsolute} = require(`path`); 18 | const pnpApi = require(`pnpapi`); 19 | 20 | const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//); 21 | const isPortal = str => str.startsWith("portal:/"); 22 | const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`); 23 | 24 | const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => { 25 | return `${locator.name}@${locator.reference}`; 26 | })); 27 | 28 | // VSCode sends the zip paths to TS using the "zip://" prefix, that TS 29 | // doesn't understand. This layer makes sure to remove the protocol 30 | // before forwarding it to TS, and to add it back on all returned paths. 31 | 32 | function toEditorPath(str) { 33 | // We add the `zip:` prefix to both `.zip/` paths and virtual paths 34 | if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) { 35 | // We also take the opportunity to turn virtual paths into physical ones; 36 | // this makes it much easier to work with workspaces that list peer 37 | // dependencies, since otherwise Ctrl+Click would bring us to the virtual 38 | // file instances instead of the real ones. 39 | // 40 | // We only do this to modules owned by the the dependency tree roots. 41 | // This avoids breaking the resolution when jumping inside a vendor 42 | // with peer dep (otherwise jumping into react-dom would show resolution 43 | // errors on react). 44 | // 45 | const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str; 46 | if (resolved) { 47 | const locator = pnpApi.findPackageLocator(resolved); 48 | if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) { 49 | str = resolved; 50 | } 51 | } 52 | 53 | str = normalize(str); 54 | 55 | if (str.match(/\.zip\//)) { 56 | switch (hostInfo) { 57 | // Absolute VSCode `Uri.fsPath`s need to start with a slash. 58 | // VSCode only adds it automatically for supported schemes, 59 | // so we have to do it manually for the `zip` scheme. 60 | // The path needs to start with a caret otherwise VSCode doesn't handle the protocol 61 | // 62 | // Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910 63 | // 64 | // 2021-10-08: VSCode changed the format in 1.61. 65 | // Before | ^zip:/c:/foo/bar.zip/package.json 66 | // After | ^/zip//c:/foo/bar.zip/package.json 67 | // 68 | // 2022-04-06: VSCode changed the format in 1.66. 69 | // Before | ^/zip//c:/foo/bar.zip/package.json 70 | // After | ^/zip/c:/foo/bar.zip/package.json 71 | // 72 | // 2022-05-06: VSCode changed the format in 1.68 73 | // Before | ^/zip/c:/foo/bar.zip/package.json 74 | // After | ^/zip//c:/foo/bar.zip/package.json 75 | // 76 | case `vscode <1.61`: { 77 | str = `^zip:${str}`; 78 | } break; 79 | 80 | case `vscode <1.66`: { 81 | str = `^/zip/${str}`; 82 | } break; 83 | 84 | case `vscode <1.68`: { 85 | str = `^/zip${str}`; 86 | } break; 87 | 88 | case `vscode`: { 89 | str = `^/zip/${str}`; 90 | } break; 91 | 92 | // To make "go to definition" work, 93 | // We have to resolve the actual file system path from virtual path 94 | // and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip) 95 | case `coc-nvim`: { 96 | str = normalize(resolved).replace(/\.zip\//, `.zip::`); 97 | str = resolve(`zipfile:${str}`); 98 | } break; 99 | 100 | // Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server) 101 | // We have to resolve the actual file system path from virtual path, 102 | // everything else is up to neovim 103 | case `neovim`: { 104 | str = normalize(resolved).replace(/\.zip\//, `.zip::`); 105 | str = `zipfile://${str}`; 106 | } break; 107 | 108 | default: { 109 | str = `zip:${str}`; 110 | } break; 111 | } 112 | } else { 113 | str = str.replace(/^\/?/, process.platform === `win32` ? `` : `/`); 114 | } 115 | } 116 | 117 | return str; 118 | } 119 | 120 | function fromEditorPath(str) { 121 | switch (hostInfo) { 122 | case `coc-nvim`: { 123 | str = str.replace(/\.zip::/, `.zip/`); 124 | // The path for coc-nvim is in format of //zipfile://.yarn/... 125 | // So in order to convert it back, we use .* to match all the thing 126 | // before `zipfile:` 127 | return process.platform === `win32` 128 | ? str.replace(/^.*zipfile:\//, ``) 129 | : str.replace(/^.*zipfile:/, ``); 130 | } break; 131 | 132 | case `neovim`: { 133 | str = str.replace(/\.zip::/, `.zip/`); 134 | // The path for neovim is in format of zipfile:////.yarn/... 135 | return str.replace(/^zipfile:\/\//, ``); 136 | } break; 137 | 138 | case `vscode`: 139 | default: { 140 | return str.replace(/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/, process.platform === `win32` ? `` : `/`) 141 | } break; 142 | } 143 | } 144 | 145 | // Force enable 'allowLocalPluginLoads' 146 | // TypeScript tries to resolve plugins using a path relative to itself 147 | // which doesn't work when using the global cache 148 | // https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238 149 | // VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but 150 | // TypeScript already does local loads and if this code is running the user trusts the workspace 151 | // https://github.com/microsoft/vscode/issues/45856 152 | const ConfiguredProject = tsserver.server.ConfiguredProject; 153 | const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype; 154 | ConfiguredProject.prototype.enablePluginsWithOptions = function() { 155 | this.projectService.allowLocalPluginLoads = true; 156 | return originalEnablePluginsWithOptions.apply(this, arguments); 157 | }; 158 | 159 | // And here is the point where we hijack the VSCode <-> TS communications 160 | // by adding ourselves in the middle. We locate everything that looks 161 | // like an absolute path of ours and normalize it. 162 | 163 | const Session = tsserver.server.Session; 164 | const {onMessage: originalOnMessage, send: originalSend} = Session.prototype; 165 | let hostInfo = `unknown`; 166 | 167 | Object.assign(Session.prototype, { 168 | onMessage(/** @type {string | object} */ message) { 169 | const isStringMessage = typeof message === 'string'; 170 | const parsedMessage = isStringMessage ? JSON.parse(message) : message; 171 | 172 | if ( 173 | parsedMessage != null && 174 | typeof parsedMessage === `object` && 175 | parsedMessage.arguments && 176 | typeof parsedMessage.arguments.hostInfo === `string` 177 | ) { 178 | hostInfo = parsedMessage.arguments.hostInfo; 179 | if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) { 180 | const [, major, minor] = (process.env.VSCODE_IPC_HOOK.match( 181 | // The RegExp from https://semver.org/ but without the caret at the start 182 | /(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/ 183 | ) ?? []).map(Number) 184 | 185 | if (major === 1) { 186 | if (minor < 61) { 187 | hostInfo += ` <1.61`; 188 | } else if (minor < 66) { 189 | hostInfo += ` <1.66`; 190 | } else if (minor < 68) { 191 | hostInfo += ` <1.68`; 192 | } 193 | } 194 | } 195 | } 196 | 197 | const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => { 198 | return typeof value === 'string' ? fromEditorPath(value) : value; 199 | }); 200 | 201 | return originalOnMessage.call( 202 | this, 203 | isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON) 204 | ); 205 | }, 206 | 207 | send(/** @type {any} */ msg) { 208 | return originalSend.call(this, JSON.parse(JSON.stringify(msg, (key, value) => { 209 | return typeof value === `string` ? toEditorPath(value) : value; 210 | }))); 211 | } 212 | }); 213 | 214 | return tsserver; 215 | }; 216 | 217 | if (existsSync(absPnpApiPath)) { 218 | if (!process.versions.pnp) { 219 | // Setup the environment to be able to require typescript/lib/tsserverlibrary.js 220 | require(absPnpApiPath).setup(); 221 | } 222 | } 223 | 224 | // Defer to the real typescript/lib/tsserverlibrary.js your application uses 225 | module.exports = moduleWrapper(absRequire(`typescript/lib/tsserverlibrary.js`)); 226 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/lib/typescript.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = createRequire(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require typescript/lib/typescript.js 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real typescript/lib/typescript.js your application uses 20 | module.exports = absRequire(`typescript/lib/typescript.js`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typescript", 3 | "version": "5.0.4-sdk", 4 | "main": "./lib/typescript.js", 5 | "type": "commonjs" 6 | } 7 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs 3 | spec: "@yarnpkg/plugin-interactive-tools" 4 | - path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs 5 | spec: "@yarnpkg/plugin-typescript" 6 | 7 | yarnPath: .yarn/releases/yarn-3.5.0.cjs 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [0.7.0](https://www.github.com/pinetwork-js/api-typing/compare/v0.6.1...v0.7.0) (2023-04-23) 4 | 5 | 6 | ### Features 7 | 8 | * add network error route ([e4cad80](https://www.github.com/pinetwork-js/api-typing/commit/e4cad801b03555c846ec2c805c095e6a6750fb4a)) 9 | 10 | ### [0.6.1](https://www.github.com/pinetwork-js/api-typing/compare/v0.6.0...v0.6.1) (2023-04-22) 11 | 12 | 13 | ### Bug Fixes 14 | 15 | * rename RESTGetClientIncompletePaymentResult to RESTGetIncompleteClientPaymentResult ([c80a96e](https://www.github.com/pinetwork-js/api-typing/commit/c80a96e9123e4254f47fef2179678d0ec32d3bd3)) 16 | * route type for static routes ([3ecd123](https://www.github.com/pinetwork-js/api-typing/commit/3ecd123c9da6572409a46586a090caf3da9d6e36)) 17 | 18 | ## [0.6.0](https://www.github.com/pinetwork-js/api-typing/compare/v0.5.2...v0.6.0) (2023-04-14) 19 | 20 | 21 | ### Features 22 | 23 | * add preferred_language scope ([0004daa](https://www.github.com/pinetwork-js/api-typing/commit/0004daa14551ff55736b83a1b04cd5c0866308c0)) 24 | 25 | ### [0.5.2](https://www.github.com/PiNetwork-js/api-typing/compare/v0.5.1...v0.5.2) (2023-01-23) 26 | 27 | 28 | ### Documentation 29 | 30 | * makes README clearer ([33f3fa8](https://www.github.com/PiNetwork-js/api-typing/commit/33f3fa8f38a8b5f664a22d7c5c1ed333193bf93e)) 31 | 32 | ### [0.5.1](https://www.github.com/PiNetwork-js/api-typing/compare/v0.5.0...v0.5.1) (2023-01-21) 33 | 34 | 35 | ### Bug Fixes 36 | 37 | * differentiate payment creation API endpoints ([1ab4fd6](https://www.github.com/PiNetwork-js/api-typing/commit/1ab4fd6f685d5b7a491a8e924bfbb274d13d2897)) 38 | 39 | ## [0.5.0](https://www.github.com/PiNetwork-js/api-typing/compare/v0.4.0...v0.5.0) (2023-01-21) 40 | 41 | 42 | ### Features 43 | 44 | * add App-to-Pioneer API types and endpoints ([f3e2dba](https://www.github.com/PiNetwork-js/api-typing/commit/f3e2dba7d652aae05cdd3adb5a37cc5db2319a24)) 45 | * add event_hacker role ([eb21c9e](https://www.github.com/PiNetwork-js/api-typing/commit/eb21c9e73caec060b2ef1edf590d13007a45da5a)) 46 | * add wallet_address scope ([7db9172](https://www.github.com/PiNetwork-js/api-typing/commit/7db9172999b8dd7dc46279bdd43e9c2f4f443fae)) 47 | 48 | ## [0.4.0](https://www.github.com/PiNetwork-js/api-typing/compare/v0.3.0...v0.4.0) (2022-08-01) 49 | 50 | 51 | ### Features 52 | 53 | * add exports field in package.json ([d559dbd](https://www.github.com/PiNetwork-js/api-typing/commit/d559dbdc0fabf3f4b500f930e86d52c87670e826)) 54 | * add usage tracking API info ([6d91f54](https://www.github.com/PiNetwork-js/api-typing/commit/6d91f541a2999822c62cfd572b47cfe4e0908ccd)) 55 | * new APIUser structure ([c35f248](https://www.github.com/PiNetwork-js/api-typing/commit/c35f24862e6273866df57a7952242a1f2614c56f)) 56 | 57 | 58 | ### Bug Fixes 59 | 60 | * missing some exports ([1fdd8b7](https://www.github.com/PiNetwork-js/api-typing/commit/1fdd8b7877f7fd03cc26aa21fa2b48d14ab68bf5)) 61 | 62 | ## [0.3.0](https://www.github.com/PiNetwork-js/api-typing/compare/v0.2.4...v0.3.0) (2021-08-12) 63 | 64 | 65 | ### Features 66 | 67 | * new APIUser type with scope system ([0bfd2c0](https://www.github.com/PiNetwork-js/api-typing/commit/0bfd2c0da9c3c187ff2c11380cb1c4fc7b5d7c17)) 68 | 69 | ### [0.2.4](https://www.github.com/PiNetwork-js/api-typing/compare/v0.2.3...v0.2.4) (2021-08-12) 70 | 71 | 72 | ### Bug Fixes 73 | 74 | * remove unused roles in APIUserRoles for auth ([aa6ff20](https://www.github.com/PiNetwork-js/api-typing/commit/aa6ff20d0141cc8b675c6760f2ebeb7f29c786f6)) 75 | 76 | ### [0.2.3](https://www.github.com/PiNetwork-js/api-typing/compare/v0.2.2...v0.2.3) (2021-08-06) 77 | 78 | 79 | ### Bug Fixes 80 | 81 | * remove slash at the beginning of routes ([aff8e32](https://www.github.com/PiNetwork-js/api-typing/commit/aff8e3286567de70174cad4e10fd6c887400b29f)) 82 | 83 | ### [0.2.2](https://www.github.com/PiNetwork-js/api-typing/compare/v0.2.1...v0.2.2) (2021-07-28) 84 | 85 | 86 | ### Documentation 87 | 88 | * update create payment documentation link ([a649270](https://www.github.com/PiNetwork-js/api-typing/commit/a64927082961ae6c0ea3c5569f13ab535c94d7aa)) 89 | 90 | 91 | ### Miscellaneous Chores 92 | 93 | * update APIUserRoles type ([5a9fb80](https://www.github.com/PiNetwork-js/api-typing/commit/5a9fb8081a185f803e9ab273ef8965594f2eeddb)) 94 | 95 | 96 | ### [0.2.1](https://www.github.com/PiNetwork-js/api-typing/compare/v0.2.0...v0.2.1) (2021-07-12) 97 | 98 | 99 | ### Bug Fixes 100 | 101 | * **routes:** change recent payment to incomplete payment ([#15](https://www.github.com/PiNetwork-js/api-typing/issues/15)) ([f449768](https://www.github.com/PiNetwork-js/api-typing/commit/f44976874daad4ff4b7514648d3edb86470acd7c)) 102 | 103 | ## [0.2.0](https://www.github.com/PiNetwork-js/api-typing/compare/v0.1.0...v0.2.0) (2021-07-01) 104 | 105 | 106 | ### Features 107 | 108 | * group export ([#12](https://www.github.com/PiNetwork-js/api-typing/issues/12)) ([45f7e6a](https://www.github.com/PiNetwork-js/api-typing/commit/45f7e6afe8e9102e4be189ff472d1337b1b2c1f9)) 109 | * routes typing ([#10](https://www.github.com/PiNetwork-js/api-typing/issues/10)) ([2f8c1bf](https://www.github.com/PiNetwork-js/api-typing/commit/2f8c1bf00bae036c43cfbc6ddb25f3444826ab85)) 110 | 111 | ## 0.1.0 (2021-06-30) 112 | 113 | 114 | ### Features 115 | 116 | * Typing ([#2](https://www.github.com/PiNetwork-js/api-typing/issues/2)) ([734737d](https://www.github.com/PiNetwork-js/api-typing/commit/734737ddf2c22c57f2e05e6a10b2df93ed3cd103)) 117 | 118 | 119 | ### Bug Fixes 120 | 121 | * **ci:** typo in release-please.yml ([50177ba](https://www.github.com/PiNetwork-js/api-typing/commit/50177bac679fcca8e6c975866c609e5dca423952)) 122 | * package version start ([7f401bd](https://www.github.com/PiNetwork-js/api-typing/commit/7f401bd6f6a1ae9d257508dc4469fffa15e31dc6)) 123 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | PiOS License 2 | 3 | Copyright (C) 2021 Brewal Derouet 4 | 5 | Permission is hereby granted by the application software developer (“Software Developer”), free 6 | of charge, to any person obtaining a copy of this application, software and associated 7 | documentation files (the “Software”), which was developed by the Software Developer for use on 8 | Pi Network, whereby the purpose of this license is to permit the development of derivative works 9 | based on the Software, including the right to use, copy, modify, merge, publish, distribute, 10 | sub-license, and/or sell copies of such derivative works and any Software components incorporated 11 | therein, and to permit persons to whom such derivative works are furnished to do so, in each case, 12 | solely to develop, use and market applications for the official Pi Network. For purposes of this 13 | license, Pi Network shall mean any application, software, or other present or future platform 14 | developed, owned or managed by Pi Community Company, and its parents, affiliates or subsidiaries, 15 | for which the Software was developed, or on which the Software continues to operate. However, 16 | you are prohibited from using any portion of the Software or any derivative works thereof in any 17 | manner (a) which infringes on any Pi Network intellectual property rights, (b) to hack any of Pi 18 | Network’s systems or processes or (c) to develop any product or service which is competitive with 19 | the Pi Network. 20 | 21 | The above copyright notice and this permission notice shall be included in all copies or 22 | substantial portions of the Software. 23 | 24 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 25 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 26 | AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, PUBLISHERS, OR COPYRIGHT HOLDERS OF THIS 27 | SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL 28 | DAMAGES (INCLUDING, BUT NOT LIMITED TO BUSINESS INTERRUPTION, LOSS OF USE, DATA OR PROFITS) 29 | HOWEVER CAUSED AND UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 30 | TORT (INCLUDING NEGLIGENCE) ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 31 | OR OTHER DEALINGS IN THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 32 | 33 | Pi, Pi Network and the Pi logo are trademarks of the Pi Community Company. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pi Network API Types 2 | 3 | [![GitHub](https://img.shields.io/github/license/PiNetwork-js/api-typing)](https://github.com/PiNetwork-js/api-typing/blob/main/LICENSE.md) 4 | [![npm](https://img.shields.io/npm/v/@pinetwork-js/api-typing?color=crimson&logo=npm)](https://www.npmjs.com/package/@pinetwork-js/api-typing) 5 | 6 | Typing for the [Pi Network API](https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md) 7 | 8 | ## Installation 9 | 10 | Install with [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com): 11 | 12 | ```sh 13 | npm install @pinetwork-js/api-typing --save-dev 14 | yarn add @pinetwork-js/api-typing -D 15 | ``` 16 | 17 | ### Usage 18 | 19 | To use the package on your code, you can import everything or just what you want: 20 | 21 | ```js 22 | const api = require('@pinetwork-js/api-typing'); 23 | const { APIPayment } = require('@pinetwork-js/api-typing'); 24 | ``` 25 | 26 | ```ts 27 | // TypeScript or ESM support 28 | import api from '@pinetwork-js/api-typing'; 29 | import { APIPayment } from '@pinetwork-js/api-typing'; 30 | ``` 31 | 32 | The package is divided into three parts: `payloads`, `rest` and `routes`. If you just want to import all the types of a certain part: 33 | 34 | ```js 35 | const { routes } = require('@pinetwork-js/api-typing'); 36 | // or 37 | const routes = require('@pinetwork-js/api-typing/routes') 38 | ``` 39 | 40 | ```ts 41 | // TypeScript or ESM support 42 | import { routes } from '@pinetwork-js/api-typing'; 43 | // (or with moduleResolution set to 'node16' or 'nodenext') 44 | import routes from '@pinetwork-js/api-typing/routes'; 45 | ``` 46 | 47 | ### Routes 48 | 49 | The package provides typed routes for the Pi Network API. There are static and dynamic routes. Here's how it works: 50 | 51 | **Static routes:** 52 | 53 | Static routes are routes that doesn't change (you don't have to provide any information in the route) like `/me`. The exported static routes are just strings but with a custom type `Route` (where R is the type of the data sent by the API and P is the type of the payload we send to the API). Thanks to this type, we can store the type of the result and the payload requested by the route to type the requests we make. 54 | 55 | **Dynamic routes:** 56 | 57 | Dynamic routes are routes that need to be changed like `/payments/:payment_id` (you have to provide a payment id to get the information of that specific payment for example). The exported dynamic routes are functions who take an object as argument with the information it needs to create the final route. The result is a crafted string (the route) with the custom type `Route` (like a static route). Here's an example: 58 | 59 | ```ts 60 | import { getPayment } from '@pinetwork-js/api-typing/routes'; 61 | 62 | // routes.getPayment represents the dynamic route for 'GET /payments/:payment_id' 63 | 64 | const getPaymentRoute = getPayment({ paymentId: '1234' }); 65 | console.log(getPaymentRoute); // 'v2/payments/1234' 66 | 67 | type GetPaymentRoute = typeof getPaymentRoute; // Route 68 | ``` 69 | 70 | **How to type a request?** 71 | 72 | The package provide two generic types to help you for that: `RouteResult` and `RoutePayload`. `RouteResult` get the result's type of a route (the `R` in the type `Route`) and `RoutePayload` get the payload's type (the `P`). Here's an example of (non-functional) code to show you how to type your request functions (based on my rewrite of the SDK that you can find [here](https://github.com/PiNetwork-js/sdk)): 73 | 74 | ```ts 75 | import { RoutePayload, RouteResult, Route } from '@pinetwork-js/api-typing'; 76 | 77 | async function get>(route: T): Promise> { 78 | const response = await myGetRequest(route); 79 | 80 | return response.data; 81 | } 82 | 83 | async function post>(route: T, payload: RoutePayload): Promise> { 84 | const response = await myPostRequest(route, payload); 85 | 86 | return response.data; 87 | } 88 | ``` 89 | 90 | ## Project Structure 91 | 92 | The export is split into two main parts: 93 | 94 | - Everything exported with the `API` prefix represents a payload you may get from or post to the REST API. 95 | 96 | - Everything exported with the `REST` prefix represents data that only comes from or is directly related to the REST API. 97 | 98 | - For endpoint options, they will follow the following structure: `REST` where the type represents what it will return. 99 | 100 | - For example, `RESTPostCompletePaymentJSONBody` or `RESTPostCompletePaymentResult`. 101 | 102 | - If a type ends with `Result`, then it represents the expected result by calling its accompanying route. 103 | 104 | - Anything else that is miscellaneous will be exported based on what it represents (for example the `routes` or `utils` parts) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@pinetwork-js/api-typing", 3 | "description": "Typing for the Pi Network SDK API", 4 | "version": "0.7.0", 5 | "main": "build/index.js", 6 | "types": "build/index.d.ts", 7 | "prettier": "@pinetwork-js/prettier-config", 8 | "exports": { 9 | ".": "./build/index.js", 10 | "./payloads": "./build/payloads/index.js", 11 | "./payloads/v2": "./build/payloads/v2/index.js", 12 | "./rest": "./build/rest/index.js", 13 | "./rest/v2": "./build/rest/v2/index.js", 14 | "./routes": "./build/routes/index.js", 15 | "./routes/v2": "./build/routes/v2/index.js" 16 | }, 17 | "scripts": { 18 | "prepack": "yarn build", 19 | "build": "tsc --build --clean && tsc", 20 | "lint": "eslint 'src/**/**.{js,ts}'", 21 | "lint:fix": "eslint 'src/**/**.{js,ts}' --fix", 22 | "format": "prettier 'src/**/**.{js,ts}' --write", 23 | "format:check": "prettier 'src/**/**.{js,ts}' --check" 24 | }, 25 | "author": "Brewal Derouet ", 26 | "license": "PiOS", 27 | "repository": { 28 | "type": "git", 29 | "url": "git+https://github.com/PiNetwork-js/api-typing.git" 30 | }, 31 | "homepage": "https://github.com/PiNetwork-js/api-typing#readme", 32 | "bugs": { 33 | "url": "https://github.com/PiNetwork-js/api-typing/issues" 34 | }, 35 | "devDependencies": { 36 | "@pinetwork-js/eslint-config": "^0.2.0", 37 | "@pinetwork-js/mrm-preset": "^0.2.1", 38 | "@pinetwork-js/prettier-config": "^0.1.0", 39 | "@types/node": "^18.15.11", 40 | "@typescript-eslint/eslint-plugin": "^5.58.0", 41 | "@typescript-eslint/parser": "^5.58.0", 42 | "eslint": "^8.38.0", 43 | "eslint-config-prettier": "^8.8.0", 44 | "eslint-import-resolver-node": "^0.3.7", 45 | "eslint-plugin-import": "^2.27.5", 46 | "eslint-plugin-prettier": "^4.2.1", 47 | "eslint-plugin-sonarjs": "^0.19.0", 48 | "eslint-plugin-unicorn": "^46.0.0", 49 | "prettier": "^2.8.7", 50 | "typescript": "^5.0.4" 51 | }, 52 | "files": [ 53 | "build" 54 | ], 55 | "keywords": [ 56 | "pi", 57 | "Pi Network", 58 | "api", 59 | "minepi", 60 | "typing" 61 | ], 62 | "packageManager": "yarn@3.5.0" 63 | } 64 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export type * from './payloads'; 2 | export type * as payloads from './payloads'; 3 | 4 | export type * from './rest'; 5 | export type * as rest from './rest'; 6 | 7 | export * from './routes'; 8 | export * as routes from './routes'; 9 | 10 | export type * from './utils'; 11 | export type * as utils from './utils'; 12 | -------------------------------------------------------------------------------- /src/payloads/error.ts: -------------------------------------------------------------------------------- 1 | export interface NetworkError { 2 | /** 3 | * The date when the error occurred 4 | */ 5 | time: string; 6 | 7 | /** 8 | * The action that was running when the error occurred 9 | */ 10 | call: string; 11 | 12 | /** 13 | * A message about the error 14 | */ 15 | message: string; 16 | 17 | /** 18 | * Some information returned by the error 19 | */ 20 | data: unknown; 21 | } 22 | -------------------------------------------------------------------------------- /src/payloads/index.ts: -------------------------------------------------------------------------------- 1 | export type * from './v2'; 2 | export type * from './error'; 3 | -------------------------------------------------------------------------------- /src/payloads/v2/auth.ts: -------------------------------------------------------------------------------- 1 | import type { LanguageCode } from '../../utils'; 2 | 3 | /** 4 | * List of available roles 5 | */ 6 | export type APIUserRoles = 'core_team' | 'email_verified' | 'event_hacker' | 'mega_mod' | 'moderator'; 7 | 8 | /** 9 | * List of available scopes 10 | */ 11 | export type APIUserScopes = 'payments' | 'platform' | 'preferred_language' | 'roles' | 'username' | 'wallet_address'; 12 | 13 | /** 14 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#userdto (not updated) 15 | */ 16 | export interface APIUser { 17 | /** 18 | * The UID of the user. 19 | */ 20 | uid: string; 21 | 22 | /** 23 | * The credentials of the user. 24 | */ 25 | credentials: APIUserCredentials; 26 | 27 | /** 28 | * The username of the user if `username` scope is specified. 29 | */ 30 | username?: string; 31 | 32 | /** 33 | * The roles of the user if `roles` scope is specified. 34 | */ 35 | roles?: APIUserRoles[]; 36 | 37 | /** 38 | * The preferred language of the user if `preferred_language` scope is specified. 39 | */ 40 | preferred_language?: LanguageCode; 41 | } 42 | 43 | /** 44 | * Structure representing a user credentials from the Pi Platform API. 45 | */ 46 | export interface APIUserCredentials { 47 | /** 48 | * The available scopes for the user. 49 | */ 50 | scopes: APIUserScopes[]; 51 | 52 | /** 53 | * Information on the validity of the scopes. 54 | */ 55 | valid_until: APIUserCredentialsValidation; 56 | } 57 | 58 | /** 59 | * Structure representing a user credentials validation information from the Pi Platform API 60 | */ 61 | export interface APIUserCredentialsValidation { 62 | /** 63 | * Timestamp of the scopes validity end date. 64 | */ 65 | timestamp: number; 66 | 67 | /** 68 | * ISO 8601 representation of the scopes validity end date. 69 | */ 70 | iso8601: string; 71 | } 72 | -------------------------------------------------------------------------------- /src/payloads/v2/index.ts: -------------------------------------------------------------------------------- 1 | export type * from './auth'; 2 | export type * from './payment'; 3 | export type * from './usage'; 4 | -------------------------------------------------------------------------------- /src/payloads/v2/payment.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * https://github.com/pi-apps/pi-ruby#create_payment 3 | */ 4 | export interface APIPartialPayment { 5 | /** 6 | * The payment amount 7 | */ 8 | amount: number; 9 | 10 | /** 11 | * A string provided by the developer, shown to the user 12 | */ 13 | memo: string; 14 | 15 | /** 16 | * An object provided by the developer for their own usage 17 | */ 18 | metadata: Record; 19 | 20 | /** 21 | * The user's app-specific ID 22 | */ 23 | uid: string; 24 | } 25 | 26 | export type APIPaymentDirection = 'app_to_user' | 'user_to_app'; 27 | export type APIPaymentNetwork = 'Pi Network' | 'Pi Testnet'; 28 | 29 | /** 30 | * https://github.com/pi-apps/pi-ruby#complete_payment 31 | */ 32 | export interface APIPayment extends Omit { 33 | /** 34 | * The payment identifier 35 | */ 36 | identifier: string; 37 | 38 | /** 39 | * The user's app-specific ID 40 | */ 41 | user_uid: string; 42 | 43 | /** 44 | * The sender address of the blockchain transaction 45 | */ 46 | from_address: string; 47 | 48 | /** 49 | * The recipient address of the blockchain transaction 50 | */ 51 | to_address: string; 52 | 53 | /** 54 | * The direction of the payment 55 | */ 56 | direction: APIPaymentDirection; 57 | 58 | /** 59 | * The payment's creation timestamp 60 | */ 61 | created_at: string; 62 | 63 | /** 64 | * The network of the payment 65 | */ 66 | network: APIPaymentNetwork; 67 | 68 | /** 69 | * Status flags representing the current state of this payment 70 | */ 71 | status: APIPaymentStatus; 72 | 73 | /** 74 | * Blockchain transaction data, this is null if no transaction has been made yet 75 | */ 76 | transaction: APIPaymentTransaction | null; 77 | } 78 | 79 | /** 80 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#paymentdto 81 | */ 82 | export interface APIPaymentStatus { 83 | /** 84 | * Server-Side Approval 85 | */ 86 | developer_approved: boolean; 87 | 88 | /** 89 | * Blockchain transaction verified 90 | */ 91 | transaction_verified: boolean; 92 | 93 | /** 94 | * Server-Side Completion 95 | */ 96 | developer_completed: boolean; 97 | 98 | /** 99 | * Cancelled by the developer or by Pi Network 100 | */ 101 | cancelled: boolean; 102 | 103 | /** 104 | * Cancelled by the user 105 | */ 106 | user_cancelled: boolean; 107 | } 108 | 109 | /** 110 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#paymentdto 111 | */ 112 | export interface APIPaymentTransaction { 113 | /** 114 | * The id of the blockchain transaction 115 | */ 116 | txid: string; 117 | 118 | /** 119 | * True if the transaction matches the payment, false otherwise 120 | */ 121 | verified: boolean; 122 | 123 | /** 124 | * A link to the operation on the Blockchain API 125 | */ 126 | _link: string; 127 | } 128 | 129 | export type APIIncompleteClientPayment = 130 | | { 131 | /** 132 | * Whether or not there is an incomplete payment 133 | */ 134 | exists: false; 135 | 136 | /** 137 | * The incomplete payment if there is one 138 | */ 139 | payment: null; 140 | } 141 | | { 142 | /** 143 | * Whether or not there is an incomplete payment 144 | */ 145 | exists: true; 146 | 147 | /** 148 | * The incomplete payment if there is one 149 | */ 150 | payment: APIPayment; 151 | }; 152 | -------------------------------------------------------------------------------- /src/payloads/v2/usage.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable-next-line @typescript-eslint/no-empty-interface */ 2 | export interface APIUsageTrackInfo {} 3 | -------------------------------------------------------------------------------- /src/rest/error.ts: -------------------------------------------------------------------------------- 1 | import type { NetworkError } from '../payloads'; 2 | 3 | /** 4 | * Undocumented route (POST /network/error) 5 | */ 6 | export interface RESTPostNetworkErrorJSONBody { 7 | /** 8 | * The error to send to the API 9 | */ 10 | error: NetworkError; 11 | } 12 | -------------------------------------------------------------------------------- /src/rest/index.ts: -------------------------------------------------------------------------------- 1 | export type * from './v2'; 2 | export type * from './error'; 3 | -------------------------------------------------------------------------------- /src/rest/v2/auth.ts: -------------------------------------------------------------------------------- 1 | import type { APIUser } from '../../payloads'; 2 | 3 | /** 4 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#access-a-users-resource 5 | */ 6 | export type RESTGetAuthenticatedUserResult = APIUser; 7 | -------------------------------------------------------------------------------- /src/rest/v2/index.ts: -------------------------------------------------------------------------------- 1 | export type * from './auth'; 2 | export type * from './payment'; 3 | export type * from './usage'; 4 | -------------------------------------------------------------------------------- /src/rest/v2/payment.ts: -------------------------------------------------------------------------------- 1 | import type { APIIncompleteClientPayment, APIPartialPayment, APIPayment } from '../../payloads'; 2 | 3 | /** 4 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#get-a-payment 5 | */ 6 | export type RESTGetPaymentResult = APIPayment; 7 | 8 | /** 9 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#create-a-payment 10 | */ 11 | export type RESTPostCreateUserToAppPaymentJSONBody = Omit; 12 | 13 | /** 14 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#create-a-payment 15 | */ 16 | export type RESTPostCreateUserToAppPaymentResult = APIPayment; 17 | 18 | /** 19 | * https://github.com/pi-apps/pi-ruby#create_payment 20 | */ 21 | export type RESTPostCreateAppToUserPaymentJSONBody = APIPartialPayment; 22 | 23 | /** 24 | * https://github.com/pi-apps/pi-ruby#create_payment 25 | */ 26 | export type RESTPostCreateAppToUserPaymentResult = APIPayment; 27 | 28 | /** 29 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#approve-a-payment 30 | */ 31 | export type RESTPostApprovePaymentResult = APIPayment; 32 | 33 | /** 34 | * Undocumented route (POST /payments/:payment_id/verify_transaction) 35 | */ 36 | export interface RESTPostVerifyTransactionJSONBody { 37 | /** 38 | * The id of the blockchain transaction 39 | */ 40 | txid: string; 41 | } 42 | 43 | /** 44 | * Undocumented route (POST /payments/:payment_id/verify_transaction) 45 | */ 46 | export type RESTPostVerifyTransactionResult = APIPayment; 47 | 48 | /** 49 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#complete-a-payment 50 | */ 51 | export interface RESTPostCompletePaymentJSONBody { 52 | /** 53 | * The id of the blockchain transaction 54 | */ 55 | txid: string; 56 | } 57 | 58 | /** 59 | * https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md#complete-a-payment 60 | */ 61 | export type RESTPostCompletePaymentResult = APIPayment; 62 | 63 | /** 64 | * Undocumented route (GET /payments/incomplete) 65 | */ 66 | export type RESTGetIncompleteClientPaymentResult = APIIncompleteClientPayment; 67 | 68 | /** 69 | * https://github.com/pi-apps/pi-ruby#get_incomplete_server_payments 70 | */ 71 | export type RESTGetIncompleteServerPaymentsResult = APIPayment[]; 72 | 73 | /** 74 | * https://github.com/pi-apps/pi-ruby#cancel_payment 75 | */ 76 | export type RESTPostCancelPaymentJSONBody = Record; 77 | 78 | /** 79 | * https://github.com/pi-apps/pi-ruby#cancel_payment 80 | */ 81 | export type RESTPostCancelPaymentResult = APIPayment; 82 | -------------------------------------------------------------------------------- /src/rest/v2/usage.ts: -------------------------------------------------------------------------------- 1 | import type { APIUsageTrackInfo } from '../../payloads'; 2 | 3 | /** 4 | * Undocumented route (POST /usage/track) 5 | */ 6 | export type RESTPostUsageTrackJSONBody = APIUsageTrackInfo; 7 | -------------------------------------------------------------------------------- /src/routes/error.ts: -------------------------------------------------------------------------------- 1 | import type { RESTPostNetworkErrorJSONBody } from '../rest'; 2 | import { routify } from './routify'; 3 | 4 | // eslint-disable-next-line @typescript-eslint/naming-convention 5 | type _ = undefined; 6 | 7 | export const postNetworkError = routify<_, RESTPostNetworkErrorJSONBody>`/network/error`({}); 8 | -------------------------------------------------------------------------------- /src/routes/index.ts: -------------------------------------------------------------------------------- 1 | export * from './routify'; 2 | export * from './v2'; 3 | export * from './error'; 4 | -------------------------------------------------------------------------------- /src/routes/routify.ts: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 2 | export type Route = string & { _: never }; 3 | 4 | export type RoutePayload = E extends Route ? R : void; 5 | export type RouteResult = E extends Route ? R : undefined; 6 | 7 | export function routify( 8 | literals: TemplateStringsArray, 9 | ...keys: K 10 | ) { 11 | return function (data: Record): Route { 12 | let endpoint = literals[0]; 13 | 14 | for (let index = 1; index < literals.length; index++) { 15 | const literal = literals[index]; 16 | const key: K[number] = keys[index - 1]; 17 | const value = data[key]; 18 | 19 | endpoint += `${value}${literal}`; 20 | } 21 | 22 | return endpoint as Route; 23 | }; 24 | } 25 | -------------------------------------------------------------------------------- /src/routes/v2/auth.ts: -------------------------------------------------------------------------------- 1 | import type * as api from '../../rest/v2'; 2 | import { routify } from '../routify'; 3 | 4 | export const getAuthenticatedUser = routify`v2/me`({}); 5 | -------------------------------------------------------------------------------- /src/routes/v2/index.ts: -------------------------------------------------------------------------------- 1 | export * from './auth'; 2 | export * from './payment'; 3 | export * from './usage'; 4 | -------------------------------------------------------------------------------- /src/routes/v2/payment.ts: -------------------------------------------------------------------------------- 1 | import type * as api from '../../rest/v2'; 2 | import { routify } from '../routify'; 3 | 4 | // eslint-disable-next-line @typescript-eslint/naming-convention 5 | type _ = undefined; 6 | 7 | export const createAppToUserPayment = routify< 8 | api.RESTPostCreateAppToUserPaymentResult, 9 | api.RESTPostCreateAppToUserPaymentJSONBody 10 | >`v2/payments`({}); 11 | 12 | export const createUserToAppPayment = routify< 13 | api.RESTPostCreateUserToAppPaymentResult, 14 | api.RESTPostCreateUserToAppPaymentJSONBody 15 | >`v2/payments/user_to_app`({}); 16 | 17 | export const getIncompleteClientPayment = routify`v2/payments/incomplete`({}); 18 | 19 | export const getIncompleteServerPayments = 20 | routify`v2/payments/incomplete_server_payments`({}); 21 | 22 | export const getPayment = routify`v2/payments/${'paymentId'}`; 23 | 24 | export const approvePayment = routify< 25 | api.RESTPostApprovePaymentResult, 26 | _, 27 | ['paymentId'] 28 | >`v2/payments/${'paymentId'}/approve`; 29 | 30 | export const verifyTransaction = routify< 31 | api.RESTPostVerifyTransactionResult, 32 | api.RESTPostVerifyTransactionJSONBody, 33 | ['paymentId'] 34 | >`v2/payments/${'paymentId'}/verify_transaction`; 35 | 36 | export const completePayment = routify< 37 | api.RESTPostCompletePaymentResult, 38 | api.RESTPostCompletePaymentJSONBody, 39 | ['paymentId'] 40 | >`v2/payments/${'paymentId'}/complete`; 41 | 42 | export const cancelPayment = routify< 43 | api.RESTPostCancelPaymentResult, 44 | api.RESTPostCancelPaymentJSONBody, 45 | ['paymentId'] 46 | >`v2/payments/${'paymentId'}/cancel`; 47 | -------------------------------------------------------------------------------- /src/routes/v2/usage.ts: -------------------------------------------------------------------------------- 1 | import type * as api from '../../rest/v2'; 2 | import { routify } from '../routify'; 3 | 4 | // eslint-disable-next-line @typescript-eslint/naming-convention 5 | type _ = undefined; 6 | 7 | export const trackUsage = routify<_, api.RESTPostUsageTrackJSONBody>`v2/usage/track`({}); 8 | -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | export type { LanguageCode } from './language-code'; 2 | -------------------------------------------------------------------------------- /src/utils/language-code.ts: -------------------------------------------------------------------------------- 1 | export type LanguageCode = 2 | | 'aa' 3 | | 'ab' 4 | | 'ae' 5 | | 'af' 6 | | 'ak' 7 | | 'am' 8 | | 'an' 9 | | 'ar' 10 | | 'as' 11 | | 'av' 12 | | 'ay' 13 | | 'az' 14 | | 'ba' 15 | | 'be' 16 | | 'bg' 17 | | 'bi' 18 | | 'bm' 19 | | 'bn' 20 | | 'bo' 21 | | 'br' 22 | | 'bs' 23 | | 'ca' 24 | | 'ce' 25 | | 'ch' 26 | | 'co' 27 | | 'cr' 28 | | 'cs' 29 | | 'cu' 30 | | 'cv' 31 | | 'cy' 32 | | 'da' 33 | | 'de' 34 | | 'dv' 35 | | 'dz' 36 | | 'ee' 37 | | 'el' 38 | | 'en' 39 | | 'eo' 40 | | 'es' 41 | | 'et' 42 | | 'eu' 43 | | 'fa' 44 | | 'ff' 45 | | 'fi' 46 | | 'fj' 47 | | 'fo' 48 | | 'fr' 49 | | 'fy' 50 | | 'ga' 51 | | 'gd' 52 | | 'gl' 53 | | 'gn' 54 | | 'gu' 55 | | 'gv' 56 | | 'ha' 57 | | 'he' 58 | | 'hi' 59 | | 'ho' 60 | | 'hr' 61 | | 'ht' 62 | | 'hu' 63 | | 'hy' 64 | | 'hz' 65 | | 'ia' 66 | | 'id' 67 | | 'ie' 68 | | 'ig' 69 | | 'ii' 70 | | 'ik' 71 | | 'io' 72 | | 'is' 73 | | 'it' 74 | | 'iu' 75 | | 'ja' 76 | | 'jv' 77 | | 'ka' 78 | | 'kg' 79 | | 'ki' 80 | | 'kj' 81 | | 'kk' 82 | | 'kl' 83 | | 'km' 84 | | 'kn' 85 | | 'ko' 86 | | 'kr' 87 | | 'ks' 88 | | 'ku' 89 | | 'kv' 90 | | 'kw' 91 | | 'ky' 92 | | 'la' 93 | | 'lb' 94 | | 'lg' 95 | | 'li' 96 | | 'ln' 97 | | 'lo' 98 | | 'lt' 99 | | 'lu' 100 | | 'lv' 101 | | 'mg' 102 | | 'mh' 103 | | 'mi' 104 | | 'mk' 105 | | 'ml' 106 | | 'mn' 107 | | 'mr' 108 | | 'ms' 109 | | 'mt' 110 | | 'my' 111 | | 'na' 112 | | 'nb' 113 | | 'nd' 114 | | 'ne' 115 | | 'ng' 116 | | 'nl' 117 | | 'nn' 118 | | 'no' 119 | | 'nr' 120 | | 'nv' 121 | | 'ny' 122 | | 'oc' 123 | | 'oj' 124 | | 'om' 125 | | 'or' 126 | | 'os' 127 | | 'pa' 128 | | 'pi' 129 | | 'pl' 130 | | 'ps' 131 | | 'pt' 132 | | 'qu' 133 | | 'rm' 134 | | 'rn' 135 | | 'ro' 136 | | 'ru' 137 | | 'rw' 138 | | 'sa' 139 | | 'sc' 140 | | 'sd' 141 | | 'se' 142 | | 'sg' 143 | | 'si' 144 | | 'sk' 145 | | 'sl' 146 | | 'sm' 147 | | 'sn' 148 | | 'so' 149 | | 'sq' 150 | | 'sr' 151 | | 'ss' 152 | | 'st' 153 | | 'su' 154 | | 'sv' 155 | | 'sw' 156 | | 'ta' 157 | | 'te' 158 | | 'tg' 159 | | 'th' 160 | | 'ti' 161 | | 'tk' 162 | | 'tl' 163 | | 'tn' 164 | | 'to' 165 | | 'tr' 166 | | 'ts' 167 | | 'tt' 168 | | 'tw' 169 | | 'ty' 170 | | 'ug' 171 | | 'uk' 172 | | 'ur' 173 | | 'uz' 174 | | 've' 175 | | 'vi' 176 | | 'vo' 177 | | 'wa' 178 | | 'wo' 179 | | 'xh' 180 | | 'yi' 181 | | 'yo' 182 | | 'za' 183 | | 'zh' 184 | | 'zu'; 185 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "esModuleInterop": true, 5 | "strict": true, 6 | "target": "ESNext", 7 | "lib": ["ESNext"], 8 | "outDir": "build", 9 | "declaration": true, 10 | "module": "CommonJS" 11 | }, 12 | "include": ["src"] 13 | } 14 | --------------------------------------------------------------------------------