@chirper/node 0.0.3 → 0.0.5

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 CHANGED
@@ -1,796 +1 @@
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
- };
1
+ var Q=Object.create;var S=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var F=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),et=(s,t)=>{for(var e in t)S(s,e,{get:t[e],enumerable:!0})},k=(s,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of X(t))!tt.call(s,n)&&n!==e&&S(s,n,{get:()=>t[n],enumerable:!(i=W(t,n))||i.enumerable});return s};var L=(s,t,e)=>(e=s!=null?Q(Z(s)):{},k(t||!s||!s.__esModule?S(e,"default",{value:s,enumerable:!0}):e,s)),it=s=>k(S({},"__esModule",{value:!0}),s);var J=F((lt,E)=>{var U=(()=>{var s=Object.defineProperty,t=Object.getOwnPropertySymbols,e=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,n=(y,_,g)=>_ in y?s(y,_,{enumerable:!0,configurable:!0,writable:!0,value:g}):y[_]=g,l=(y,_)=>{for(var g in _||(_={}))e.call(_,g)&&n(y,g,_[g]);if(t)for(var g of t(_))i.call(_,g)&&n(y,g,_[g]);return y},h=y=>s(y,"__esModule",{value:!0}),u=(y,_)=>{h(y);for(var g in _)s(y,g,{get:_[g],enumerable:!0})},r={};u(r,{DEFAULT_UUID_LENGTH:()=>d,default:()=>m});var $="4.4.4",d=6,c={dictionary:"alphanum",shuffle:!0,debug:!1,length:d},b=class extends Function{constructor(y={}){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=(...o)=>{let a=[...o];if(a[0]=`[short-unique-id] ${o[0]}`,this.debug===!0&&typeof console<"u"&&console!==null)return console.log(...a)},this.setDictionary=(o,a)=>{let f;if(o&&Array.isArray(o)&&o.length>1)f=o;else{f=[];let v;this.dictIndex=v=0;let x=`_${o}_dict_ranges`,N=this[x];Object.keys(N).forEach(Y=>{let z=Y;for(this.dictRange=N[z],this.lowerBound=this.dictRange[0],this.upperBound=this.dictRange[1],this.dictIndex=v=this.lowerBound;this.lowerBound<=this.upperBound?v<this.upperBound:v>this.upperBound;this.dictIndex=this.lowerBound<=this.upperBound?v+=1:v-=1)f.push(String.fromCharCode(this.dictIndex))})}a&&(f=f.sort(()=>Math.random()-.5)),this.dict=f,this.dictLength=this.dict.length,this.counter=0},this.seq=()=>this.sequentialUUID(),this.sequentialUUID=()=>{let o,a,f="";o=this.counter;do a=o%this.dictLength,o=Math.trunc(o/this.dictLength),f+=this.dict[a];while(o!==0);return this.counter+=1,f},this.randomUUID=(o=this.uuidLength||d)=>{let a,f,v;if(o===null||typeof o>"u"||o<1)throw new Error("Invalid UUID Length Provided");let x=o>=0;for(a="",v=0;v<o;v+=1)f=parseInt((Math.random()*this.dictLength).toFixed(0),10)%this.dictLength,a+=this.dict[f];return a},this.availableUUIDs=(o=this.uuidLength)=>parseFloat(Math.pow([...new Set(this.dict)].length,o).toFixed(0)),this.approxMaxBeforeCollision=(o=this.availableUUIDs(this.uuidLength))=>parseFloat(Math.sqrt(Math.PI/2*o).toFixed(20)),this.collisionProbability=(o=this.availableUUIDs(this.uuidLength),a=this.uuidLength)=>parseFloat((this.approxMaxBeforeCollision(o)/this.availableUUIDs(a)).toFixed(20)),this.uniqueness=(o=this.availableUUIDs(this.uuidLength))=>{let a=parseFloat((1-this.approxMaxBeforeCollision(o)/o).toFixed(20));return a>1?1:a<0?0:a},this.getVersion=()=>this.version,this.stamp=o=>{if(typeof o!="number"||o<10)throw new Error("Param finalLength must be number greater than 10");let a=Math.floor(+new Date/1e3).toString(16),f=o-9,v=Math.round(Math.random()*(f>15?15:f)),x=this.randomUUID(f);return`${x.substr(0,v)}${a}${x.substr(v)}${v.toString(16)}`},this.parseStamp=o=>{if(o.length<10)throw new Error("Stamp length invalid");let a=parseInt(o.substr(o.length-1,1),16);return new Date(parseInt(o.substr(a,8),16)*1e3)};let _=l(l({},c),y);this.counter=0,this.debug=!1,this.dict=[],this.version=$;let{dictionary:g,shuffle:H,length:V}=_;return this.uuidLength=V,this.setDictionary(g,H),this.debug=_.debug,this.log(this.dict),this.log(`Generator instantiated with Dictionary Size ${this.dictLength}`),new Proxy(this,{apply:(o,a,f)=>this.randomUUID(...f)})}},m=b;return m.default=b,r})();typeof E<"u"&&(E.exports=U.default),typeof window<"u"&&(U=U.default)});var T=F((at,P)=>{"use strict";var st=Object.prototype.hasOwnProperty,w="~";function O(){}Object.create&&(O.prototype=Object.create(null),new O().__proto__||(w=!1));function rt(s,t,e){this.fn=s,this.context=t,this.once=e||!1}function B(s,t,e,i,n){if(typeof e!="function")throw new TypeError("The listener must be a function");var l=new rt(e,i||s,n),h=w?w+t:t;return s._events[h]?s._events[h].fn?s._events[h]=[s._events[h],l]:s._events[h].push(l):(s._events[h]=l,s._eventsCount++),s}function I(s,t){--s._eventsCount===0?s._events=new O:delete s._events[t]}function p(){this._events=new O,this._eventsCount=0}p.prototype.eventNames=function(){var t=[],e,i;if(this._eventsCount===0)return t;for(i in e=this._events)st.call(e,i)&&t.push(w?i.slice(1):i);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};p.prototype.listeners=function(t){var e=w?w+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,l=i.length,h=new Array(l);n<l;n++)h[n]=i[n].fn;return h};p.prototype.listenerCount=function(t){var e=w?w+t:t,i=this._events[e];return i?i.fn?1:i.length:0};p.prototype.emit=function(t,e,i,n,l,h){var u=w?w+t:t;if(!this._events[u])return!1;var r=this._events[u],$=arguments.length,d,c;if(r.fn){switch(r.once&&this.removeListener(t,r.fn,void 0,!0),$){case 1:return r.fn.call(r.context),!0;case 2:return r.fn.call(r.context,e),!0;case 3:return r.fn.call(r.context,e,i),!0;case 4:return r.fn.call(r.context,e,i,n),!0;case 5:return r.fn.call(r.context,e,i,n,l),!0;case 6:return r.fn.call(r.context,e,i,n,l,h),!0}for(c=1,d=new Array($-1);c<$;c++)d[c-1]=arguments[c];r.fn.apply(r.context,d)}else{var b=r.length,m;for(c=0;c<b;c++)switch(r[c].once&&this.removeListener(t,r[c].fn,void 0,!0),$){case 1:r[c].fn.call(r[c].context);break;case 2:r[c].fn.call(r[c].context,e);break;case 3:r[c].fn.call(r[c].context,e,i);break;case 4:r[c].fn.call(r[c].context,e,i,n);break;default:if(!d)for(m=1,d=new Array($-1);m<$;m++)d[m-1]=arguments[m];r[c].fn.apply(r[c].context,d)}}return!0};p.prototype.on=function(t,e,i){return B(this,t,e,i,!1)};p.prototype.once=function(t,e,i){return B(this,t,e,i,!0)};p.prototype.removeListener=function(t,e,i,n){var l=w?w+t:t;if(!this._events[l])return this;if(!e)return I(this,l),this;var h=this._events[l];if(h.fn)h.fn===e&&(!n||h.once)&&(!i||h.context===i)&&I(this,l);else{for(var u=0,r=[],$=h.length;u<$;u++)(h[u].fn!==e||n&&!h[u].once||i&&h[u].context!==i)&&r.push(h[u]);r.length?this._events[l]=r.length===1?r[0]:r:I(this,l)}return this};p.prototype.removeAllListeners=function(t){var e;return t?(e=w?w+t:t,this._events[e]&&I(this,e)):(this._events=new O,this._eventsCount=0),this};p.prototype.off=p.prototype.removeListener;p.prototype.addListener=p.prototype.on;p.prefixed=w;p.EventEmitter=p;typeof P<"u"&&(P.exports=p)});var ot={};et(ot,{default:()=>C});module.exports=it(ot);var K=L(J()),G=L(require("socket.io-client"));var D=L(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 q=s=>({get:t=>s.get(`/chirp/${t}`),list:({user:t,query:e,following:i,parent:n,username:l,skip:h,limit:u,search:r,contact:$,sort:d,filter:c,page:b}={})=>s.get("/chirp",{user:t,parent:n,following:i,query:e,username:l,skip:h,limit:u,search:r,contact:$,sort:d,filter:c,page:b}),count:t=>s.get(`/chirp/${t?.id||t}/count`),delete:t=>s.delete(`/chirp/${t}`)});var R=s=>({get:t=>s.get(`/follow/${t}`),toggle:t=>s.post(`/follow/${t?.id||t}`)});var j=s=>({get:t=>s.get(`/chirper/${t}`),list:({user:t,skip:e,limit:i,search:n,contact:l,sort:h,filter:u,page:r}={})=>s.get("/chirper",{user:t,skip:e,limit:i,search:n,contact:l,sort:h,filter:u,page:r}),create:t=>s.post("/chirper",t),update:(t,e)=>s.patch(`/chirper/${t.id}`,e?{updates:e}:t),delete:t=>s.delete(`/chirper/${t}`)});var nt=new K.default({length:10}),C=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.Chirp=q(this),this.Follow=R(this),this.Chirper=j(this),this.build()}build(){if(this.__resolveConnecting=null,this.connecting=new Promise(e=>{this.__resolveConnecting=e}),!this.url)return;let t=G.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={},n=!1){if(["patch","put","delete","post"].includes(t.toLowerCase())&&(n=!1),n&&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 l;try{l=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)}`),!l?.success)throw new Error(l.message);return n&&(this.cache[`${t}${e}${JSON.stringify(i)}`]=l,this.cache[`${t}${e}${JSON.stringify(i)}`].then(()=>{typeof n=="number"?setTimeout(()=>{delete this.cache[`${t}${e}${JSON.stringify(i)}`]},n):delete this.cache[`${t}${e}${JSON.stringify(i)}`]})),l.result}async wsFetch(t,e,i={},n=!1,l=!0){if(l&&await this.connecting,l&&await this.authing,l&&!this.account&&e.includes(":account")&&await new Promise(r=>{this.events.once("account",r)}),this.account&&(e=e.replace(":account",this.account?.id)),["patch","put","delete","post"].includes(t.toLowerCase())&&(n=!1),n&&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=nt();console.time(`[chirper] [${h}] ${t}:${e} ${JSON.stringify(i)}`);let u=new Promise((r,$)=>{this.socket.once(h,({success:d,result:c,message:b})=>{if(console.timeEnd(`[chirper] [${h}] ${t}:${e} ${JSON.stringify(i)}`),d)return r(c);$(b)})});return n&&(this.cache[`${t}${e}${JSON.stringify(i)}`]=u,this.cache[`${t}${e}${JSON.stringify(i)}`].then(()=>{typeof n=="number"?setTimeout(()=>{delete this.cache[`${t}${e}${JSON.stringify(i)}`]},n):delete this.cache[`${t}${e}${JSON.stringify(i)}`]})),this.socket.emit("call",h,t.toUpperCase(),e,i),u}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)}};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chirper/node",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "",
5
5
  "main": "dist/bundle.js",
6
6
  "scripts": {
package/src/api/Chirp.ts CHANGED
@@ -10,6 +10,10 @@ export default (api) => ({
10
10
  // return done
11
11
  return api.get(`/chirp`, { user, parent, following, query, username, skip, limit, search, contact, sort, filter, page });
12
12
  },
13
+ count : (thread) => {
14
+ // return done
15
+ return api.get(`/chirp/${thread?.id || thread}/count`);
16
+ },
13
17
  delete : (id) => {
14
18
  // return patch
15
19
  return api.delete(`/chirp/${id}`);