@learncard/network-brain-client 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env ADDED
@@ -0,0 +1,7 @@
1
+ # Wait 60 seconds before connecting using these details, or login to https://console.neo4j.io to validate the Aura Instance is available
2
+ NEO4J_URI=neo4j+s://ab9edde2.databases.neo4j.io
3
+ NEO4J_USERNAME=neo4j
4
+ NEO4J_PASSWORD=V58sFdxds9E42A62bD1oA39AONg8fl8tNSMXCCQomow
5
+ AURA_INSTANCENAME=Instance01
6
+
7
+ SEED=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
package/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # @learncard/network-brain-client
2
+
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - [#213](https://github.com/learningeconomy/LearnCard/pull/213) [`2508bba`](https://github.com/learningeconomy/LearnCard/commit/2508bba1950faed5ebe4c92f6a5e3bf82114b9fe) Thanks [@TaylorBeeston](https://github.com/TaylorBeeston)! - Initial Release
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [[`2508bba`](https://github.com/learningeconomy/LearnCard/commit/2508bba1950faed5ebe4c92f6a5e3bf82114b9fe)]:
12
+ - @learncard/network-brain-service@1.0.0
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Learning Economy Foundation <sdk@learningeconomy.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+ Footer
23
+ © 2022 GitHub, Inc.
24
+ Footer navigation
25
+ Terms
@@ -0,0 +1,95 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ default: () => src_default,
24
+ getClient: () => getClient
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+ var import_client = require("@trpc/client");
28
+
29
+ // src/callbackLink.ts
30
+ var import_observable = require("@trpc/server/observable");
31
+ var callbackLink = /* @__PURE__ */ __name((callback) => {
32
+ return () => {
33
+ return ({ next, op }) => {
34
+ return (0, import_observable.observable)((observer) => {
35
+ let request = null;
36
+ let attempts = 0;
37
+ let isDone = false;
38
+ const attempt = /* @__PURE__ */ __name(() => {
39
+ attempts += 1;
40
+ request?.unsubscribe();
41
+ request = next(op).subscribe({
42
+ error: async (error) => {
43
+ if (attempts > 5 || error.data?.httpStatus !== 401) {
44
+ return observer.error(error);
45
+ }
46
+ await callback();
47
+ attempt();
48
+ },
49
+ next: (result) => observer.next(result),
50
+ complete: () => {
51
+ if (isDone)
52
+ observer.complete();
53
+ }
54
+ });
55
+ }, "attempt");
56
+ attempt();
57
+ return () => {
58
+ isDone = true;
59
+ request?.unsubscribe();
60
+ };
61
+ });
62
+ };
63
+ };
64
+ }, "callbackLink");
65
+
66
+ // src/index.ts
67
+ var getClient = /* @__PURE__ */ __name(async (url, didAuthFunction) => {
68
+ let challenges = [];
69
+ const challengeRequester = (0, import_client.createTRPCProxyClient)({
70
+ links: [
71
+ (0, import_client.httpBatchLink)({ url, headers: { Authorization: `Bearer ${await didAuthFunction()}` } })
72
+ ]
73
+ });
74
+ const getChallenges = /* @__PURE__ */ __name(async (amount = 95 + Math.round((Math.random() - 0.5) * 5)) => {
75
+ return challengeRequester.utilities.getChallenges.query({ amount });
76
+ }, "getChallenges");
77
+ challenges = await getChallenges();
78
+ const trpc = (0, import_client.createTRPCProxyClient)({
79
+ links: [
80
+ callbackLink(async () => {
81
+ challenges = await getChallenges();
82
+ }),
83
+ (0, import_client.httpBatchLink)({
84
+ url,
85
+ headers: async () => {
86
+ if (challenges.length === 0)
87
+ challenges.push(...await getChallenges());
88
+ return { Authorization: `Bearer ${await didAuthFunction(challenges.pop())}` };
89
+ }
90
+ })
91
+ ]
92
+ });
93
+ return trpc;
94
+ }, "getClient");
95
+ var src_default = getClient;
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/callbackLink.ts"],
4
+ "sourcesContent": ["import { createTRPCProxyClient, CreateTRPCProxyClient, httpBatchLink } from '@trpc/client';\nimport type { inferRouterInputs } from '@trpc/server';\nimport type { UnsignedVC, VC, VP, JWE } from '@learncard/types';\nimport type { AppRouter } from '@learncard/network-brain-service';\n\nimport { callbackLink } from './callbackLink';\n\ntype Inputs = inferRouterInputs<AppRouter>;\n\ntype Client = CreateTRPCProxyClient<AppRouter>;\n\ntype OverriddenClient = Client & {\n storage: Client['storage'] & {\n resolve: {\n query: (args: Inputs['storage']['resolve']) => Promise<VC | UnsignedVC | VP | JWE>;\n };\n };\n};\n\nexport const getClient = async (\n url: string,\n didAuthFunction: (challenge?: string) => Promise<string>\n) => {\n let challenges: string[] = [];\n\n const challengeRequester = createTRPCProxyClient<AppRouter>({\n links: [\n httpBatchLink({ url, headers: { Authorization: `Bearer ${await didAuthFunction()}` } }),\n ],\n }) as OverriddenClient;\n\n const getChallenges = async (\n amount = 95 + Math.round((Math.random() - 0.5) * 5)\n ): Promise<string[]> => {\n return challengeRequester.utilities.getChallenges.query({ amount });\n };\n\n challenges = await getChallenges();\n\n const trpc = createTRPCProxyClient<AppRouter>({\n links: [\n callbackLink(async () => {\n challenges = await getChallenges();\n }),\n httpBatchLink({\n url,\n headers: async () => {\n if (challenges.length === 0) challenges.push(...(await getChallenges()));\n\n return { Authorization: `Bearer ${await didAuthFunction(challenges.pop())}` };\n },\n }),\n ],\n }) as OverriddenClient;\n\n return trpc;\n};\n\nexport default getClient;\n", "import { TRPCLink } from '@trpc/client';\nimport { observable, Unsubscribable } from '@trpc/server/observable';\nimport type { AppRouter } from '@learncard/network-brain-service';\n\nexport const callbackLink = (callback: () => Promise<void>): TRPCLink<AppRouter> => {\n return () => {\n return ({ next, op }) => {\n return observable(observer => {\n let request: Unsubscribable | null = null;\n let attempts = 0;\n let isDone = false;\n\n const attempt = () => {\n attempts += 1;\n request?.unsubscribe();\n request = next(op).subscribe({\n error: async error => {\n if (attempts > 5 || error.data?.httpStatus !== 401) {\n return observer.error(error);\n }\n\n await callback();\n\n attempt();\n },\n next: result => observer.next(result),\n complete: () => {\n if (isDone) observer.complete();\n },\n });\n };\n\n attempt();\n\n return () => {\n isDone = true;\n request?.unsubscribe();\n };\n });\n };\n };\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA4E;;;ACC5E,wBAA2C;AAGpC,IAAM,eAAe,wBAAC,aAAuD;AAChF,SAAO,MAAM;AACT,WAAO,CAAC,EAAE,MAAM,GAAG,MAAM;AACrB,iBAAO,8BAAW,cAAY;AAC1B,YAAI,UAAiC;AACrC,YAAI,WAAW;AACf,YAAI,SAAS;AAEb,cAAM,UAAU,6BAAM;AAClB,sBAAY;AACZ,mBAAS,YAAY;AACrB,oBAAU,KAAK,EAAE,EAAE,UAAU;AAAA,YACzB,OAAO,OAAM,UAAS;AAClB,kBAAI,WAAW,KAAK,MAAM,MAAM,eAAe,KAAK;AAChD,uBAAO,SAAS,MAAM,KAAK;AAAA,cAC/B;AAEA,oBAAM,SAAS;AAEf,sBAAQ;AAAA,YACZ;AAAA,YACA,MAAM,YAAU,SAAS,KAAK,MAAM;AAAA,YACpC,UAAU,MAAM;AACZ,kBAAI;AAAQ,yBAAS,SAAS;AAAA,YAClC;AAAA,UACJ,CAAC;AAAA,QACL,GAlBgB;AAoBhB,gBAAQ;AAER,eAAO,MAAM;AACT,mBAAS;AACT,mBAAS,YAAY;AAAA,QACzB;AAAA,MACJ,CAAC;AAAA,IACL;AAAA,EACJ;AACJ,GArC4B;;;ADerB,IAAM,YAAY,8BACrB,KACA,oBACC;AACD,MAAI,aAAuB,CAAC;AAE5B,QAAM,yBAAqB,qCAAiC;AAAA,IACxD,OAAO;AAAA,UACH,6BAAc,EAAE,KAAK,SAAS,EAAE,eAAe,UAAU,MAAM,gBAAgB,IAAI,EAAE,CAAC;AAAA,IAC1F;AAAA,EACJ,CAAC;AAED,QAAM,gBAAgB,8BAClB,SAAS,KAAK,KAAK,OAAO,KAAK,OAAO,IAAI,OAAO,CAAC,MAC9B;AACpB,WAAO,mBAAmB,UAAU,cAAc,MAAM,EAAE,OAAO,CAAC;AAAA,EACtE,GAJsB;AAMtB,eAAa,MAAM,cAAc;AAEjC,QAAM,WAAO,qCAAiC;AAAA,IAC1C,OAAO;AAAA,MACH,aAAa,YAAY;AACrB,qBAAa,MAAM,cAAc;AAAA,MACrC,CAAC;AAAA,UACD,6BAAc;AAAA,QACV;AAAA,QACA,SAAS,YAAY;AACjB,cAAI,WAAW,WAAW;AAAG,uBAAW,KAAK,GAAI,MAAM,cAAc,CAAE;AAEvE,iBAAO,EAAE,eAAe,UAAU,MAAM,gBAAgB,WAAW,IAAI,CAAC,IAAI;AAAA,QAChF;AAAA,MACJ,CAAC;AAAA,IACL;AAAA,EACJ,CAAC;AAED,SAAO;AACX,GArCyB;AAuCzB,IAAO,cAAQ;",
6
+ "names": []
7
+ }
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var a=(t,e)=>l(t,"name",{value:e,configurable:!0});var f=(t,e)=>{for(var n in e)l(t,n,{get:e[n],enumerable:!0})},h=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of b(e))!d.call(t,r)&&r!==n&&l(t,r,{get:()=>e[r],enumerable:!(i=y(e,r))||i.enumerable});return t};var R=t=>h(l({},"__esModule",{value:!0}),t);var k={};f(k,{default:()=>P,getClient:()=>g});module.exports=R(k);var s=require("@trpc/client");var m=require("@trpc/server/observable");var C=a(t=>()=>({next:e,op:n})=>(0,m.observable)(i=>{let r=null,u=0,o=!1,c=a(()=>{u+=1,r?.unsubscribe(),r=e(n).subscribe({error:async p=>{if(u>5||p.data?.httpStatus!==401)return i.error(p);await t(),c()},next:p=>i.next(p),complete:()=>{o&&i.complete()}})},"attempt");return c(),()=>{o=!0,r?.unsubscribe()}}),"callbackLink");var g=a(async(t,e)=>{let n=[],i=(0,s.createTRPCProxyClient)({links:[(0,s.httpBatchLink)({url:t,headers:{Authorization:`Bearer ${await e()}`}})]}),r=a(async(o=95+Math.round((Math.random()-.5)*5))=>i.utilities.getChallenges.query({amount:o}),"getChallenges");return n=await r(),(0,s.createTRPCProxyClient)({links:[C(async()=>{n=await r()}),(0,s.httpBatchLink)({url:t,headers:async()=>(n.length===0&&n.push(...await r()),{Authorization:`Bearer ${await e(n.pop())}`})})]})},"getClient"),P=g;
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/callbackLink.ts"],
4
+ "sourcesContent": ["import { createTRPCProxyClient, CreateTRPCProxyClient, httpBatchLink } from '@trpc/client';\nimport type { inferRouterInputs } from '@trpc/server';\nimport type { UnsignedVC, VC, VP, JWE } from '@learncard/types';\nimport type { AppRouter } from '@learncard/network-brain-service';\n\nimport { callbackLink } from './callbackLink';\n\ntype Inputs = inferRouterInputs<AppRouter>;\n\ntype Client = CreateTRPCProxyClient<AppRouter>;\n\ntype OverriddenClient = Client & {\n storage: Client['storage'] & {\n resolve: {\n query: (args: Inputs['storage']['resolve']) => Promise<VC | UnsignedVC | VP | JWE>;\n };\n };\n};\n\nexport const getClient = async (\n url: string,\n didAuthFunction: (challenge?: string) => Promise<string>\n) => {\n let challenges: string[] = [];\n\n const challengeRequester = createTRPCProxyClient<AppRouter>({\n links: [\n httpBatchLink({ url, headers: { Authorization: `Bearer ${await didAuthFunction()}` } }),\n ],\n }) as OverriddenClient;\n\n const getChallenges = async (\n amount = 95 + Math.round((Math.random() - 0.5) * 5)\n ): Promise<string[]> => {\n return challengeRequester.utilities.getChallenges.query({ amount });\n };\n\n challenges = await getChallenges();\n\n const trpc = createTRPCProxyClient<AppRouter>({\n links: [\n callbackLink(async () => {\n challenges = await getChallenges();\n }),\n httpBatchLink({\n url,\n headers: async () => {\n if (challenges.length === 0) challenges.push(...(await getChallenges()));\n\n return { Authorization: `Bearer ${await didAuthFunction(challenges.pop())}` };\n },\n }),\n ],\n }) as OverriddenClient;\n\n return trpc;\n};\n\nexport default getClient;\n", "import { TRPCLink } from '@trpc/client';\nimport { observable, Unsubscribable } from '@trpc/server/observable';\nimport type { AppRouter } from '@learncard/network-brain-service';\n\nexport const callbackLink = (callback: () => Promise<void>): TRPCLink<AppRouter> => {\n return () => {\n return ({ next, op }) => {\n return observable(observer => {\n let request: Unsubscribable | null = null;\n let attempts = 0;\n let isDone = false;\n\n const attempt = () => {\n attempts += 1;\n request?.unsubscribe();\n request = next(op).subscribe({\n error: async error => {\n if (attempts > 5 || error.data?.httpStatus !== 401) {\n return observer.error(error);\n }\n\n await callback();\n\n attempt();\n },\n next: result => observer.next(result),\n complete: () => {\n if (isDone) observer.complete();\n },\n });\n };\n\n attempt();\n\n return () => {\n isDone = true;\n request?.unsubscribe();\n };\n });\n };\n };\n};\n"],
5
+ "mappings": "+cAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,cAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAA4E,wBCC5E,IAAAC,EAA2C,mCAGpC,IAAMC,EAAeC,EAACC,GAClB,IACI,CAAC,CAAE,KAAAC,EAAM,GAAAC,CAAG,OACR,cAAWC,GAAY,CAC1B,IAAIC,EAAiC,KACjCC,EAAW,EACXC,EAAS,GAEPC,EAAUR,EAAA,IAAM,CAClBM,GAAY,EACZD,GAAS,YAAY,EACrBA,EAAUH,EAAKC,CAAE,EAAE,UAAU,CACzB,MAAO,MAAMM,GAAS,CAClB,GAAIH,EAAW,GAAKG,EAAM,MAAM,aAAe,IAC3C,OAAOL,EAAS,MAAMK,CAAK,EAG/B,MAAMR,EAAS,EAEfO,EAAQ,CACZ,EACA,KAAME,GAAUN,EAAS,KAAKM,CAAM,EACpC,SAAU,IAAM,CACRH,GAAQH,EAAS,SAAS,CAClC,CACJ,CAAC,CACL,EAlBgB,WAoBhB,OAAAI,EAAQ,EAED,IAAM,CACTD,EAAS,GACTF,GAAS,YAAY,CACzB,CACJ,CAAC,EAlCe,gBDerB,IAAMM,EAAYC,EAAA,MACrBC,EACAC,IACC,CACD,IAAIC,EAAuB,CAAC,EAEtBC,KAAqB,yBAAiC,CACxD,MAAO,IACH,iBAAc,CAAE,IAAAH,EAAK,QAAS,CAAE,cAAe,UAAU,MAAMC,EAAgB,GAAI,CAAE,CAAC,CAC1F,CACJ,CAAC,EAEKG,EAAgBL,EAAA,MAClBM,EAAS,GAAK,KAAK,OAAO,KAAK,OAAO,EAAI,IAAO,CAAC,IAE3CF,EAAmB,UAAU,cAAc,MAAM,CAAE,OAAAE,CAAO,CAAC,EAHhD,iBAMtB,OAAAH,EAAa,MAAME,EAAc,KAEpB,yBAAiC,CAC1C,MAAO,CACHE,EAAa,SAAY,CACrBJ,EAAa,MAAME,EAAc,CACrC,CAAC,KACD,iBAAc,CACV,IAAAJ,EACA,QAAS,UACDE,EAAW,SAAW,GAAGA,EAAW,KAAK,GAAI,MAAME,EAAc,CAAE,EAEhE,CAAE,cAAe,UAAU,MAAMH,EAAgBC,EAAW,IAAI,CAAC,GAAI,EAEpF,CAAC,CACL,CACJ,CAAC,CAGL,EArCyB,aAuClBK,EAAQT",
6
+ "names": ["src_exports", "__export", "src_default", "getClient", "__toCommonJS", "import_client", "import_observable", "callbackLink", "__name", "callback", "next", "op", "observer", "request", "attempts", "isDone", "attempt", "error", "result", "getClient", "__name", "url", "didAuthFunction", "challenges", "challengeRequester", "getChallenges", "amount", "callbackLink", "src_default"]
7
+ }
@@ -0,0 +1,77 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/index.ts
5
+ import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";
6
+
7
+ // src/callbackLink.ts
8
+ import { observable } from "@trpc/server/observable";
9
+ var callbackLink = /* @__PURE__ */ __name((callback) => {
10
+ return () => {
11
+ return ({ next, op }) => {
12
+ return observable((observer) => {
13
+ let request = null;
14
+ let attempts = 0;
15
+ let isDone = false;
16
+ const attempt = /* @__PURE__ */ __name(() => {
17
+ attempts += 1;
18
+ request?.unsubscribe();
19
+ request = next(op).subscribe({
20
+ error: async (error) => {
21
+ if (attempts > 5 || error.data?.httpStatus !== 401) {
22
+ return observer.error(error);
23
+ }
24
+ await callback();
25
+ attempt();
26
+ },
27
+ next: (result) => observer.next(result),
28
+ complete: () => {
29
+ if (isDone)
30
+ observer.complete();
31
+ }
32
+ });
33
+ }, "attempt");
34
+ attempt();
35
+ return () => {
36
+ isDone = true;
37
+ request?.unsubscribe();
38
+ };
39
+ });
40
+ };
41
+ };
42
+ }, "callbackLink");
43
+
44
+ // src/index.ts
45
+ var getClient = /* @__PURE__ */ __name(async (url, didAuthFunction) => {
46
+ let challenges = [];
47
+ const challengeRequester = createTRPCProxyClient({
48
+ links: [
49
+ httpBatchLink({ url, headers: { Authorization: `Bearer ${await didAuthFunction()}` } })
50
+ ]
51
+ });
52
+ const getChallenges = /* @__PURE__ */ __name(async (amount = 95 + Math.round((Math.random() - 0.5) * 5)) => {
53
+ return challengeRequester.utilities.getChallenges.query({ amount });
54
+ }, "getChallenges");
55
+ challenges = await getChallenges();
56
+ const trpc = createTRPCProxyClient({
57
+ links: [
58
+ callbackLink(async () => {
59
+ challenges = await getChallenges();
60
+ }),
61
+ httpBatchLink({
62
+ url,
63
+ headers: async () => {
64
+ if (challenges.length === 0)
65
+ challenges.push(...await getChallenges());
66
+ return { Authorization: `Bearer ${await didAuthFunction(challenges.pop())}` };
67
+ }
68
+ })
69
+ ]
70
+ });
71
+ return trpc;
72
+ }, "getClient");
73
+ var src_default = getClient;
74
+ export {
75
+ src_default as default,
76
+ getClient
77
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/callbackLink.ts"],
4
+ "sourcesContent": ["import { createTRPCProxyClient, CreateTRPCProxyClient, httpBatchLink } from '@trpc/client';\nimport type { inferRouterInputs } from '@trpc/server';\nimport type { UnsignedVC, VC, VP, JWE } from '@learncard/types';\nimport type { AppRouter } from '@learncard/network-brain-service';\n\nimport { callbackLink } from './callbackLink';\n\ntype Inputs = inferRouterInputs<AppRouter>;\n\ntype Client = CreateTRPCProxyClient<AppRouter>;\n\ntype OverriddenClient = Client & {\n storage: Client['storage'] & {\n resolve: {\n query: (args: Inputs['storage']['resolve']) => Promise<VC | UnsignedVC | VP | JWE>;\n };\n };\n};\n\nexport const getClient = async (\n url: string,\n didAuthFunction: (challenge?: string) => Promise<string>\n) => {\n let challenges: string[] = [];\n\n const challengeRequester = createTRPCProxyClient<AppRouter>({\n links: [\n httpBatchLink({ url, headers: { Authorization: `Bearer ${await didAuthFunction()}` } }),\n ],\n }) as OverriddenClient;\n\n const getChallenges = async (\n amount = 95 + Math.round((Math.random() - 0.5) * 5)\n ): Promise<string[]> => {\n return challengeRequester.utilities.getChallenges.query({ amount });\n };\n\n challenges = await getChallenges();\n\n const trpc = createTRPCProxyClient<AppRouter>({\n links: [\n callbackLink(async () => {\n challenges = await getChallenges();\n }),\n httpBatchLink({\n url,\n headers: async () => {\n if (challenges.length === 0) challenges.push(...(await getChallenges()));\n\n return { Authorization: `Bearer ${await didAuthFunction(challenges.pop())}` };\n },\n }),\n ],\n }) as OverriddenClient;\n\n return trpc;\n};\n\nexport default getClient;\n", "import { TRPCLink } from '@trpc/client';\nimport { observable, Unsubscribable } from '@trpc/server/observable';\nimport type { AppRouter } from '@learncard/network-brain-service';\n\nexport const callbackLink = (callback: () => Promise<void>): TRPCLink<AppRouter> => {\n return () => {\n return ({ next, op }) => {\n return observable(observer => {\n let request: Unsubscribable | null = null;\n let attempts = 0;\n let isDone = false;\n\n const attempt = () => {\n attempts += 1;\n request?.unsubscribe();\n request = next(op).subscribe({\n error: async error => {\n if (attempts > 5 || error.data?.httpStatus !== 401) {\n return observer.error(error);\n }\n\n await callback();\n\n attempt();\n },\n next: result => observer.next(result),\n complete: () => {\n if (isDone) observer.complete();\n },\n });\n };\n\n attempt();\n\n return () => {\n isDone = true;\n request?.unsubscribe();\n };\n });\n };\n };\n};\n"],
5
+ "mappings": ";;;;AAAA,SAAS,uBAA8C,qBAAqB;;;ACC5E,SAAS,kBAAkC;AAGpC,IAAM,eAAe,wBAAC,aAAuD;AAChF,SAAO,MAAM;AACT,WAAO,CAAC,EAAE,MAAM,GAAG,MAAM;AACrB,aAAO,WAAW,cAAY;AAC1B,YAAI,UAAiC;AACrC,YAAI,WAAW;AACf,YAAI,SAAS;AAEb,cAAM,UAAU,6BAAM;AAClB,sBAAY;AACZ,mBAAS,YAAY;AACrB,oBAAU,KAAK,EAAE,EAAE,UAAU;AAAA,YACzB,OAAO,OAAM,UAAS;AAClB,kBAAI,WAAW,KAAK,MAAM,MAAM,eAAe,KAAK;AAChD,uBAAO,SAAS,MAAM,KAAK;AAAA,cAC/B;AAEA,oBAAM,SAAS;AAEf,sBAAQ;AAAA,YACZ;AAAA,YACA,MAAM,YAAU,SAAS,KAAK,MAAM;AAAA,YACpC,UAAU,MAAM;AACZ,kBAAI;AAAQ,yBAAS,SAAS;AAAA,YAClC;AAAA,UACJ,CAAC;AAAA,QACL,GAlBgB;AAoBhB,gBAAQ;AAER,eAAO,MAAM;AACT,mBAAS;AACT,mBAAS,YAAY;AAAA,QACzB;AAAA,MACJ,CAAC;AAAA,IACL;AAAA,EACJ;AACJ,GArC4B;;;ADerB,IAAM,YAAY,8BACrB,KACA,oBACC;AACD,MAAI,aAAuB,CAAC;AAE5B,QAAM,qBAAqB,sBAAiC;AAAA,IACxD,OAAO;AAAA,MACH,cAAc,EAAE,KAAK,SAAS,EAAE,eAAe,UAAU,MAAM,gBAAgB,IAAI,EAAE,CAAC;AAAA,IAC1F;AAAA,EACJ,CAAC;AAED,QAAM,gBAAgB,8BAClB,SAAS,KAAK,KAAK,OAAO,KAAK,OAAO,IAAI,OAAO,CAAC,MAC9B;AACpB,WAAO,mBAAmB,UAAU,cAAc,MAAM,EAAE,OAAO,CAAC;AAAA,EACtE,GAJsB;AAMtB,eAAa,MAAM,cAAc;AAEjC,QAAM,OAAO,sBAAiC;AAAA,IAC1C,OAAO;AAAA,MACH,aAAa,YAAY;AACrB,qBAAa,MAAM,cAAc;AAAA,MACrC,CAAC;AAAA,MACD,cAAc;AAAA,QACV;AAAA,QACA,SAAS,YAAY;AACjB,cAAI,WAAW,WAAW;AAAG,uBAAW,KAAK,GAAI,MAAM,cAAc,CAAE;AAEvE,iBAAO,EAAE,eAAe,UAAU,MAAM,gBAAgB,WAAW,IAAI,CAAC,IAAI;AAAA,QAChF;AAAA,MACJ,CAAC;AAAA,IACL;AAAA,EACJ,CAAC;AAED,SAAO;AACX,GArCyB;AAuCzB,IAAO,cAAQ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,3 @@
1
+ import { TRPCLink } from '@trpc/client';
2
+ import type { AppRouter } from '@learncard/network-brain-service';
3
+ export declare const callbackLink: (callback: () => Promise<void>) => TRPCLink<AppRouter>;
@@ -0,0 +1,15 @@
1
+ import { CreateTRPCProxyClient } from '@trpc/client';
2
+ import type { inferRouterInputs } from '@trpc/server';
3
+ import type { UnsignedVC, VC, VP, JWE } from '@learncard/types';
4
+ import type { AppRouter } from '@learncard/network-brain-service';
5
+ type Inputs = inferRouterInputs<AppRouter>;
6
+ type Client = CreateTRPCProxyClient<AppRouter>;
7
+ type OverriddenClient = Client & {
8
+ storage: Client['storage'] & {
9
+ resolve: {
10
+ query: (args: Inputs['storage']['resolve']) => Promise<VC | UnsignedVC | VP | JWE>;
11
+ };
12
+ };
13
+ };
14
+ export declare const getClient: (url: string, didAuthFunction: (challenge?: string) => Promise<string>) => Promise<OverriddenClient>;
15
+ export default getClient;
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === 'production') {
4
+ module.exports = require('./brain-client.cjs.production.min.js');
5
+ } else {
6
+ module.exports = require('./brain-client.cjs.development.js');
7
+ }
package/esbuild.mjs ADDED
@@ -0,0 +1,25 @@
1
+ import { build } from 'esbuild';
2
+
3
+ const startTime = Date.now();
4
+
5
+ console.log('🎁 Building main bundle...');
6
+
7
+ const finalBuildObj = {
8
+ entryPoints: ['src/index.ts'],
9
+ platform: 'node',
10
+ bundle: true,
11
+ format: 'cjs',
12
+ outdir: 'dist',
13
+ target: 'node18',
14
+ external: [],
15
+ minify: true,
16
+ };
17
+
18
+ if (process.env.NODE_ENV !== 'production') {
19
+ finalBuildObj.sourcemap = 'inline';
20
+ finalBuildObj.minify = false;
21
+ }
22
+
23
+ build(finalBuildObj).then(() => {
24
+ console.log(`🎁 Done building main bundle! (${Date.now() - startTime}ms)`);
25
+ });
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@learncard/network-brain-client",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "module": "./dist/brain-client.esm.js",
7
+ "types": "dist/index.d.ts",
8
+ "keywords": [],
9
+ "author": "Learning Economy Foundation (www.learningeconomy.io)",
10
+ "license": "MIT",
11
+ "devDependencies": {
12
+ "dts-bundle-generator": "^6.10.0",
13
+ "esbuild": "^0.16.16",
14
+ "@learncard/types": "5.2.0"
15
+ },
16
+ "dependencies": {
17
+ "@trpc/client": "^10.9.0",
18
+ "@trpc/server": "^10.9.0",
19
+ "@learncard/network-brain-service": "1.0.0"
20
+ },
21
+ "scripts": {
22
+ "build": "node ./scripts/build.mjs && shx cp ./scripts/mixedEntypoint.js ./dist/index.js && tsc --p tsconfig.json"
23
+ }
24
+ }
package/project.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "$schema": "../../../node_modules/nx/schemas/project-schema.json",
3
+ "name": "network-brain-client",
4
+ "sourceRoot": "packages/learn-card-network/brain-client/src",
5
+ "projectType": "library",
6
+ "root": "packages/learn-card-network/brain-client",
7
+ "tags": [],
8
+ "implicitDependencies": ["types", "network-brain-service"],
9
+ "namedInputs": {
10
+ "source": ["{projectRoot}/src/**/*"],
11
+ "scripts": ["{projectRoot}/scripts/**/*"],
12
+ "dist": ["{projectRoot}/dist/**/*"]
13
+ },
14
+ "targets": {
15
+ "build": {
16
+ "executor": "nx:run-script",
17
+ "inputs": ["source", "scripts"],
18
+ "options": {
19
+ "script": "build"
20
+ }
21
+ }
22
+ }
23
+ }
24
+
@@ -0,0 +1,10 @@
1
+ {
2
+ "root": false,
3
+ "env": {
4
+ "node": true
5
+ },
6
+ "rules": {
7
+ "no-console": "off",
8
+ "@typescript-eslint/no-var-requires": "off"
9
+ }
10
+ }
@@ -0,0 +1,89 @@
1
+ import path from 'path';
2
+
3
+ import esbuild from 'esbuild';
4
+ import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve';
5
+ import rimraf from 'rimraf';
6
+
7
+ const nodeResolveExternal = NodeResolvePlugin({
8
+ extensions: ['.ts', '.js', '.tsx', '.jsx', '.cjs', '.mjs'],
9
+ onResolved: resolved => {
10
+ if (resolved.includes('node_modules')) {
11
+ return {
12
+ external: true,
13
+ };
14
+ }
15
+ return resolved;
16
+ },
17
+ });
18
+
19
+ const configurations = [
20
+ {
21
+ keepNames: true,
22
+ bundle: true,
23
+ sourcemap: 'external',
24
+ incremental: true,
25
+ tsconfig: 'tsconfig.json',
26
+ plugins: [nodeResolveExternal],
27
+ entryPoints: ['src/index.ts'],
28
+ format: 'cjs',
29
+ outfile: 'dist/brain-client.cjs.development.js',
30
+ },
31
+ {
32
+ keepNames: true,
33
+ bundle: true,
34
+ sourcemap: 'external',
35
+ incremental: true,
36
+ tsconfig: 'tsconfig.json',
37
+ plugins: [nodeResolveExternal],
38
+ entryPoints: ['src/index.ts'],
39
+ minify: true,
40
+ format: 'cjs',
41
+ outfile: 'dist/brain-client.cjs.production.min.js',
42
+ },
43
+ {
44
+ keepNames: true,
45
+ bundle: true,
46
+ sourcemap: 'external',
47
+ incremental: true,
48
+ tsconfig: 'tsconfig.json',
49
+ plugins: [nodeResolveExternal],
50
+ entryPoints: ['src/index.ts'],
51
+ format: 'esm',
52
+ outfile: 'dist/brain-client.esm.js',
53
+ },
54
+ ];
55
+
56
+ function asyncRimraf(path) {
57
+ return new Promise((resolve, reject) => {
58
+ rimraf(path, err => {
59
+ if (err) {
60
+ reject(err);
61
+ } else {
62
+ resolve();
63
+ }
64
+ });
65
+ });
66
+ }
67
+
68
+ function main() {
69
+ Promise.all(
70
+ configurations.map(config => {
71
+ var dir = config.outdir || path.dirname(config.outfile);
72
+ asyncRimraf(dir).catch(() => {
73
+ console.log('Unable to delete directory', dir);
74
+ });
75
+ })
76
+ ).then(() => {
77
+ Promise.all(configurations.map(config => esbuild.build(config)))
78
+ .then(() => {
79
+ console.log('✔ Build successful');
80
+ process.exit(0);
81
+ })
82
+ .catch(err => {
83
+ console.error('❌ Build failed');
84
+ process.exit(1);
85
+ });
86
+ });
87
+ }
88
+
89
+ main();
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ if (process.env.NODE_ENV === 'production') {
4
+ module.exports = require('./brain-client.cjs.production.min.js');
5
+ } else {
6
+ module.exports = require('./brain-client.cjs.development.js');
7
+ }
@@ -0,0 +1,42 @@
1
+ import { TRPCLink } from '@trpc/client';
2
+ import { observable, Unsubscribable } from '@trpc/server/observable';
3
+ import type { AppRouter } from '@learncard/network-brain-service';
4
+
5
+ export const callbackLink = (callback: () => Promise<void>): TRPCLink<AppRouter> => {
6
+ return () => {
7
+ return ({ next, op }) => {
8
+ return observable(observer => {
9
+ let request: Unsubscribable | null = null;
10
+ let attempts = 0;
11
+ let isDone = false;
12
+
13
+ const attempt = () => {
14
+ attempts += 1;
15
+ request?.unsubscribe();
16
+ request = next(op).subscribe({
17
+ error: async error => {
18
+ if (attempts > 5 || error.data?.httpStatus !== 401) {
19
+ return observer.error(error);
20
+ }
21
+
22
+ await callback();
23
+
24
+ attempt();
25
+ },
26
+ next: result => observer.next(result),
27
+ complete: () => {
28
+ if (isDone) observer.complete();
29
+ },
30
+ });
31
+ };
32
+
33
+ attempt();
34
+
35
+ return () => {
36
+ isDone = true;
37
+ request?.unsubscribe();
38
+ };
39
+ });
40
+ };
41
+ };
42
+ };
package/src/index.ts ADDED
@@ -0,0 +1,59 @@
1
+ import { createTRPCProxyClient, CreateTRPCProxyClient, httpBatchLink } from '@trpc/client';
2
+ import type { inferRouterInputs } from '@trpc/server';
3
+ import type { UnsignedVC, VC, VP, JWE } from '@learncard/types';
4
+ import type { AppRouter } from '@learncard/network-brain-service';
5
+
6
+ import { callbackLink } from './callbackLink';
7
+
8
+ type Inputs = inferRouterInputs<AppRouter>;
9
+
10
+ type Client = CreateTRPCProxyClient<AppRouter>;
11
+
12
+ type OverriddenClient = Client & {
13
+ storage: Client['storage'] & {
14
+ resolve: {
15
+ query: (args: Inputs['storage']['resolve']) => Promise<VC | UnsignedVC | VP | JWE>;
16
+ };
17
+ };
18
+ };
19
+
20
+ export const getClient = async (
21
+ url: string,
22
+ didAuthFunction: (challenge?: string) => Promise<string>
23
+ ) => {
24
+ let challenges: string[] = [];
25
+
26
+ const challengeRequester = createTRPCProxyClient<AppRouter>({
27
+ links: [
28
+ httpBatchLink({ url, headers: { Authorization: `Bearer ${await didAuthFunction()}` } }),
29
+ ],
30
+ }) as OverriddenClient;
31
+
32
+ const getChallenges = async (
33
+ amount = 95 + Math.round((Math.random() - 0.5) * 5)
34
+ ): Promise<string[]> => {
35
+ return challengeRequester.utilities.getChallenges.query({ amount });
36
+ };
37
+
38
+ challenges = await getChallenges();
39
+
40
+ const trpc = createTRPCProxyClient<AppRouter>({
41
+ links: [
42
+ callbackLink(async () => {
43
+ challenges = await getChallenges();
44
+ }),
45
+ httpBatchLink({
46
+ url,
47
+ headers: async () => {
48
+ if (challenges.length === 0) challenges.push(...(await getChallenges()));
49
+
50
+ return { Authorization: `Bearer ${await didAuthFunction(challenges.pop())}` };
51
+ },
52
+ }),
53
+ ],
54
+ }) as OverriddenClient;
55
+
56
+ return trpc;
57
+ };
58
+
59
+ export default getClient;
package/tsconfig.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "compilerOptions": {
3
+ "lib": ["es2022"],
4
+ "module": "esnext",
5
+ "moduleResolution": "node",
6
+ "resolveJsonModule": true,
7
+ "removeComments": true,
8
+ "preserveConstEnums": true,
9
+ "strict": true,
10
+ "alwaysStrict": true,
11
+ "strictNullChecks": true,
12
+ "noUncheckedIndexedAccess": true,
13
+
14
+ "noImplicitAny": true,
15
+ "noImplicitReturns": true,
16
+ "noImplicitThis": true,
17
+ "noUnusedLocals": true,
18
+ "noUnusedParameters": true,
19
+ "allowUnreachableCode": false,
20
+ "noFallthroughCasesInSwitch": true,
21
+
22
+ "target": "es2022",
23
+ "outDir": "dist",
24
+ "rootDir": "src",
25
+ "declaration": true,
26
+ "emitDeclarationOnly": true,
27
+ "sourceMap": true,
28
+
29
+ "esModuleInterop": true,
30
+ "allowSyntheticDefaultImports": true,
31
+ "allowJs": false,
32
+ "skipLibCheck": true,
33
+ "forceConsistentCasingInFileNames": true
34
+ },
35
+ "exclude": ["./dist/**/*", "./node_modules/**/*"]
36
+ }