@elysiajs/eden 0.3.0-exp-230224.1831 → 0.3.0-rc.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/.eslintrc ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "env": {
3
+ "es2021": true,
4
+ "node": true
5
+ },
6
+ "extends": [
7
+ "eslint:recommended",
8
+ "plugin:@typescript-eslint/recommended"
9
+ ],
10
+ "parser": "@typescript-eslint/parser",
11
+ "parserOptions": {
12
+ "ecmaVersion": "latest",
13
+ "sourceType": "module"
14
+ },
15
+ "plugins": [
16
+ "@typescript-eslint"
17
+ ],
18
+ "rules": {
19
+ "@typescript-eslint/ban-types": "off",
20
+ "@typescript-eslint/no-explicit-any": "off"
21
+ },
22
+ "ignorePatterns": ["example/*", "tests/**/*"]
23
+ }
@@ -0,0 +1,4 @@
1
+ import type { Elysia } from 'elysia';
2
+ import type { EdenFetch } from './types';
3
+ export type { EdenFetch } from './types';
4
+ export declare const edenFetch: <App extends Elysia<any>>(server: string, config?: EdenFetch.Config) => EdenFetch.Create<App>;
@@ -0,0 +1,26 @@
1
+ /// <reference types="bun-types" />
2
+ import type { Elysia, SCHEMA } from 'elysia';
3
+ import type { EdenFetchError } from '../utils';
4
+ import type { MapError, IsUnknown, IsNever } from '../types';
5
+ export declare namespace EdenFetch {
6
+ type Create<App extends Elysia<any>> = App['meta'] extends Record<typeof SCHEMA, infer Schema extends Record<string, any>> ? EdenFetch.Fn<Schema> : 'Please install Elysia before using Eden';
7
+ interface Config {
8
+ }
9
+ type Fn<Schema extends Record<string, any>> = <Endpoint extends keyof Schema, Method extends Extract<keyof Schema[Endpoint], string>, Route extends Schema[Endpoint][Method]>(endpoint: Endpoint, options: Omit<RequestInit, 'body' | 'method' | 'headers'> & ('get' extends Method ? {
10
+ method?: Uppercase<Method>;
11
+ } : {
12
+ method: Uppercase<Method>;
13
+ }) & (IsNever<keyof Route['params']> extends true ? {
14
+ params?: Record<never, string>;
15
+ } : {
16
+ params: Route['params'];
17
+ }) & (undefined extends Route['headers'] ? {
18
+ headers?: Record<string, string>;
19
+ } : {
20
+ headers: Route['headers'];
21
+ }) & (IsUnknown<Route['body']> extends false ? {
22
+ body: Route['body'];
23
+ } : {
24
+ body?: unknown;
25
+ })) => Promise<Route['response']['200']> | (MapError<Route['response']> extends infer Errors ? IsNever<Errors> extends true ? EdenFetchError<number, string> : Errors : never);
26
+ }
@@ -0,0 +1 @@
1
+ export * from './fetch/index'
package/dist/fetch.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./utils-0d7d9b21.js"),h=(l,p)=>async(r,{params:s,body:c,...i}={})=>{var u;s&&Object.entries(s).forEach(([e,t])=>{r=r.replace(`:${e}`,t)});const a=(u=i.headers)==null?void 0:u["Content-Type"];return(!a||a==="application/json")&&(c=JSON.stringify(c)),fetch(l+r,{...i,headers:{"content-type":"application/json",...i.headers},body:c}).then(async e=>{var f;let t;switch((f=e.headers.get("Content-Type"))==null?void 0:f.split(";")[0]){case"application/json":t=e.json();break;default:t=e.text().then(n=>Number.isNaN(+n)?n==="true"?!0:n==="false"?!1:n:+n)}return e.status>300?new o.EdenFetchError(e.status,await t):t})};exports.edenFetch=h;
package/dist/fetch.mjs ADDED
@@ -0,0 +1,33 @@
1
+ import { E as o } from "./utils-0d2b8b1a.mjs";
2
+ const j = (h, l) => (
3
+ // @ts-ignore
4
+ async (r, { params: a, body: c, ...s } = {}) => {
5
+ var f;
6
+ a && Object.entries(a).forEach(([e, t]) => {
7
+ r = r.replace(`:${e}`, t);
8
+ });
9
+ const i = (f = s.headers) == null ? void 0 : f["Content-Type"];
10
+ return (!i || i === "application/json") && (c = JSON.stringify(c)), fetch(h + r, {
11
+ ...s,
12
+ headers: {
13
+ "content-type": "application/json",
14
+ ...s.headers
15
+ },
16
+ body: c
17
+ }).then(async (e) => {
18
+ var u;
19
+ let t;
20
+ switch ((u = e.headers.get("Content-Type")) == null ? void 0 : u.split(";")[0]) {
21
+ case "application/json":
22
+ t = e.json();
23
+ break;
24
+ default:
25
+ t = e.text().then((n) => Number.isNaN(+n) ? n === "true" ? !0 : n === "false" ? !1 : n : +n);
26
+ }
27
+ return e.status > 300 ? new o(e.status, await t) : t;
28
+ });
29
+ }
30
+ );
31
+ export {
32
+ j as edenFetch
33
+ };
@@ -0,0 +1,4 @@
1
+ import type { Elysia } from 'elysia';
2
+ import type { EdenFn } from './types';
3
+ export type { EdenFn } from './types';
4
+ export declare const edenFn: <App extends Elysia<any>>(domain: string, config?: EdenFn.Config) => EdenFn.Create<App>;
@@ -0,0 +1,24 @@
1
+ /// <reference types="bun-types" />
2
+ import type { Elysia, EXPOSED } from 'elysia';
3
+ export declare namespace EdenFn {
4
+ type Create<App extends Elysia<any>> = App['meta'] extends Record<typeof EXPOSED, infer Schema extends Record<string, any>> ? EdenFn.Compose<Schema> : 'Please install Elysia before using Eden';
5
+ interface Config {
6
+ }
7
+ type Compose<Exposed extends Record<string, any>> = Fn<Exposed> & {
8
+ $set(config: Config): void;
9
+ $clone(config?: Config): Compose<Exposed>;
10
+ };
11
+ type Fn<T> = T extends {
12
+ [EXPOSED]: any;
13
+ value: infer Value;
14
+ } ? Asynctify<Value> : Asynctify<T>;
15
+ interface Config {
16
+ fn?: string;
17
+ fetch?: Omit<RequestInit, 'body'>;
18
+ }
19
+ }
20
+ type Promisify<T extends (...args: any[]) => any> = T extends (...args: infer Args) => infer Return ? Return extends Promise<any> ? T : (...args: Args) => Promise<Return> : never;
21
+ type Asynctify<T> = T extends infer Fn extends (...args: any) => any ? Promisify<Fn> : T extends Record<string, any> ? {
22
+ [K in keyof T]: EdenFn.Fn<T[K]>;
23
+ } : never;
24
+ export {};
@@ -0,0 +1,13 @@
1
+ import type { EdenFn } from './types';
2
+ export declare class Signal {
3
+ private url;
4
+ private config;
5
+ private pendings;
6
+ private operation;
7
+ private isFetching;
8
+ private sJson;
9
+ constructor(url: string, config?: EdenFn.Config);
10
+ setConfig(config: EdenFn.Config): void;
11
+ clone(config?: EdenFn.Config): Signal;
12
+ run(procedure: string[], params: any): Promise<any>;
13
+ }
package/dist/fn.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './fn/index'
package/dist/fn.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var d=Object.create;var g=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty;var O=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of z(t))!P.call(e,s)&&s!==n&&g(e,s,{get:()=>t[s],enumerable:!(i=w(t,s))||i.enumerable});return e};var S=(e,t,n)=>(n=e!=null?d(F(e)):{},O(t||!e||!e.__esModule?g(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class f{constructor(t,n={}){this.pendings=[],this.operation=null,this.isFetching=!1,this.url=t,this.config=n,this.sJson=import("superjson").then(i=>({serialize:i.serialize,deserialize:i.deserialize}))}setConfig(t){this.config=t}clone(t){return new f(this.url,t??this.config)}async run(t,n){var o;const i=+this.pendings.length;if(this.pendings.push(n!==void 0?{n:t,p:n}:{n:t}),this.isFetching)return(o=this.operation)==null?void 0:o.then(r=>r[i]);this.isFetching=!0,this.operation=new Promise(r=>{setTimeout(async()=>{var u;const h=[...this.pendings];this.pendings=[];const{serialize:c,deserialize:p}=await this.sJson,a=await fetch(`${this.url}${this.config.fn??"/~fn"}`,{method:"POST",...this.config.fetch,headers:{"content-type":"elysia/fn",...(u=this.config.fetch)==null?void 0:u.headers},body:JSON.stringify(c(h))});a.status===200?r(a.json().then(y=>p(y))):r(Array(h.length).fill(new Error(await a.text())))},33)});const s=await this.operation.then(r=>r[i]);return this.operation=null,this.isFetching=!1,s}}const l=(e,t,n)=>new Proxy((...i)=>{},{get(i,s,o){return l(e,[...t,s],n)},apply(i,s,o){const r=o[0],h=t[0];if(t.length===1){if(h in Object.prototype||h in Promise.prototype)return i(...o);switch(h){case"toJSON":return i(...o);case"$set":return n.setConfig(r);case"$clone":return l(e,[],n.clone(r))}}return n.run(t,o).then(c=>{if(c instanceof Error)throw c;return c})}}),b=(e,t)=>l(e,[],new f(e,t));exports.edenFn=b;
package/dist/fn.mjs ADDED
@@ -0,0 +1,80 @@
1
+ class l {
2
+ constructor(t, n = {}) {
3
+ this.pendings = [], this.operation = null, this.isFetching = !1, this.url = t, this.config = n, this.sJson = import("superjson").then((e) => ({
4
+ serialize: e.serialize,
5
+ deserialize: e.deserialize
6
+ }));
7
+ }
8
+ setConfig(t) {
9
+ this.config = t;
10
+ }
11
+ clone(t) {
12
+ return new l(this.url, t ?? this.config);
13
+ }
14
+ async run(t, n) {
15
+ var s;
16
+ const e = +this.pendings.length;
17
+ if (this.pendings.push(
18
+ n !== void 0 ? { n: t, p: n } : { n: t }
19
+ ), this.isFetching)
20
+ return (s = this.operation) == null ? void 0 : s.then((i) => i[e]);
21
+ this.isFetching = !0, this.operation = new Promise((i) => {
22
+ setTimeout(async () => {
23
+ var u;
24
+ const r = [...this.pendings];
25
+ this.pendings = [];
26
+ const { serialize: h, deserialize: g } = await this.sJson, a = await fetch(
27
+ `${this.url}${this.config.fn ?? "/~fn"}`,
28
+ {
29
+ method: "POST",
30
+ ...this.config.fetch,
31
+ headers: {
32
+ "content-type": "elysia/fn",
33
+ ...(u = this.config.fetch) == null ? void 0 : u.headers
34
+ },
35
+ body: JSON.stringify(h(r))
36
+ }
37
+ );
38
+ a.status === 200 ? i(a.json().then((p) => g(p))) : i(
39
+ Array(r.length).fill(
40
+ new Error(await a.text())
41
+ )
42
+ );
43
+ }, 33);
44
+ });
45
+ const c = await this.operation.then((i) => i[e]);
46
+ return this.operation = null, this.isFetching = !1, c;
47
+ }
48
+ }
49
+ const f = (o, t, n) => new Proxy((...e) => {
50
+ }, {
51
+ get(e, c, s) {
52
+ return f(o, [...t, c], n);
53
+ },
54
+ apply(e, c, s) {
55
+ const i = s[0], r = t[0];
56
+ if (t.length === 1) {
57
+ if (r in Object.prototype || r in Promise.prototype)
58
+ return e(...s);
59
+ switch (r) {
60
+ case "toJSON":
61
+ return e(...s);
62
+ case "$set":
63
+ return n.setConfig(i);
64
+ case "$clone":
65
+ return f(o, [], n.clone(i));
66
+ }
67
+ }
68
+ return n.run(t, s).then((h) => {
69
+ if (h instanceof Error)
70
+ throw h;
71
+ return h;
72
+ });
73
+ }
74
+ }), y = (o, t) => (
75
+ // @ts-ignore
76
+ f(o, [], new l(o, t))
77
+ );
78
+ export {
79
+ y as edenFn
80
+ };
package/dist/index.d.ts CHANGED
@@ -1,15 +1,3 @@
1
- /// <reference types="bun-types" />
2
- import type { Elysia, TypedSchema } from 'elysia';
3
- import type { Eden, EdenConfig, EdenWSEvent } from './types';
4
- export declare class EdenWS<Schema extends TypedSchema<any> = TypedSchema> {
5
- ws: WebSocket;
6
- url: string;
7
- constructor(url: string);
8
- send(data: Schema['body'] | Schema['body'][]): this;
9
- on<K extends keyof WebSocketEventMap>(type: K, listener: (event: EdenWSEvent<K, Schema['response']>) => void, options?: boolean | AddEventListenerOptions): this;
10
- off<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): this;
11
- addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (event: EdenWSEvent<K, Schema['response']>) => void, options?: boolean | AddEventListenerOptions): this;
12
- removeEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): this;
13
- close(): this;
14
- }
15
- export declare const eden: <App extends Elysia<any>>(domain: string, config?: EdenConfig) => Eden<App>;
1
+ export { edenTreaty } from './treaty';
2
+ export { edenFetch } from './fetch';
3
+ export { edenFn } from './fn';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var O=Object.create;var E=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var J=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of P(t))!F.call(s,r)&&r!==e&&E(s,r,{get:()=>t[r],enumerable:!(n=N(t,r))||n.enumerable});return s};var L=(s,t,e)=>(e=s!=null?O(z(s)):{},J(t||!s||!s.__esModule?E(e,"default",{value:s,enumerable:!0}):e,s));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class A extends Error{constructor(t,e){super(),this.status=t,this.value=e}}const W=s=>s.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`),m=(s,t,e)=>{if(s.endsWith("/")||(s+="/"),t=W(t.replace(/index/g,"")),!e||!Object.keys(e).length)return`${s}${t}`;let n="";for(const[r,i]of Object.entries(e))n+=`${r}=${i}&`;return`${s}${t}?${n.slice(0,-1)}`};class p{constructor(t,e){this.pendings=[],this.operation=null,this.isFetching=!1,this.url=t,this.config=e,this.sJson=import("superjson").then(n=>({serialize:n.serialize,deserialize:n.deserialize}))}setConfig(t){this.config=t}clone(t){return new p(this.url,t??this.config)}async run(t,e){var i;const n=+this.pendings.length;if(this.pendings.push(e!==void 0?{n:t,p:e}:{n:t}),this.isFetching)return(i=this.operation)==null?void 0:i.then(o=>o[n]);this.isFetching=!0,this.operation=new Promise(o=>{setTimeout(async()=>{var l;const a=[...this.pendings];this.pendings=[];const{serialize:g,deserialize:y}=await this.sJson,h=await fetch(`${this.url}${this.config.fn??"/~fn"}`,{method:"POST",...this.config.fetch,headers:{"content-type":"elysia/fn",...(l=this.config.fetch)==null?void 0:l.headers},body:JSON.stringify(g(a))});h.status===200?o(h.json().then(u=>y(u))):o(Array(a.length).fill(new Error(await h.text())))},33)});const r=await this.operation.then(o=>o[n]);return this.operation=null,this.isFetching=!1,r}}class ${constructor(t){this.ws=new WebSocket(t),this.url=t}send(t){return Array.isArray(t)?(t.forEach(e=>this.send(e)),this):(this.ws.send(typeof t=="object"?JSON.stringify(t):t.toString()),this)}on(t,e,n){return this.addEventListener(t,e,n)}off(t,e,n){return this.ws.removeEventListener(t,e,n),this}addEventListener(t,e,n){return this.ws.addEventListener(t,r=>{if(t==="message"){let i=r.data.toString();const o=i.charCodeAt(0);if(o===47||o===123)try{i=JSON.parse(i)}catch{}else Number.isNaN(+i)?i==="true"?i=!0:i==="fase"&&(i=!1):i=+i;e({...r,data:i})}else e(r)},n),this}removeEventListener(t,e,n){return this.off(t,e,n),this}close(){return this.ws.close(),this}}const w=(s,t,e)=>new Proxy((...n)=>{},{get(n,r,i){return w(s,[...t,r],e)},apply(n,r,i){const o=i[0];if(t.length===1){if(t[0]in Object.prototype||t[0]in Promise.prototype)return n(i);switch(t[0]){case"toJSON":return n(i);case"$set":return e.setConfig(o);case"$clone":return w(s,[],e.clone(o))}}return e.run(t,i).then(a=>{if(a instanceof Error)throw a;return a})}}),x=(s,t="",e)=>new Proxy(()=>{},{get(n,r,i){return x(s,`${t}/${r.toString()}`,e)},apply(n,r,[{$query:i,$fetch:o,$body:a,...g}={$fetch:void 0,$query:void 0,$body:void 0}]=[{}]){var b;const y=t.lastIndexOf("/"),h=t.slice(y+1),l=m(s,t.slice(0,y),i);if(h==="subscribe")return new $(l.replace(/^([^]+):\/\//,l.startsWith("https://")?"wss://":"ws://"));const u=a??(Object.keys(g).length?g:void 0),v=typeof u=="object";return fetch(l,{method:h,body:v?JSON.stringify(u):u,...e.fetch,...o,headers:u?{"content-type":v?"application/json":"text/plain",...(b=e.fetch)==null?void 0:b.headers,...o==null?void 0:o.headers}:void 0}).then(async c=>{var S,j;if(c.status>300){let d;if((S=c.headers.get("content-type"))!=null&&S.includes("application/json"))try{d=await c.json()}catch{d=await c.text()}else d=await c.text();return new A(c.status,d)}if((j=c.headers.get("content-type"))!=null&&j.includes("application/json"))try{return await c.json()}catch{}let f=await c.text();return Number.isNaN(+f)?f==="true"?!0:f==="false"?!1:f:+f})}}),C=(s,t={})=>new Proxy({},{get(e,n){return n==="$fn"?w(s,[],new p(s,t)):x(s,n,t)}});exports.EdenWS=$;exports.eden=C;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./treaty.js"),t=require("./fetch.js"),r=require("./fn.js");require("./utils-0d7d9b21.js");exports.edenTreaty=e.edenTreaty;exports.edenFetch=t.edenFetch;exports.edenFn=r.edenFn;
package/dist/index.mjs CHANGED
@@ -1,199 +1,9 @@
1
- class E extends Error {
2
- constructor(t, e) {
3
- super(), this.status = t, this.value = e;
4
- }
5
- }
6
- const N = (i) => i.replace(/[A-Z]/g, (t) => `-${t.toLowerCase()}`), O = (i, t, e) => {
7
- if (i.endsWith("/") || (i += "/"), t = N(t.replace(/index/g, "")), !e || !Object.keys(e).length)
8
- return `${i}${t}`;
9
- let s = "";
10
- for (const [o, n] of Object.entries(e))
11
- s += `${o}=${n}&`;
12
- return `${i}${t}?${s.slice(0, -1)}`;
13
- };
14
- class p {
15
- constructor(t, e) {
16
- this.pendings = [], this.operation = null, this.isFetching = !1, this.url = t, this.config = e, this.sJson = import("superjson").then((s) => ({
17
- serialize: s.serialize,
18
- deserialize: s.deserialize
19
- }));
20
- }
21
- setConfig(t) {
22
- this.config = t;
23
- }
24
- clone(t) {
25
- return new p(this.url, t ?? this.config);
26
- }
27
- async run(t, e) {
28
- var n;
29
- const s = +this.pendings.length;
30
- if (this.pendings.push(
31
- e !== void 0 ? { n: t, p: e } : { n: t }
32
- ), this.isFetching)
33
- return (n = this.operation) == null ? void 0 : n.then((r) => r[s]);
34
- this.isFetching = !0, this.operation = new Promise((r) => {
35
- setTimeout(async () => {
36
- var l;
37
- const a = [...this.pendings];
38
- this.pendings = [];
39
- const { serialize: d, deserialize: y } = await this.sJson, h = await fetch(
40
- `${this.url}${this.config.fn ?? "/~fn"}`,
41
- {
42
- method: "POST",
43
- ...this.config.fetch,
44
- headers: {
45
- "content-type": "elysia/fn",
46
- ...(l = this.config.fetch) == null ? void 0 : l.headers
47
- },
48
- body: JSON.stringify(d(a))
49
- }
50
- );
51
- h.status === 200 ? r(h.json().then((u) => y(u))) : r(
52
- Array(a.length).fill(
53
- new Error(await h.text())
54
- )
55
- );
56
- }, 33);
57
- });
58
- const o = await this.operation.then((r) => r[s]);
59
- return this.operation = null, this.isFetching = !1, o;
60
- }
61
- }
62
- class S {
63
- constructor(t) {
64
- this.ws = new WebSocket(t), this.url = t;
65
- }
66
- send(t) {
67
- return Array.isArray(t) ? (t.forEach((e) => this.send(e)), this) : (this.ws.send(
68
- typeof t == "object" ? JSON.stringify(t) : t.toString()
69
- ), this);
70
- }
71
- on(t, e, s) {
72
- return this.addEventListener(t, e, s);
73
- }
74
- off(t, e, s) {
75
- return this.ws.removeEventListener(t, e, s), this;
76
- }
77
- addEventListener(t, e, s) {
78
- return this.ws.addEventListener(
79
- t,
80
- (o) => {
81
- if (t === "message") {
82
- let n = o.data.toString();
83
- const r = n.charCodeAt(0);
84
- if (r === 47 || r === 123)
85
- try {
86
- n = JSON.parse(n);
87
- } catch {
88
- }
89
- else
90
- Number.isNaN(+n) ? n === "true" ? n = !0 : n === "fase" && (n = !1) : n = +n;
91
- e({
92
- ...o,
93
- data: n
94
- });
95
- } else
96
- e(o);
97
- },
98
- s
99
- ), this;
100
- }
101
- removeEventListener(t, e, s) {
102
- return this.off(t, e, s), this;
103
- }
104
- close() {
105
- return this.ws.close(), this;
106
- }
107
- }
108
- const w = (i, t, e) => new Proxy((...s) => {
109
- }, {
110
- get(s, o, n) {
111
- return w(i, [...t, o], e);
112
- },
113
- apply(s, o, n) {
114
- const r = n[0];
115
- if (t.length === 1) {
116
- if (t[0] in Object.prototype || t[0] in Promise.prototype)
117
- return s(n);
118
- switch (t[0]) {
119
- case "toJSON":
120
- return s(n);
121
- case "$set":
122
- return e.setConfig(r);
123
- case "$clone":
124
- return w(i, [], e.clone(r));
125
- }
126
- }
127
- return e.run(t, n).then((a) => {
128
- if (a instanceof Error)
129
- throw a;
130
- return a;
131
- });
132
- }
133
- }), j = (i, t = "", e) => new Proxy(() => {
134
- }, {
135
- get(s, o, n) {
136
- return j(i, `${t}/${o.toString()}`, e);
137
- },
138
- apply(s, o, [
139
- { $query: n, $fetch: r, $body: a, ...d } = {
140
- $fetch: void 0,
141
- $query: void 0,
142
- $body: void 0
143
- }
144
- ] = [{}]) {
145
- var b;
146
- const y = t.lastIndexOf("/"), h = t.slice(y + 1), l = O(i, t.slice(0, y), n);
147
- if (h === "subscribe")
148
- return new S(
149
- l.replace(
150
- /^([^]+):\/\//,
151
- l.startsWith("https://") ? "wss://" : "ws://"
152
- )
153
- );
154
- const u = a ?? (Object.keys(d).length ? d : void 0), v = typeof u == "object";
155
- return fetch(l, {
156
- method: h,
157
- body: v ? JSON.stringify(u) : u,
158
- ...e.fetch,
159
- ...r,
160
- headers: u ? {
161
- "content-type": v ? "application/json" : "text/plain",
162
- ...(b = e.fetch) == null ? void 0 : b.headers,
163
- ...r == null ? void 0 : r.headers
164
- } : void 0
165
- }).then(async (c) => {
166
- var x, $;
167
- if (c.status > 300) {
168
- let g;
169
- if ((x = c.headers.get("content-type")) != null && x.includes("application/json"))
170
- try {
171
- g = await c.json();
172
- } catch {
173
- g = await c.text();
174
- }
175
- else
176
- g = await c.text();
177
- return new E(c.status, g);
178
- }
179
- if (($ = c.headers.get("content-type")) != null && $.includes("application/json"))
180
- try {
181
- return await c.json();
182
- } catch {
183
- }
184
- let f = await c.text();
185
- return Number.isNaN(+f) ? f === "true" ? !0 : f === "false" ? !1 : f : +f;
186
- });
187
- }
188
- }), z = (i, t = {}) => new Proxy(
189
- {},
190
- {
191
- get(e, s) {
192
- return s === "$fn" ? w(i, [], new p(i, t)) : j(i, s, t);
193
- }
194
- }
195
- );
1
+ import { edenTreaty as t } from "./treaty.mjs";
2
+ import { edenFetch as n } from "./fetch.mjs";
3
+ import { edenFn as d } from "./fn.mjs";
4
+ import "./utils-0d2b8b1a.mjs";
196
5
  export {
197
- S as EdenWS,
198
- z as eden
6
+ n as edenFetch,
7
+ d as edenFn,
8
+ t as edenTreaty
199
9
  };
@@ -0,0 +1,16 @@
1
+ /// <reference types="bun-types" />
2
+ import type { Elysia, TypedSchema } from 'elysia';
3
+ import type { EdenTreaty } from './types';
4
+ export type { EdenTreaty } from './types';
5
+ export declare class EdenWS<Schema extends TypedSchema<any> = TypedSchema> {
6
+ ws: WebSocket;
7
+ url: string;
8
+ constructor(url: string);
9
+ send(data: Schema['body'] | Schema['body'][]): this;
10
+ on<K extends keyof WebSocketEventMap>(type: K, listener: (event: EdenTreaty.WSEvent<K, Schema['response']>) => void, options?: boolean | AddEventListenerOptions): this;
11
+ off<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): this;
12
+ addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (event: EdenTreaty.WSEvent<K, Schema['response']>) => void, options?: boolean | AddEventListenerOptions): this;
13
+ removeEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): this;
14
+ close(): this;
15
+ }
16
+ export declare const edenTreaty: <App extends Elysia<any>>(domain: string, config?: {}) => EdenTreaty.Create<App>;
@@ -0,0 +1,57 @@
1
+ /// <reference types="bun-types" />
2
+ import type { Elysia, SCHEMA, AnyTypedSchema } from 'elysia';
3
+ import type { EdenWS } from './index';
4
+ import type { IsNever, IsUnknown, MapError, UnionToIntersect } from '../types';
5
+ import { EdenFetchError } from '../utils';
6
+ export declare namespace EdenTreaty {
7
+ type Create<App extends Elysia<any>> = App['meta'] extends Record<typeof SCHEMA, infer Schema extends Record<string, any>> ? EdenTreaty.Sign<Schema> : 'Please install Elysia before using Eden';
8
+ interface Config {
9
+ }
10
+ type Sign<A> = {
11
+ [Path in keyof A as Path extends `/${infer Prefix}/${infer _}` ? Prefix : Path extends `/` ? 'index' : Path extends `/${infer Prefix}` ? Prefix : never]: UnionToIntersect<Path extends `/${infer _}/${infer Rest}` ? NestPath<Rest, {
12
+ [Method in keyof A[Path]]: A[Path][Method] extends infer Route extends AnyTypedSchema ? Method extends 'subscribe' ? undefined extends Route['query'] ? (params?: {
13
+ $query?: Record<string, string>;
14
+ }) => EdenWS<Route> : undefined extends Route['query'] ? (params: {
15
+ $query: Route['query'];
16
+ }) => EdenWS<Route> : (params?: {
17
+ $query?: Record<string, string>;
18
+ }) => EdenWS<Route> : IsUnknown<Route['body']> extends true ? (params?: {
19
+ $query?: Record<string, string>;
20
+ $fetch?: RequestInit;
21
+ }) => Promise<Route['response']['200']> | (MapError<Route['response']> extends infer Errors ? IsNever<Errors> extends true ? EdenFetchError<number, string> : Errors : never) : (params: Route['body'] & {
22
+ $query?: Record<string, string>;
23
+ $fetch?: RequestInit;
24
+ }) => Promise<Route['response'] extends {
25
+ 200: infer ReturnedType;
26
+ } ? ReturnedType : unknown> : never;
27
+ }> : {
28
+ [Method in keyof A[Path]]: A[Path][Method] extends infer Route extends AnyTypedSchema ? Method extends 'subscribe' ? IsUnknown<Route['query']> extends true ? (params?: {
29
+ $query?: Record<string, string>;
30
+ }) => EdenWS<Route> : undefined extends Route['query'] ? (params: {
31
+ $query: Route['query'];
32
+ }) => EdenWS<Route> : (params?: {
33
+ $query?: Record<string, string>;
34
+ }) => EdenWS<Route> : IsUnknown<Route['body']> extends true ? (params?: {
35
+ $query?: Record<string, string>;
36
+ $fetch?: RequestInit;
37
+ }) => Promise<Route['response']['200']> | (MapError<Route['response']> extends infer Errors ? IsNever<Errors> extends true ? EdenFetchError<number, string> : Errors : never) : (params: Route['body'] & {
38
+ $query?: Record<string, string>;
39
+ $fetch?: RequestInit;
40
+ }) => Promise<Route['response'] extends {
41
+ 200: infer ReturnedType;
42
+ } ? ReturnedType : unknown> : never;
43
+ }>;
44
+ };
45
+ interface OnMessage<Data = unknown> extends MessageEvent {
46
+ data: Data;
47
+ rawData: MessageEvent['data'];
48
+ }
49
+ type WSEvent<K extends keyof WebSocketEventMap, Data = unknown> = K extends 'message' ? OnMessage<Data> : WebSocketEventMap[K];
50
+ interface CallOption {
51
+ [x: string]: any;
52
+ $fetch?: RequestInit;
53
+ $query?: Record<string, string>;
54
+ }
55
+ }
56
+ type NestPath<T extends string, V> = T extends `${infer First}/${infer Rest}` ? First extends `:${infer Parameter}` ? Record<(string & {}) | `:${Parameter}`, NestPath<Rest, V>> : Record<First, NestPath<Rest, V>> : T extends `:${infer Parameter}` ? Record<(string & {}) | T, V> : Record<T, V>;
57
+ export {};
@@ -0,0 +1 @@
1
+ export declare const composePath: (domain: string, path: string, query: Record<string, string> | undefined) => string;
@@ -0,0 +1 @@
1
+ export * from './treaty/index'
package/dist/treaty.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./utils-0d7d9b21.js"),E=(n,e,t)=>{if(n.endsWith("/")||(n+="/"),e==="index"&&(e=""),!t||!Object.keys(t).length)return`${n}${e}`;let s="";for(const[i,r]of Object.entries(t))s+=`${i}=${r}&`;return`${n}${e}?${s.slice(0,-1)}`};class v{constructor(e){this.ws=new WebSocket(e),this.url=e}send(e){return Array.isArray(e)?(e.forEach(t=>this.send(t)),this):(this.ws.send(typeof e=="object"?JSON.stringify(e):e.toString()),this)}on(e,t,s){return this.addEventListener(e,t,s)}off(e,t,s){return this.ws.removeEventListener(e,t,s),this}addEventListener(e,t,s){return this.ws.addEventListener(e,i=>{if(e==="message"){let r=i.data.toString();const o=r.charCodeAt(0);if(o===47||o===123)try{r=JSON.parse(r)}catch{}else Number.isNaN(+r)?r==="true"?r=!0:r==="fase"&&(r=!1):r=+r;t({...i,data:r})}else t(i)},s),this}removeEventListener(e,t,s){return this.off(e,t,s),this}close(){return this.ws.close(),this}}const w=(n,e="",t)=>new Proxy(()=>{},{get(s,i,r){return w(n,`${e}/${i.toString()}`)},apply(s,i,[{$query:r,$fetch:o,$body:S,...d}={$fetch:void 0,$query:void 0,$body:void 0}]=[{}]){const h=e.lastIndexOf("/"),y=e.slice(h+1),a=E(n,e.slice(0,h),r);if(y==="subscribe")return new v(a.replace(/^([^]+):\/\//,a.startsWith("https://")?"wss://":"ws://"));const l=S??(Object.keys(d).length?d:void 0),g=typeof l=="object";return fetch(a,{method:y,body:g?JSON.stringify(l):l,...o,headers:l?{"content-type":g?"application/json":"text/plain",...o==null?void 0:o.headers}:void 0}).then(async c=>{var b;let f;switch((b=c.headers.get("Content-Type"))==null?void 0:b.split(";")[0]){case"application/json":f=c.json();break;default:f=c.text().then(u=>Number.isNaN(+u)?u==="true"?!0:u==="false"?!1:u:+u)}return c.status>300?new p.EdenFetchError(c.status,await f):f})}}),j=(n,e={})=>new Proxy({},{get(t,s){return w(n,s)}});exports.EdenWS=v;exports.edenTreaty=j;