@chirper/node 0.0.1 → 0.0.3
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/dist/bundle.js +796 -1
- package/package.json +1 -1
- package/src/api/Chirp.ts +17 -0
- package/src/api/Chirper.ts +27 -0
- package/src/api/Follow.ts +13 -0
- package/src/index.ts +6 -0
package/dist/bundle.js
CHANGED
@@ -1 +1,796 @@
|
|
1
|
-
var V=Object.create;var S=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var k=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),X=(s,t)=>{for(var e in t)S(s,e,{get:t[e],enumerable:!0})},J=(s,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of z(t))!W.call(s,o)&&o!==e&&S(s,o,{get:()=>t[o],enumerable:!(i=Y(t,o))||i.enumerable});return s};var U=(s,t,e)=>(e=s!=null?V(Q(s)):{},J(t||!s||!s.__esModule?S(e,"default",{value:s,enumerable:!0}):e,s)),Z=s=>J(S({},"__esModule",{value:!0}),s);var B=k((rt,E)=>{var C=(()=>{var s=Object.defineProperty,t=Object.getOwnPropertySymbols,e=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,o=(w,f,p)=>f in w?s(w,f,{enumerable:!0,configurable:!0,writable:!0,value:p}):w[f]=p,a=(w,f)=>{for(var p in f||(f={}))e.call(f,p)&&o(w,p,f[p]);if(t)for(var p of t(f))i.call(f,p)&&o(w,p,f[p]);return w},h=w=>s(w,"__esModule",{value:!0}),v=(w,f)=>{h(w);for(var p in f)s(w,p,{get:f[p],enumerable:!0})},n={};v(n,{DEFAULT_UUID_LENGTH:()=>y,default:()=>b});var $="4.4.4",y=6,c={dictionary:"alphanum",shuffle:!0,debug:!1,length:y},m=class extends Function{constructor(w={}){super(),this.dictIndex=0,this.dictRange=[],this.lowerBound=0,this.upperBound=0,this.dictLength=0,this._digit_first_ascii=48,this._digit_last_ascii=58,this._alpha_lower_first_ascii=97,this._alpha_lower_last_ascii=123,this._hex_last_ascii=103,this._alpha_upper_first_ascii=65,this._alpha_upper_last_ascii=91,this._number_dict_ranges={digits:[this._digit_first_ascii,this._digit_last_ascii]},this._alpha_dict_ranges={lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]},this._alpha_lower_dict_ranges={lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]},this._alpha_upper_dict_ranges={upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]},this._alphanum_dict_ranges={digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]},this._alphanum_lower_dict_ranges={digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]},this._alphanum_upper_dict_ranges={digits:[this._digit_first_ascii,this._digit_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]},this._hex_dict_ranges={decDigits:[this._digit_first_ascii,this._digit_last_ascii],alphaDigits:[this._alpha_lower_first_ascii,this._hex_last_ascii]},this.log=(...r)=>{let l=[...r];if(l[0]=`[short-unique-id] ${r[0]}`,this.debug===!0&&typeof console<"u"&&console!==null)return console.log(...l)},this.setDictionary=(r,l)=>{let u;if(r&&Array.isArray(r)&&r.length>1)u=r;else{u=[];let d;this.dictIndex=d=0;let x=`_${r}_dict_ranges`,N=this[x];Object.keys(N).forEach(G=>{let H=G;for(this.dictRange=N[H],this.lowerBound=this.dictRange[0],this.upperBound=this.dictRange[1],this.dictIndex=d=this.lowerBound;this.lowerBound<=this.upperBound?d<this.upperBound:d>this.upperBound;this.dictIndex=this.lowerBound<=this.upperBound?d+=1:d-=1)u.push(String.fromCharCode(this.dictIndex))})}l&&(u=u.sort(()=>Math.random()-.5)),this.dict=u,this.dictLength=this.dict.length,this.counter=0},this.seq=()=>this.sequentialUUID(),this.sequentialUUID=()=>{let r,l,u="";r=this.counter;do l=r%this.dictLength,r=Math.trunc(r/this.dictLength),u+=this.dict[l];while(r!==0);return this.counter+=1,u},this.randomUUID=(r=this.uuidLength||y)=>{let l,u,d;if(r===null||typeof r>"u"||r<1)throw new Error("Invalid UUID Length Provided");let x=r>=0;for(l="",d=0;d<r;d+=1)u=parseInt((Math.random()*this.dictLength).toFixed(0),10)%this.dictLength,l+=this.dict[u];return l},this.availableUUIDs=(r=this.uuidLength)=>parseFloat(Math.pow([...new Set(this.dict)].length,r).toFixed(0)),this.approxMaxBeforeCollision=(r=this.availableUUIDs(this.uuidLength))=>parseFloat(Math.sqrt(Math.PI/2*r).toFixed(20)),this.collisionProbability=(r=this.availableUUIDs(this.uuidLength),l=this.uuidLength)=>parseFloat((this.approxMaxBeforeCollision(r)/this.availableUUIDs(l)).toFixed(20)),this.uniqueness=(r=this.availableUUIDs(this.uuidLength))=>{let l=parseFloat((1-this.approxMaxBeforeCollision(r)/r).toFixed(20));return l>1?1:l<0?0:l},this.getVersion=()=>this.version,this.stamp=r=>{if(typeof r!="number"||r<10)throw new Error("Param finalLength must be number greater than 10");let l=Math.floor(+new Date/1e3).toString(16),u=r-9,d=Math.round(Math.random()*(u>15?15:u)),x=this.randomUUID(u);return`${x.substr(0,d)}${l}${x.substr(d)}${d.toString(16)}`},this.parseStamp=r=>{if(r.length<10)throw new Error("Stamp length invalid");let l=parseInt(r.substr(r.length-1,1),16);return new Date(parseInt(r.substr(l,8),16)*1e3)};let f=a(a({},c),w);this.counter=0,this.debug=!1,this.dict=[],this.version=$;let{dictionary:p,shuffle:j,length:K}=f;return this.uuidLength=K,this.setDictionary(p,j),this.debug=f.debug,this.log(this.dict),this.log(`Generator instantiated with Dictionary Size ${this.dictLength}`),new Proxy(this,{apply:(r,l,u)=>this.randomUUID(...u)})}},b=m;return b.default=m,n})();typeof E<"u"&&(E.exports=C.default),typeof window<"u"&&(C=C.default)});var T=k((ht,P)=>{"use strict";var tt=Object.prototype.hasOwnProperty,g="~";function O(){}Object.create&&(O.prototype=Object.create(null),new O().__proto__||(g=!1));function et(s,t,e){this.fn=s,this.context=t,this.once=e||!1}function F(s,t,e,i,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var a=new et(e,i||s,o),h=g?g+t:t;return s._events[h]?s._events[h].fn?s._events[h]=[s._events[h],a]:s._events[h].push(a):(s._events[h]=a,s._eventsCount++),s}function I(s,t){--s._eventsCount===0?s._events=new O:delete s._events[t]}function _(){this._events=new O,this._eventsCount=0}_.prototype.eventNames=function(){var t=[],e,i;if(this._eventsCount===0)return t;for(i in e=this._events)tt.call(e,i)&&t.push(g?i.slice(1):i);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};_.prototype.listeners=function(t){var e=g?g+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var o=0,a=i.length,h=new Array(a);o<a;o++)h[o]=i[o].fn;return h};_.prototype.listenerCount=function(t){var e=g?g+t:t,i=this._events[e];return i?i.fn?1:i.length:0};_.prototype.emit=function(t,e,i,o,a,h){var v=g?g+t:t;if(!this._events[v])return!1;var n=this._events[v],$=arguments.length,y,c;if(n.fn){switch(n.once&&this.removeListener(t,n.fn,void 0,!0),$){case 1:return n.fn.call(n.context),!0;case 2:return n.fn.call(n.context,e),!0;case 3:return n.fn.call(n.context,e,i),!0;case 4:return n.fn.call(n.context,e,i,o),!0;case 5:return n.fn.call(n.context,e,i,o,a),!0;case 6:return n.fn.call(n.context,e,i,o,a,h),!0}for(c=1,y=new Array($-1);c<$;c++)y[c-1]=arguments[c];n.fn.apply(n.context,y)}else{var m=n.length,b;for(c=0;c<m;c++)switch(n[c].once&&this.removeListener(t,n[c].fn,void 0,!0),$){case 1:n[c].fn.call(n[c].context);break;case 2:n[c].fn.call(n[c].context,e);break;case 3:n[c].fn.call(n[c].context,e,i);break;case 4:n[c].fn.call(n[c].context,e,i,o);break;default:if(!y)for(b=1,y=new Array($-1);b<$;b++)y[b-1]=arguments[b];n[c].fn.apply(n[c].context,y)}}return!0};_.prototype.on=function(t,e,i){return F(this,t,e,i,!1)};_.prototype.once=function(t,e,i){return F(this,t,e,i,!0)};_.prototype.removeListener=function(t,e,i,o){var a=g?g+t:t;if(!this._events[a])return this;if(!e)return I(this,a),this;var h=this._events[a];if(h.fn)h.fn===e&&(!o||h.once)&&(!i||h.context===i)&&I(this,a);else{for(var v=0,n=[],$=h.length;v<$;v++)(h[v].fn!==e||o&&!h[v].once||i&&h[v].context!==i)&&n.push(h[v]);n.length?this._events[a]=n.length===1?n[0]:n:I(this,a)}return this};_.prototype.removeAllListeners=function(t){var e;return t?(e=g?g+t:t,this._events[e]&&I(this,e)):(this._events=new O,this._eventsCount=0),this};_.prototype.off=_.prototype.removeListener;_.prototype.addListener=_.prototype.on;_.prefixed=g;_.EventEmitter=_;typeof P<"u"&&(P.exports=_)});var st={};X(st,{default:()=>L});module.exports=Z(st);var q=U(B()),R=U(require("socket.io-client"));var D=U(T(),1);var A=s=>({prompt:t=>s.post("/:account/ai",t),image:t=>s.post("/:account/ai/image",t)});var M=s=>({get:(t,e=null,i=null)=>s.get(`/:account/stat/${t}`,{from:e,to:i})});var it=new q.default({length:10}),L=class{constructor({url:t,version:e}){this.key=null;this.url=null;this.cache={};this.events=new D.default;this.call=null;this.socket=null;this.account=null;this.version="v1";this.loading=!0;this.authing=null;this.authKey=null;this.shareKey=null;this.customer=null;this.presences={};this.connecting=null;this.options={path:"/ws",cors:!0,agent:!0,reconnect:!0,transports:["websocket"],withCredentials:!0};t&&(this.url=t),e&&(this.version=e),this.build=this.build.bind(this),this.fetch=this.fetch.bind(this),this.wsFetch=this.wsFetch.bind(this),this.on=this.on.bind(this),this.off=this.off.bind(this),this.emit=this.emit.bind(this),this.once=this.once.bind(this),this.addListener=this.events.addListener.bind(this.events),this.removeListener=this.events.removeListener.bind(this.events),this.get=this.get.bind(this),this.put=this.put.bind(this),this.post=this.post.bind(this),this.patch=this.patch.bind(this),this.delete=this.delete.bind(this),this.AI=A(this),this.Stat=M(this),this.build()}build(){if(this.__resolveConnecting=null,this.connecting=new Promise(e=>{this.__resolveConnecting=e}),!this.url)return;let t=R.default.connect(`${this.url}`,this.options);t.on("connect",async()=>{this.authing||(this.authing=this.auth(this.authKey,this.shareKey),await this.authing,this.authing=null,this.__resolveConnecting())}),t.on("disconnect",()=>{this.connecting=new Promise(e=>{this.__resolveConnecting=e})}),this.socket=t}async auth(){this.loading=!0,this.events.emit("loading",!0);let t=await this.get("/auth",{key:this.key},!1,!1);t?.user&&(this.user=t.user,this.events.emit("user",t.user)),this.loading=!1,this.events.emit("loading",!1),typeof window<"u"&&(window.chirper=this)}async fetch(t,e,i={},o=!1){if(["patch","put","delete","post"].includes(t.toLowerCase())&&(o=!1),o&&this.cache[`${t}${e}${JSON.stringify(i)}`])return this.cache[`${t}${e}${JSON.stringify(i)}`];delete this.cache[`${t}${e}${JSON.stringify(i)}`],console.time(`[chirper] [fetch] ${t}:${e} ${JSON.stringify(i)}`);let a;try{a=await(await fetch(`${this.url}${e}${`${t}`.toLowerCase()==="get"?`?${new URLSearchParams(i)}`:""}`,{body:`${t}`.toLowerCase()!=="get"?JSON.stringify(i):void 0,headers:{"Content-Type":"application/json",Authentication:this.key?`Bearer ${this.key}`:void 0},credentials:"include"})).json()}catch(h){throw console.timeEnd(`[chirper] [fetch] ${t}:${e} ${JSON.stringify(i)}`),h}if(console.timeEnd(`[chirper] [fetch] ${t}:${e} ${JSON.stringify(i)}`),!a?.success)throw new Error(a.message);return o&&(this.cache[`${t}${e}${JSON.stringify(i)}`]=a,this.cache[`${t}${e}${JSON.stringify(i)}`].then(()=>{typeof o=="number"?setTimeout(()=>{delete this.cache[`${t}${e}${JSON.stringify(i)}`]},o):delete this.cache[`${t}${e}${JSON.stringify(i)}`]})),a.result}async wsFetch(t,e,i={},o=!1,a=!0){if(a&&await this.connecting,a&&await this.authing,a&&!this.account&&e.includes(":account")&&await new Promise(n=>{this.events.once("account",n)}),this.account&&(e=e.replace(":account",this.account?.id)),["patch","put","delete","post"].includes(t.toLowerCase())&&(o=!1),o&&this.cache[`${t}${e}${JSON.stringify(i)}`])return this.cache[`${t}${e}${JSON.stringify(i)}`];delete this.cache[`${t}${e}${JSON.stringify(i)}`];let h=it();console.time(`[chirper] [${h}] ${t}:${e} ${JSON.stringify(i)}`);let v=new Promise((n,$)=>{this.socket.once(h,({success:y,result:c,message:m})=>{if(console.timeEnd(`[chirper] [${h}] ${t}:${e} ${JSON.stringify(i)}`),y)return n(c);$(m)})});return o&&(this.cache[`${t}${e}${JSON.stringify(i)}`]=v,this.cache[`${t}${e}${JSON.stringify(i)}`].then(()=>{typeof o=="number"?setTimeout(()=>{delete this.cache[`${t}${e}${JSON.stringify(i)}`]},o):delete this.cache[`${t}${e}${JSON.stringify(i)}`]})),this.socket.emit("call",h,t.toUpperCase(),e,i),v}on(...t){this.socket.on(...t)}off(...t){this.socket.off(...t)}emit(...t){this.socket.emit(...t)}once(...t){this.socket.once(...t)}get(t,e,...i){return this.wsFetch("GET",`/${this.version}${t}`,e,...i)}put(t,e,...i){return this.wsFetch("PUT",`/${this.version}${t}`,e,...i)}post(t,e,...i){return this.wsFetch("POST",`/${this.version}${t}`,e,...i)}patch(t,e,...i){return this.wsFetch("PATCH",`/${this.version}${t}`,e,...i)}delete(t,e,...i){return this.wsFetch("DELETE",`/${this.version}${t}`,e,...i)}};
|
1
|
+
var __create = Object.create;
|
2
|
+
var __defProp = Object.defineProperty;
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
7
|
+
var __commonJS = (cb, mod) => function __require() {
|
8
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
9
|
+
};
|
10
|
+
var __export = (target, all) => {
|
11
|
+
for (var name in all)
|
12
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
13
|
+
};
|
14
|
+
var __copyProps = (to, from, except, desc) => {
|
15
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
16
|
+
for (let key of __getOwnPropNames(from))
|
17
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
18
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
19
|
+
}
|
20
|
+
return to;
|
21
|
+
};
|
22
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
23
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
24
|
+
// file that has been converted to a CommonJS file using a Babel-
|
25
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
26
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
27
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
28
|
+
mod
|
29
|
+
));
|
30
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
31
|
+
|
32
|
+
// node_modules/short-unique-id/dist/short-unique-id.js
|
33
|
+
var require_short_unique_id = __commonJS({
|
34
|
+
"node_modules/short-unique-id/dist/short-unique-id.js"(exports, module2) {
|
35
|
+
var ShortUniqueId = (() => {
|
36
|
+
var __defProp2 = Object.defineProperty;
|
37
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
38
|
+
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
39
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
40
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
41
|
+
var __spreadValues = (a, b) => {
|
42
|
+
for (var prop in b || (b = {}))
|
43
|
+
if (__hasOwnProp2.call(b, prop))
|
44
|
+
__defNormalProp(a, prop, b[prop]);
|
45
|
+
if (__getOwnPropSymbols)
|
46
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
47
|
+
if (__propIsEnum.call(b, prop))
|
48
|
+
__defNormalProp(a, prop, b[prop]);
|
49
|
+
}
|
50
|
+
return a;
|
51
|
+
};
|
52
|
+
var __markAsModule = (target) => __defProp2(target, "__esModule", { value: true });
|
53
|
+
var __export2 = (target, all) => {
|
54
|
+
__markAsModule(target);
|
55
|
+
for (var name in all)
|
56
|
+
__defProp2(target, name, { get: all[name], enumerable: true });
|
57
|
+
};
|
58
|
+
var src_exports2 = {};
|
59
|
+
__export2(src_exports2, {
|
60
|
+
DEFAULT_UUID_LENGTH: () => DEFAULT_UUID_LENGTH,
|
61
|
+
default: () => ShortUniqueId2
|
62
|
+
});
|
63
|
+
var version = "4.4.4";
|
64
|
+
var DEFAULT_UUID_LENGTH = 6;
|
65
|
+
var DEFAULT_OPTIONS = {
|
66
|
+
dictionary: "alphanum",
|
67
|
+
shuffle: true,
|
68
|
+
debug: false,
|
69
|
+
length: DEFAULT_UUID_LENGTH
|
70
|
+
};
|
71
|
+
var _ShortUniqueId = class extends Function {
|
72
|
+
constructor(argOptions = {}) {
|
73
|
+
super();
|
74
|
+
this.dictIndex = 0;
|
75
|
+
this.dictRange = [];
|
76
|
+
this.lowerBound = 0;
|
77
|
+
this.upperBound = 0;
|
78
|
+
this.dictLength = 0;
|
79
|
+
this._digit_first_ascii = 48;
|
80
|
+
this._digit_last_ascii = 58;
|
81
|
+
this._alpha_lower_first_ascii = 97;
|
82
|
+
this._alpha_lower_last_ascii = 123;
|
83
|
+
this._hex_last_ascii = 103;
|
84
|
+
this._alpha_upper_first_ascii = 65;
|
85
|
+
this._alpha_upper_last_ascii = 91;
|
86
|
+
this._number_dict_ranges = {
|
87
|
+
digits: [this._digit_first_ascii, this._digit_last_ascii]
|
88
|
+
};
|
89
|
+
this._alpha_dict_ranges = {
|
90
|
+
lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],
|
91
|
+
upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii]
|
92
|
+
};
|
93
|
+
this._alpha_lower_dict_ranges = {
|
94
|
+
lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii]
|
95
|
+
};
|
96
|
+
this._alpha_upper_dict_ranges = {
|
97
|
+
upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii]
|
98
|
+
};
|
99
|
+
this._alphanum_dict_ranges = {
|
100
|
+
digits: [this._digit_first_ascii, this._digit_last_ascii],
|
101
|
+
lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],
|
102
|
+
upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii]
|
103
|
+
};
|
104
|
+
this._alphanum_lower_dict_ranges = {
|
105
|
+
digits: [this._digit_first_ascii, this._digit_last_ascii],
|
106
|
+
lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii]
|
107
|
+
};
|
108
|
+
this._alphanum_upper_dict_ranges = {
|
109
|
+
digits: [this._digit_first_ascii, this._digit_last_ascii],
|
110
|
+
upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii]
|
111
|
+
};
|
112
|
+
this._hex_dict_ranges = {
|
113
|
+
decDigits: [this._digit_first_ascii, this._digit_last_ascii],
|
114
|
+
alphaDigits: [this._alpha_lower_first_ascii, this._hex_last_ascii]
|
115
|
+
};
|
116
|
+
this.log = (...args) => {
|
117
|
+
const finalArgs = [...args];
|
118
|
+
finalArgs[0] = `[short-unique-id] ${args[0]}`;
|
119
|
+
if (this.debug === true) {
|
120
|
+
if (typeof console !== "undefined" && console !== null) {
|
121
|
+
return console.log(...finalArgs);
|
122
|
+
}
|
123
|
+
}
|
124
|
+
};
|
125
|
+
this.setDictionary = (dictionary2, shuffle2) => {
|
126
|
+
let finalDict;
|
127
|
+
if (dictionary2 && Array.isArray(dictionary2) && dictionary2.length > 1) {
|
128
|
+
finalDict = dictionary2;
|
129
|
+
} else {
|
130
|
+
finalDict = [];
|
131
|
+
let i;
|
132
|
+
this.dictIndex = i = 0;
|
133
|
+
const rangesName = `_${dictionary2}_dict_ranges`;
|
134
|
+
const ranges = this[rangesName];
|
135
|
+
Object.keys(ranges).forEach((rangeType) => {
|
136
|
+
const rangeTypeKey = rangeType;
|
137
|
+
this.dictRange = ranges[rangeTypeKey];
|
138
|
+
this.lowerBound = this.dictRange[0];
|
139
|
+
this.upperBound = this.dictRange[1];
|
140
|
+
for (this.dictIndex = i = this.lowerBound; this.lowerBound <= this.upperBound ? i < this.upperBound : i > this.upperBound; this.dictIndex = this.lowerBound <= this.upperBound ? i += 1 : i -= 1) {
|
141
|
+
finalDict.push(String.fromCharCode(this.dictIndex));
|
142
|
+
}
|
143
|
+
});
|
144
|
+
}
|
145
|
+
if (shuffle2) {
|
146
|
+
const PROBABILITY = 0.5;
|
147
|
+
finalDict = finalDict.sort(() => Math.random() - PROBABILITY);
|
148
|
+
}
|
149
|
+
this.dict = finalDict;
|
150
|
+
this.dictLength = this.dict.length;
|
151
|
+
this.counter = 0;
|
152
|
+
};
|
153
|
+
this.seq = () => {
|
154
|
+
return this.sequentialUUID();
|
155
|
+
};
|
156
|
+
this.sequentialUUID = () => {
|
157
|
+
let counterDiv;
|
158
|
+
let counterRem;
|
159
|
+
let id = "";
|
160
|
+
counterDiv = this.counter;
|
161
|
+
do {
|
162
|
+
counterRem = counterDiv % this.dictLength;
|
163
|
+
counterDiv = Math.trunc(counterDiv / this.dictLength);
|
164
|
+
id += this.dict[counterRem];
|
165
|
+
} while (counterDiv !== 0);
|
166
|
+
this.counter += 1;
|
167
|
+
return id;
|
168
|
+
};
|
169
|
+
this.randomUUID = (uuidLength = this.uuidLength || DEFAULT_UUID_LENGTH) => {
|
170
|
+
let id;
|
171
|
+
let randomPartIdx;
|
172
|
+
let j;
|
173
|
+
if (uuidLength === null || typeof uuidLength === "undefined" || uuidLength < 1) {
|
174
|
+
throw new Error("Invalid UUID Length Provided");
|
175
|
+
}
|
176
|
+
const isPositive = uuidLength >= 0;
|
177
|
+
id = "";
|
178
|
+
for (j = 0; j < uuidLength; j += 1) {
|
179
|
+
randomPartIdx = parseInt((Math.random() * this.dictLength).toFixed(0), 10) % this.dictLength;
|
180
|
+
id += this.dict[randomPartIdx];
|
181
|
+
}
|
182
|
+
return id;
|
183
|
+
};
|
184
|
+
this.availableUUIDs = (uuidLength = this.uuidLength) => {
|
185
|
+
return parseFloat(Math.pow([...new Set(this.dict)].length, uuidLength).toFixed(0));
|
186
|
+
};
|
187
|
+
this.approxMaxBeforeCollision = (rounds = this.availableUUIDs(this.uuidLength)) => {
|
188
|
+
return parseFloat(Math.sqrt(Math.PI / 2 * rounds).toFixed(20));
|
189
|
+
};
|
190
|
+
this.collisionProbability = (rounds = this.availableUUIDs(this.uuidLength), uuidLength = this.uuidLength) => {
|
191
|
+
return parseFloat((this.approxMaxBeforeCollision(rounds) / this.availableUUIDs(uuidLength)).toFixed(20));
|
192
|
+
};
|
193
|
+
this.uniqueness = (rounds = this.availableUUIDs(this.uuidLength)) => {
|
194
|
+
const score = parseFloat((1 - this.approxMaxBeforeCollision(rounds) / rounds).toFixed(20));
|
195
|
+
return score > 1 ? 1 : score < 0 ? 0 : score;
|
196
|
+
};
|
197
|
+
this.getVersion = () => {
|
198
|
+
return this.version;
|
199
|
+
};
|
200
|
+
this.stamp = (finalLength) => {
|
201
|
+
if (typeof finalLength !== "number" || finalLength < 10) {
|
202
|
+
throw new Error("Param finalLength must be number greater than 10");
|
203
|
+
}
|
204
|
+
const hexStamp = Math.floor(+new Date() / 1e3).toString(16);
|
205
|
+
const idLength = finalLength - 9;
|
206
|
+
const rndIdx = Math.round(Math.random() * (idLength > 15 ? 15 : idLength));
|
207
|
+
const id = this.randomUUID(idLength);
|
208
|
+
return `${id.substr(0, rndIdx)}${hexStamp}${id.substr(rndIdx)}${rndIdx.toString(16)}`;
|
209
|
+
};
|
210
|
+
this.parseStamp = (stamp) => {
|
211
|
+
if (stamp.length < 10) {
|
212
|
+
throw new Error("Stamp length invalid");
|
213
|
+
}
|
214
|
+
const rndIdx = parseInt(stamp.substr(stamp.length - 1, 1), 16);
|
215
|
+
return new Date(parseInt(stamp.substr(rndIdx, 8), 16) * 1e3);
|
216
|
+
};
|
217
|
+
const options = __spreadValues(__spreadValues({}, DEFAULT_OPTIONS), argOptions);
|
218
|
+
this.counter = 0;
|
219
|
+
this.debug = false;
|
220
|
+
this.dict = [];
|
221
|
+
this.version = version;
|
222
|
+
const {
|
223
|
+
dictionary,
|
224
|
+
shuffle,
|
225
|
+
length
|
226
|
+
} = options;
|
227
|
+
this.uuidLength = length;
|
228
|
+
this.setDictionary(dictionary, shuffle);
|
229
|
+
this.debug = options.debug;
|
230
|
+
this.log(this.dict);
|
231
|
+
this.log(`Generator instantiated with Dictionary Size ${this.dictLength}`);
|
232
|
+
return new Proxy(this, {
|
233
|
+
apply: (target, that, args) => this.randomUUID(...args)
|
234
|
+
});
|
235
|
+
}
|
236
|
+
};
|
237
|
+
var ShortUniqueId2 = _ShortUniqueId;
|
238
|
+
ShortUniqueId2.default = _ShortUniqueId;
|
239
|
+
return src_exports2;
|
240
|
+
})();
|
241
|
+
"undefined" != typeof module2 && (module2.exports = ShortUniqueId.default), "undefined" != typeof window && (ShortUniqueId = ShortUniqueId.default);
|
242
|
+
}
|
243
|
+
});
|
244
|
+
|
245
|
+
// node_modules/eventemitter3/index.js
|
246
|
+
var require_eventemitter3 = __commonJS({
|
247
|
+
"node_modules/eventemitter3/index.js"(exports, module2) {
|
248
|
+
"use strict";
|
249
|
+
var has = Object.prototype.hasOwnProperty;
|
250
|
+
var prefix = "~";
|
251
|
+
function Events() {
|
252
|
+
}
|
253
|
+
if (Object.create) {
|
254
|
+
Events.prototype = /* @__PURE__ */ Object.create(null);
|
255
|
+
if (!new Events().__proto__)
|
256
|
+
prefix = false;
|
257
|
+
}
|
258
|
+
function EE(fn, context, once) {
|
259
|
+
this.fn = fn;
|
260
|
+
this.context = context;
|
261
|
+
this.once = once || false;
|
262
|
+
}
|
263
|
+
function addListener(emitter, event, fn, context, once) {
|
264
|
+
if (typeof fn !== "function") {
|
265
|
+
throw new TypeError("The listener must be a function");
|
266
|
+
}
|
267
|
+
var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
|
268
|
+
if (!emitter._events[evt])
|
269
|
+
emitter._events[evt] = listener, emitter._eventsCount++;
|
270
|
+
else if (!emitter._events[evt].fn)
|
271
|
+
emitter._events[evt].push(listener);
|
272
|
+
else
|
273
|
+
emitter._events[evt] = [emitter._events[evt], listener];
|
274
|
+
return emitter;
|
275
|
+
}
|
276
|
+
function clearEvent(emitter, evt) {
|
277
|
+
if (--emitter._eventsCount === 0)
|
278
|
+
emitter._events = new Events();
|
279
|
+
else
|
280
|
+
delete emitter._events[evt];
|
281
|
+
}
|
282
|
+
function EventEmitter2() {
|
283
|
+
this._events = new Events();
|
284
|
+
this._eventsCount = 0;
|
285
|
+
}
|
286
|
+
EventEmitter2.prototype.eventNames = function eventNames() {
|
287
|
+
var names = [], events, name;
|
288
|
+
if (this._eventsCount === 0)
|
289
|
+
return names;
|
290
|
+
for (name in events = this._events) {
|
291
|
+
if (has.call(events, name))
|
292
|
+
names.push(prefix ? name.slice(1) : name);
|
293
|
+
}
|
294
|
+
if (Object.getOwnPropertySymbols) {
|
295
|
+
return names.concat(Object.getOwnPropertySymbols(events));
|
296
|
+
}
|
297
|
+
return names;
|
298
|
+
};
|
299
|
+
EventEmitter2.prototype.listeners = function listeners(event) {
|
300
|
+
var evt = prefix ? prefix + event : event, handlers = this._events[evt];
|
301
|
+
if (!handlers)
|
302
|
+
return [];
|
303
|
+
if (handlers.fn)
|
304
|
+
return [handlers.fn];
|
305
|
+
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
|
306
|
+
ee[i] = handlers[i].fn;
|
307
|
+
}
|
308
|
+
return ee;
|
309
|
+
};
|
310
|
+
EventEmitter2.prototype.listenerCount = function listenerCount(event) {
|
311
|
+
var evt = prefix ? prefix + event : event, listeners = this._events[evt];
|
312
|
+
if (!listeners)
|
313
|
+
return 0;
|
314
|
+
if (listeners.fn)
|
315
|
+
return 1;
|
316
|
+
return listeners.length;
|
317
|
+
};
|
318
|
+
EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
|
319
|
+
var evt = prefix ? prefix + event : event;
|
320
|
+
if (!this._events[evt])
|
321
|
+
return false;
|
322
|
+
var listeners = this._events[evt], len = arguments.length, args, i;
|
323
|
+
if (listeners.fn) {
|
324
|
+
if (listeners.once)
|
325
|
+
this.removeListener(event, listeners.fn, void 0, true);
|
326
|
+
switch (len) {
|
327
|
+
case 1:
|
328
|
+
return listeners.fn.call(listeners.context), true;
|
329
|
+
case 2:
|
330
|
+
return listeners.fn.call(listeners.context, a1), true;
|
331
|
+
case 3:
|
332
|
+
return listeners.fn.call(listeners.context, a1, a2), true;
|
333
|
+
case 4:
|
334
|
+
return listeners.fn.call(listeners.context, a1, a2, a3), true;
|
335
|
+
case 5:
|
336
|
+
return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
|
337
|
+
case 6:
|
338
|
+
return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
|
339
|
+
}
|
340
|
+
for (i = 1, args = new Array(len - 1); i < len; i++) {
|
341
|
+
args[i - 1] = arguments[i];
|
342
|
+
}
|
343
|
+
listeners.fn.apply(listeners.context, args);
|
344
|
+
} else {
|
345
|
+
var length = listeners.length, j;
|
346
|
+
for (i = 0; i < length; i++) {
|
347
|
+
if (listeners[i].once)
|
348
|
+
this.removeListener(event, listeners[i].fn, void 0, true);
|
349
|
+
switch (len) {
|
350
|
+
case 1:
|
351
|
+
listeners[i].fn.call(listeners[i].context);
|
352
|
+
break;
|
353
|
+
case 2:
|
354
|
+
listeners[i].fn.call(listeners[i].context, a1);
|
355
|
+
break;
|
356
|
+
case 3:
|
357
|
+
listeners[i].fn.call(listeners[i].context, a1, a2);
|
358
|
+
break;
|
359
|
+
case 4:
|
360
|
+
listeners[i].fn.call(listeners[i].context, a1, a2, a3);
|
361
|
+
break;
|
362
|
+
default:
|
363
|
+
if (!args)
|
364
|
+
for (j = 1, args = new Array(len - 1); j < len; j++) {
|
365
|
+
args[j - 1] = arguments[j];
|
366
|
+
}
|
367
|
+
listeners[i].fn.apply(listeners[i].context, args);
|
368
|
+
}
|
369
|
+
}
|
370
|
+
}
|
371
|
+
return true;
|
372
|
+
};
|
373
|
+
EventEmitter2.prototype.on = function on(event, fn, context) {
|
374
|
+
return addListener(this, event, fn, context, false);
|
375
|
+
};
|
376
|
+
EventEmitter2.prototype.once = function once(event, fn, context) {
|
377
|
+
return addListener(this, event, fn, context, true);
|
378
|
+
};
|
379
|
+
EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
|
380
|
+
var evt = prefix ? prefix + event : event;
|
381
|
+
if (!this._events[evt])
|
382
|
+
return this;
|
383
|
+
if (!fn) {
|
384
|
+
clearEvent(this, evt);
|
385
|
+
return this;
|
386
|
+
}
|
387
|
+
var listeners = this._events[evt];
|
388
|
+
if (listeners.fn) {
|
389
|
+
if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
|
390
|
+
clearEvent(this, evt);
|
391
|
+
}
|
392
|
+
} else {
|
393
|
+
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
|
394
|
+
if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
|
395
|
+
events.push(listeners[i]);
|
396
|
+
}
|
397
|
+
}
|
398
|
+
if (events.length)
|
399
|
+
this._events[evt] = events.length === 1 ? events[0] : events;
|
400
|
+
else
|
401
|
+
clearEvent(this, evt);
|
402
|
+
}
|
403
|
+
return this;
|
404
|
+
};
|
405
|
+
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
|
406
|
+
var evt;
|
407
|
+
if (event) {
|
408
|
+
evt = prefix ? prefix + event : event;
|
409
|
+
if (this._events[evt])
|
410
|
+
clearEvent(this, evt);
|
411
|
+
} else {
|
412
|
+
this._events = new Events();
|
413
|
+
this._eventsCount = 0;
|
414
|
+
}
|
415
|
+
return this;
|
416
|
+
};
|
417
|
+
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
|
418
|
+
EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
|
419
|
+
EventEmitter2.prefixed = prefix;
|
420
|
+
EventEmitter2.EventEmitter = EventEmitter2;
|
421
|
+
if ("undefined" !== typeof module2) {
|
422
|
+
module2.exports = EventEmitter2;
|
423
|
+
}
|
424
|
+
}
|
425
|
+
});
|
426
|
+
|
427
|
+
// src/index.ts
|
428
|
+
var src_exports = {};
|
429
|
+
__export(src_exports, {
|
430
|
+
default: () => chirperNode
|
431
|
+
});
|
432
|
+
module.exports = __toCommonJS(src_exports);
|
433
|
+
var import_short_unique_id = __toESM(require_short_unique_id());
|
434
|
+
var import_socket = __toESM(require("socket.io-client"));
|
435
|
+
|
436
|
+
// node_modules/eventemitter3/index.mjs
|
437
|
+
var import_index = __toESM(require_eventemitter3(), 1);
|
438
|
+
|
439
|
+
// src/api/AI.ts
|
440
|
+
var AI_default = (api) => ({
|
441
|
+
prompt: (opts) => {
|
442
|
+
return api.post(`/:account/ai`, opts);
|
443
|
+
},
|
444
|
+
image: (opts) => {
|
445
|
+
return api.post(`/:account/ai/image`, opts);
|
446
|
+
}
|
447
|
+
});
|
448
|
+
|
449
|
+
// src/api/Stat.ts
|
450
|
+
var Stat_default = (api) => ({
|
451
|
+
get: (metric, from = null, to = null) => {
|
452
|
+
return api.get(`/:account/stat/${metric}`, { from, to });
|
453
|
+
}
|
454
|
+
});
|
455
|
+
|
456
|
+
// src/api/Chirp.ts
|
457
|
+
var Chirp_default = (api) => ({
|
458
|
+
get: (id) => {
|
459
|
+
return api.get(`/chirp/${id}`);
|
460
|
+
},
|
461
|
+
list: ({ user, query, following, parent, username, skip, limit, search, contact, sort, filter, page } = {}) => {
|
462
|
+
return api.get(`/chirp`, { user, parent, following, query, username, skip, limit, search, contact, sort, filter, page });
|
463
|
+
},
|
464
|
+
delete: (id) => {
|
465
|
+
return api.delete(`/chirp/${id}`);
|
466
|
+
}
|
467
|
+
});
|
468
|
+
|
469
|
+
// src/api/Follow.ts
|
470
|
+
var Follow_default = (api) => ({
|
471
|
+
get: (id) => {
|
472
|
+
return api.get(`/follow/${id}`);
|
473
|
+
},
|
474
|
+
toggle: (chirper) => {
|
475
|
+
return api.post(`/follow/${chirper?.id || chirper}`);
|
476
|
+
}
|
477
|
+
});
|
478
|
+
|
479
|
+
// src/api/Chirper.ts
|
480
|
+
var Chirper_default = (api) => ({
|
481
|
+
get: (id) => {
|
482
|
+
return api.get(`/chirper/${id}`);
|
483
|
+
},
|
484
|
+
list: ({ user, skip, limit, search, contact, sort, filter, page } = {}) => {
|
485
|
+
return api.get(`/chirper`, { user, skip, limit, search, contact, sort, filter, page });
|
486
|
+
},
|
487
|
+
create: (item) => {
|
488
|
+
return api.post(`/chirper`, item);
|
489
|
+
},
|
490
|
+
update: (item, updates) => {
|
491
|
+
return api.patch(`/chirper/${item.id}`, updates ? {
|
492
|
+
updates
|
493
|
+
} : item);
|
494
|
+
},
|
495
|
+
delete: (id) => {
|
496
|
+
return api.delete(`/chirper/${id}`);
|
497
|
+
}
|
498
|
+
});
|
499
|
+
|
500
|
+
// src/index.ts
|
501
|
+
var uid = new import_short_unique_id.default({ length: 10 });
|
502
|
+
var chirperNode = class {
|
503
|
+
/**
|
504
|
+
* constructor
|
505
|
+
*
|
506
|
+
* @param props
|
507
|
+
*/
|
508
|
+
constructor({ url, version }) {
|
509
|
+
// ssid
|
510
|
+
this.key = null;
|
511
|
+
this.url = null;
|
512
|
+
this.cache = {};
|
513
|
+
this.events = new import_index.default();
|
514
|
+
// cache timeout
|
515
|
+
this.call = null;
|
516
|
+
this.socket = null;
|
517
|
+
this.account = null;
|
518
|
+
this.version = `v1`;
|
519
|
+
this.loading = true;
|
520
|
+
this.authing = null;
|
521
|
+
this.authKey = null;
|
522
|
+
this.shareKey = null;
|
523
|
+
this.customer = null;
|
524
|
+
this.presences = {};
|
525
|
+
this.connecting = null;
|
526
|
+
// options
|
527
|
+
this.options = {
|
528
|
+
path: "/ws",
|
529
|
+
cors: true,
|
530
|
+
agent: true,
|
531
|
+
reconnect: true,
|
532
|
+
transports: ["websocket"],
|
533
|
+
withCredentials: true
|
534
|
+
};
|
535
|
+
if (url)
|
536
|
+
this.url = url;
|
537
|
+
if (version)
|
538
|
+
this.version = version;
|
539
|
+
this.build = this.build.bind(this);
|
540
|
+
this.fetch = this.fetch.bind(this);
|
541
|
+
this.wsFetch = this.wsFetch.bind(this);
|
542
|
+
this.on = this.on.bind(this);
|
543
|
+
this.off = this.off.bind(this);
|
544
|
+
this.emit = this.emit.bind(this);
|
545
|
+
this.once = this.once.bind(this);
|
546
|
+
this.addListener = this.events.addListener.bind(this.events);
|
547
|
+
this.removeListener = this.events.removeListener.bind(this.events);
|
548
|
+
this.get = this.get.bind(this);
|
549
|
+
this.put = this.put.bind(this);
|
550
|
+
this.post = this.post.bind(this);
|
551
|
+
this.patch = this.patch.bind(this);
|
552
|
+
this.delete = this.delete.bind(this);
|
553
|
+
this.AI = AI_default(this);
|
554
|
+
this.Stat = Stat_default(this);
|
555
|
+
this.Chirp = Chirp_default(this);
|
556
|
+
this.Follow = Follow_default(this);
|
557
|
+
this.Chirper = Chirper_default(this);
|
558
|
+
this.build();
|
559
|
+
}
|
560
|
+
////////////////////////////////////////////////////////////////////////
|
561
|
+
//
|
562
|
+
// CALL FUNCTIONALITY
|
563
|
+
//
|
564
|
+
////////////////////////////////////////////////////////////////////////
|
565
|
+
/**
|
566
|
+
* build functionality
|
567
|
+
*/
|
568
|
+
build() {
|
569
|
+
this.__resolveConnecting = null;
|
570
|
+
this.connecting = new Promise((resolve) => {
|
571
|
+
this.__resolveConnecting = resolve;
|
572
|
+
});
|
573
|
+
if (!this.url)
|
574
|
+
return;
|
575
|
+
const actualSocket = import_socket.default.connect(`${this.url}`, this.options);
|
576
|
+
actualSocket.on("connect", async () => {
|
577
|
+
if (this.authing)
|
578
|
+
return;
|
579
|
+
this.authing = this.auth(this.authKey, this.shareKey);
|
580
|
+
await this.authing;
|
581
|
+
this.authing = null;
|
582
|
+
this.__resolveConnecting();
|
583
|
+
});
|
584
|
+
actualSocket.on("disconnect", () => {
|
585
|
+
this.connecting = new Promise((resolve) => {
|
586
|
+
this.__resolveConnecting = resolve;
|
587
|
+
});
|
588
|
+
});
|
589
|
+
this.socket = actualSocket;
|
590
|
+
}
|
591
|
+
/**
|
592
|
+
* authenticate api
|
593
|
+
*
|
594
|
+
* @param key
|
595
|
+
* @param authKey
|
596
|
+
*/
|
597
|
+
async auth() {
|
598
|
+
this.loading = true;
|
599
|
+
this.events.emit("loading", true);
|
600
|
+
const auth = await this.get(`/auth`, {
|
601
|
+
key: this.key
|
602
|
+
}, false, false);
|
603
|
+
if (auth?.user) {
|
604
|
+
this.user = auth.user;
|
605
|
+
this.events.emit("user", auth.user);
|
606
|
+
}
|
607
|
+
this.loading = false;
|
608
|
+
this.events.emit("loading", false);
|
609
|
+
if (typeof window !== "undefined")
|
610
|
+
window.chirper = this;
|
611
|
+
}
|
612
|
+
/**
|
613
|
+
* fetch from http api
|
614
|
+
*
|
615
|
+
* @param method
|
616
|
+
* @param path
|
617
|
+
* @param data
|
618
|
+
* @param cache
|
619
|
+
*/
|
620
|
+
async fetch(method, path, data = {}, cache = false) {
|
621
|
+
if (["patch", "put", "delete", "post"].includes(method.toLowerCase()))
|
622
|
+
cache = false;
|
623
|
+
if (cache && this.cache[`${method}${path}${JSON.stringify(data)}`]) {
|
624
|
+
return this.cache[`${method}${path}${JSON.stringify(data)}`];
|
625
|
+
} else {
|
626
|
+
delete this.cache[`${method}${path}${JSON.stringify(data)}`];
|
627
|
+
}
|
628
|
+
console.time(`[chirper] [fetch] ${method}:${path} ${JSON.stringify(data)}`);
|
629
|
+
let result;
|
630
|
+
try {
|
631
|
+
const res = await fetch(`${this.url}${path}${`${method}`.toLowerCase() === "get" ? `?${new URLSearchParams(data)}` : ""}`, {
|
632
|
+
body: `${method}`.toLowerCase() !== "get" ? JSON.stringify(data) : void 0,
|
633
|
+
headers: {
|
634
|
+
"Content-Type": "application/json",
|
635
|
+
"Authentication": this.key ? `Bearer ${this.key}` : void 0
|
636
|
+
},
|
637
|
+
credentials: "include"
|
638
|
+
});
|
639
|
+
result = await res.json();
|
640
|
+
} catch (e) {
|
641
|
+
console.timeEnd(`[chirper] [fetch] ${method}:${path} ${JSON.stringify(data)}`);
|
642
|
+
throw e;
|
643
|
+
}
|
644
|
+
console.timeEnd(`[chirper] [fetch] ${method}:${path} ${JSON.stringify(data)}`);
|
645
|
+
if (!result?.success)
|
646
|
+
throw new Error(result.message);
|
647
|
+
if (cache) {
|
648
|
+
this.cache[`${method}${path}${JSON.stringify(data)}`] = result;
|
649
|
+
this.cache[`${method}${path}${JSON.stringify(data)}`].then(() => {
|
650
|
+
if (typeof cache === "number") {
|
651
|
+
setTimeout(() => {
|
652
|
+
delete this.cache[`${method}${path}${JSON.stringify(data)}`];
|
653
|
+
}, cache);
|
654
|
+
} else {
|
655
|
+
delete this.cache[`${method}${path}${JSON.stringify(data)}`];
|
656
|
+
}
|
657
|
+
});
|
658
|
+
}
|
659
|
+
return result.result;
|
660
|
+
}
|
661
|
+
/**
|
662
|
+
* call api method
|
663
|
+
*
|
664
|
+
* @param method
|
665
|
+
* @param path
|
666
|
+
* @param data
|
667
|
+
* @param cache
|
668
|
+
* @returns
|
669
|
+
*/
|
670
|
+
async wsFetch(method, path, data = {}, cache = false, waitForAuth = true) {
|
671
|
+
if (waitForAuth)
|
672
|
+
await this.connecting;
|
673
|
+
if (waitForAuth)
|
674
|
+
await this.authing;
|
675
|
+
if (waitForAuth && !this.account && path.includes(":account")) {
|
676
|
+
await new Promise((resolve) => {
|
677
|
+
this.events.once("account", resolve);
|
678
|
+
});
|
679
|
+
}
|
680
|
+
if (this.account)
|
681
|
+
path = path.replace(":account", this.account?.id);
|
682
|
+
if (["patch", "put", "delete", "post"].includes(method.toLowerCase()))
|
683
|
+
cache = false;
|
684
|
+
if (cache && this.cache[`${method}${path}${JSON.stringify(data)}`]) {
|
685
|
+
return this.cache[`${method}${path}${JSON.stringify(data)}`];
|
686
|
+
} else {
|
687
|
+
delete this.cache[`${method}${path}${JSON.stringify(data)}`];
|
688
|
+
}
|
689
|
+
const id = uid();
|
690
|
+
console.time(`[chirper] [${id}] ${method}:${path} ${JSON.stringify(data)}`);
|
691
|
+
const result = new Promise((resolve, reject) => {
|
692
|
+
this.socket.once(id, ({ success, result: result2, message }) => {
|
693
|
+
console.timeEnd(`[chirper] [${id}] ${method}:${path} ${JSON.stringify(data)}`);
|
694
|
+
if (success)
|
695
|
+
return resolve(result2);
|
696
|
+
reject(message);
|
697
|
+
});
|
698
|
+
});
|
699
|
+
if (cache) {
|
700
|
+
this.cache[`${method}${path}${JSON.stringify(data)}`] = result;
|
701
|
+
this.cache[`${method}${path}${JSON.stringify(data)}`].then(() => {
|
702
|
+
if (typeof cache === "number") {
|
703
|
+
setTimeout(() => {
|
704
|
+
delete this.cache[`${method}${path}${JSON.stringify(data)}`];
|
705
|
+
}, cache);
|
706
|
+
} else {
|
707
|
+
delete this.cache[`${method}${path}${JSON.stringify(data)}`];
|
708
|
+
}
|
709
|
+
});
|
710
|
+
}
|
711
|
+
this.socket.emit("call", id, method.toUpperCase(), path, data);
|
712
|
+
return result;
|
713
|
+
}
|
714
|
+
/**
|
715
|
+
* on
|
716
|
+
*
|
717
|
+
* @param args
|
718
|
+
*/
|
719
|
+
on(...args) {
|
720
|
+
this.socket.on(...args);
|
721
|
+
}
|
722
|
+
/**
|
723
|
+
* off
|
724
|
+
*
|
725
|
+
* @param args
|
726
|
+
*/
|
727
|
+
off(...args) {
|
728
|
+
this.socket.off(...args);
|
729
|
+
}
|
730
|
+
/**
|
731
|
+
* emit
|
732
|
+
*
|
733
|
+
* @param args
|
734
|
+
*/
|
735
|
+
emit(...args) {
|
736
|
+
this.socket.emit(...args);
|
737
|
+
}
|
738
|
+
/**
|
739
|
+
* once
|
740
|
+
*
|
741
|
+
* @param args
|
742
|
+
*/
|
743
|
+
once(...args) {
|
744
|
+
this.socket.once(...args);
|
745
|
+
}
|
746
|
+
/**
|
747
|
+
* api get
|
748
|
+
*
|
749
|
+
* @param path
|
750
|
+
* @param data
|
751
|
+
* @returns
|
752
|
+
*/
|
753
|
+
get(path, data, ...args) {
|
754
|
+
return this.wsFetch("GET", `/${this.version}${path}`, data, ...args);
|
755
|
+
}
|
756
|
+
/**
|
757
|
+
* api put
|
758
|
+
*
|
759
|
+
* @param path
|
760
|
+
* @param data
|
761
|
+
* @returns
|
762
|
+
*/
|
763
|
+
put(path, data, ...args) {
|
764
|
+
return this.wsFetch("PUT", `/${this.version}${path}`, data, ...args);
|
765
|
+
}
|
766
|
+
/**
|
767
|
+
* api post
|
768
|
+
*
|
769
|
+
* @param path
|
770
|
+
* @param data
|
771
|
+
* @returns
|
772
|
+
*/
|
773
|
+
post(path, data, ...args) {
|
774
|
+
return this.wsFetch("POST", `/${this.version}${path}`, data, ...args);
|
775
|
+
}
|
776
|
+
/**
|
777
|
+
* api post
|
778
|
+
*
|
779
|
+
* @param path
|
780
|
+
* @param data
|
781
|
+
* @returns
|
782
|
+
*/
|
783
|
+
patch(path, data, ...args) {
|
784
|
+
return this.wsFetch("PATCH", `/${this.version}${path}`, data, ...args);
|
785
|
+
}
|
786
|
+
/**
|
787
|
+
* api post
|
788
|
+
*
|
789
|
+
* @param path
|
790
|
+
* @param data
|
791
|
+
* @returns
|
792
|
+
*/
|
793
|
+
delete(path, data, ...args) {
|
794
|
+
return this.wsFetch("DELETE", `/${this.version}${path}`, data, ...args);
|
795
|
+
}
|
796
|
+
};
|
package/package.json
CHANGED
package/src/api/Chirp.ts
ADDED
@@ -0,0 +1,17 @@
|
|
1
|
+
|
2
|
+
/**
|
3
|
+
* chirp api
|
4
|
+
*/
|
5
|
+
export default (api) => ({
|
6
|
+
get : (id) => {
|
7
|
+
return api.get(`/chirp/${id}`);
|
8
|
+
},
|
9
|
+
list : ({ user, query, following, parent, username, skip, limit, search, contact, sort, filter, page } = {}) => {
|
10
|
+
// return done
|
11
|
+
return api.get(`/chirp`, { user, parent, following, query, username, skip, limit, search, contact, sort, filter, page });
|
12
|
+
},
|
13
|
+
delete : (id) => {
|
14
|
+
// return patch
|
15
|
+
return api.delete(`/chirp/${id}`);
|
16
|
+
}
|
17
|
+
});
|
@@ -0,0 +1,27 @@
|
|
1
|
+
|
2
|
+
/**
|
3
|
+
* chirper api
|
4
|
+
*/
|
5
|
+
export default (api) => ({
|
6
|
+
get : (id) => {
|
7
|
+
return api.get(`/chirper/${id}`);
|
8
|
+
},
|
9
|
+
list : ({ user, skip, limit, search, contact, sort, filter, page } = {}) => {
|
10
|
+
// return done
|
11
|
+
return api.get(`/chirper`, { user, skip, limit, search, contact, sort, filter, page });
|
12
|
+
},
|
13
|
+
create : (item) => {
|
14
|
+
// return patch
|
15
|
+
return api.post(`/chirper`, item);
|
16
|
+
},
|
17
|
+
update : (item, updates) => {
|
18
|
+
// return patch
|
19
|
+
return api.patch(`/chirper/${item.id}`, updates ? {
|
20
|
+
updates,
|
21
|
+
} : item);
|
22
|
+
},
|
23
|
+
delete : (id) => {
|
24
|
+
// return patch
|
25
|
+
return api.delete(`/chirper/${id}`);
|
26
|
+
}
|
27
|
+
});
|
package/src/index.ts
CHANGED
@@ -10,6 +10,9 @@ const uid = new shortid({ length : 10 });
|
|
10
10
|
// local apis
|
11
11
|
import AI from './api/AI';
|
12
12
|
import Stat from './api/Stat';
|
13
|
+
import Chirp from './api/Chirp';
|
14
|
+
import Follow from './api/Follow';
|
15
|
+
import Chirper from './api/Chirper';
|
13
16
|
|
14
17
|
// socket context
|
15
18
|
export default class chirperNode {
|
@@ -80,6 +83,9 @@ export default class chirperNode {
|
|
80
83
|
// api
|
81
84
|
this.AI = AI(this);
|
82
85
|
this.Stat = Stat(this);
|
86
|
+
this.Chirp = Chirp(this);
|
87
|
+
this.Follow = Follow(this);
|
88
|
+
this.Chirper = Chirper(this);
|
83
89
|
|
84
90
|
// build
|
85
91
|
this.build();
|