@livequery/rest 2.0.27 → 2.0.62

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/package.json CHANGED
@@ -3,30 +3,38 @@
3
3
  "repository": {
4
4
  "url": "https://github.com/livequery/rest"
5
5
  },
6
- "version": "2.0.27",
6
+ "version": "2.0.62",
7
7
  "type": "module",
8
8
  "description": "",
9
9
  "main": "build/index.js",
10
10
  "types": "build/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
11
18
  "files": [
12
19
  "build/**/*"
13
20
  ],
14
21
  "dependencies": {
15
- "query-string": "^7.0.1",
16
- "uuid": "^8.3.2"
22
+ "rxjs": "^7.8.1",
23
+ "uuid": "^13.0.0"
17
24
  },
18
25
  "devDependencies": {
19
- "rxjs": "^7.8.1",
20
- "typescript": "5.6.3",
21
- "@types/uuid": "^8.3.0",
22
- "@livequery/types": "2.0.15"
26
+ "@livequery/new": "2.0.61",
27
+ "typescript": "5.6.3"
23
28
  },
24
29
  "peerDependencies": {},
25
30
  "scripts": {
26
- "test": "echo \"Error: no test specified\" && exit 1",
27
- "build": "rm -rf build; tsc -b .",
28
- "deploy": "yarn build; git add .; git commit -m \"Update\"; git push origin master; npm publish --access public"
31
+ "clean": "rm -rf dist",
32
+ "build:js": "bun build ./src/index.ts --outdir ./dist --target browser --format esm --sourcemap",
33
+ "build:types": "bunx tsc -p tsconfig.build.json",
34
+ "build": "bun run clean && bun run build:js && bun run build:types",
35
+ "build:watch": "bun build ./src/index.ts --outdir ./dist --target browser --format esm --watch",
36
+ "prepublishOnly": "bun run build"
29
37
  },
30
38
  "author": "",
31
39
  "license": "ISC"
32
- }
40
+ }
@@ -1,29 +0,0 @@
1
- import { Transporter, QueryOption, QueryStream, Response as ApiResponse, TransporterHook } from '@livequery/types';
2
- type MaybePromise<T> = T | Promise<T>;
3
- export type ApiRequest = {
4
- url: RequestInfo | URL | string;
5
- options?: RequestInit;
6
- };
7
- export type RestTransporterConfig = {
8
- base_url: () => MaybePromise<string>;
9
- websocket_url?: () => MaybePromise<string>;
10
- };
11
- export declare class RestTransporter implements Transporter {
12
- #private;
13
- private config;
14
- private socket;
15
- constructor(config: RestTransporterConfig);
16
- hook(hook: TransporterHook): RestTransporter;
17
- query<T extends {
18
- id: string;
19
- }>(ref: string, options?: Partial<QueryOption<T>>): import("rxjs").Observable<QueryStream<T> | {
20
- error: any;
21
- }>;
22
- private call;
23
- get<T>(ref: string, query?: any): Promise<T>;
24
- add<T extends {} = {}>(ref: string, data: Partial<T>): Promise<any>;
25
- update<T extends {} = {}>(ref: string, data: Partial<T>, method?: 'PATCH' | 'PUT'): Promise<any>;
26
- remove<T>(ref: string): Promise<T>;
27
- trigger<T extends {}>(ref: string, name: string, payload?: any, query?: any): Promise<ApiResponse<T>>;
28
- }
29
- export {};
@@ -1,132 +0,0 @@
1
- import { of, firstValueFrom } from 'rxjs';
2
- import { catchError, map, mergeMap } from 'rxjs/operators';
3
- import { merge, pipe } from 'rxjs';
4
- import { Socket } from './Socket.js';
5
- import qs from 'query-string';
6
- export class RestTransporter {
7
- config;
8
- socket;
9
- constructor(config) {
10
- this.config = config;
11
- config.websocket_url && (this.socket = new Socket(config.websocket_url));
12
- }
13
- hook(hook) {
14
- return {
15
- ...this,
16
- hook: (next_hook) => {
17
- return this.hook(next => pipe(hook(() => next_hook(next))));
18
- },
19
- get: (ref, query = {}) => {
20
- return this.call(ref, 'GET', null, query, hook);
21
- },
22
- add: (ref, data) => {
23
- return this.call(ref, 'POST', data, {}, hook);
24
- },
25
- update: (ref, data, method = 'PATCH') => {
26
- return this.call(ref, method, data, {}, hook);
27
- },
28
- remove: (ref) => {
29
- return this.call(ref, 'DELETE', {}, {}, hook);
30
- },
31
- trigger: (ref, name, payload, query) => {
32
- return this.call(`${ref}/~${name}`, 'POST', payload, query, hook);
33
- },
34
- query: (ref, options) => {
35
- return this.#query(ref, options, hook);
36
- },
37
- };
38
- }
39
- query(ref, options) {
40
- return this.#query(ref, options);
41
- }
42
- #query(ref, options, hook) {
43
- const http_request = merge(this.socket?.$reconnect || of(1))
44
- .pipe(mergeMap(() => this.call(ref, 'GET', undefined, options, hook)), map(({ data, error }) => {
45
- if (error)
46
- throw error;
47
- data.subscription_token && this.socket?.subscribe(data.subscription_token);
48
- const collection = data;
49
- // If collection
50
- if (collection.items) {
51
- return {
52
- data: {
53
- summary: collection.summary,
54
- changes: collection.items.map(data => ({ data, type: 'added', ref })),
55
- paging: { ...collection, n: 0 }
56
- }
57
- };
58
- }
59
- // If document
60
- const document = data;
61
- return {
62
- data: {
63
- summary: collection.summary,
64
- changes: [{ data: document.item, type: 'added', ref }],
65
- paging: { ...collection, n: 0 }
66
- }
67
- };
68
- }), catchError(error => of({ error })));
69
- const websocket_sync = (!this.socket || options[':after'] || options[':before'] || options[':around']) ? of() : (this.socket.listen(ref).pipe(map((change) => ({ data: { changes: [change] } }))));
70
- return merge(http_request, websocket_sync);
71
- }
72
- async call(url, method, payload, query = {}, hook) {
73
- function encode_query(query) {
74
- if (!query || Object.keys(query || {}).length == 0)
75
- return '';
76
- const encoded_query = Object.keys(query).reduce((o, key) => ({
77
- ...o,
78
- [key]: typeof query[key] == 'object' ? JSON.stringify(query[key]) : query[key]
79
- }), {});
80
- return `?${qs.stringify(encoded_query)}`;
81
- }
82
- const headers = {
83
- ...payload ? {
84
- 'Content-Type': 'application/json'
85
- } : {},
86
- ...this.socket ? {
87
- socket_id: this.socket.client_id,
88
- 'x-lcid': this.socket.client_id,
89
- 'x-lgid': await firstValueFrom(this.socket.$gateway.pipe(map(g => g.id)))
90
- } : {}
91
- };
92
- try {
93
- const request = {
94
- url: `${this.config.base_url()}/${url}${encode_query(query)}`,
95
- options: {
96
- method,
97
- headers,
98
- ...payload ? { body: JSON.stringify(payload) } : {},
99
- }
100
- };
101
- const next = () => pipe(mergeMap(async (mapped) => {
102
- const response = await fetch(mapped.url, mapped.options).then(r => r.json());
103
- return {
104
- ...response,
105
- __request: mapped
106
- };
107
- }));
108
- const body = await firstValueFrom(of(request).pipe(hook ? hook(next) : next()));
109
- if (body.error)
110
- throw body.error;
111
- return body;
112
- }
113
- catch (error) {
114
- throw error;
115
- }
116
- }
117
- get(ref, query = {}) {
118
- return this.call(ref, 'GET', null, query);
119
- }
120
- add(ref, data) {
121
- return this.call(ref, 'POST', data, {});
122
- }
123
- update(ref, data, method = 'PATCH') {
124
- return this.call(ref, method, data, {});
125
- }
126
- remove(ref) {
127
- return this.call(ref, 'DELETE');
128
- }
129
- trigger(ref, name, payload, query) {
130
- return this.call(`${ref}/~${name}`, 'POST', payload, query);
131
- }
132
- }
package/build/Socket.d.ts DELETED
@@ -1,19 +0,0 @@
1
- import { UpdatedData } from "@livequery/types";
2
- import { Observable, BehaviorSubject } from "rxjs";
3
- export declare class Socket {
4
- #private;
5
- private ws_url_fatory;
6
- readonly client_id: string;
7
- readonly $gateway: BehaviorSubject<{
8
- id: string;
9
- }>;
10
- readonly $reconnect: BehaviorSubject<number>;
11
- constructor(ws_url_fatory: () => string | Promise<string>);
12
- stop(): void;
13
- private $sync;
14
- $hello(e: {
15
- gid: string;
16
- }): void;
17
- subscribe(realtime_token: string): void;
18
- listen(ref: string): Observable<UpdatedData>;
19
- }
package/build/Socket.js DELETED
@@ -1,64 +0,0 @@
1
- import { fromEvent, Subject, BehaviorSubject, merge, ReplaySubject, of, interval } from "rxjs";
2
- import { delay, finalize, map, mergeMap, retry, switchMap, tap } from "rxjs/operators";
3
- import { v4 } from 'uuid';
4
- export class Socket {
5
- ws_url_fatory;
6
- client_id = v4();
7
- $gateway = new BehaviorSubject(undefined);
8
- $reconnect = new BehaviorSubject(0);
9
- #topics = new Map();
10
- #$input = new ReplaySubject(1000);
11
- #running;
12
- #init() {
13
- if (typeof WebSocket == 'undefined')
14
- return;
15
- return of(1).pipe(mergeMap(() => this.ws_url_fatory()), map(url => new WebSocket(url)), switchMap(ws => merge(fromEvent(ws, 'closed').pipe(map(e => { throw e; })), fromEvent(ws, 'close').pipe(map(e => { throw e; })), fromEvent(ws, 'error').pipe(map(e => { throw e; })), fromEvent(ws, 'open').pipe(switchMap(() => interval(60000)), tap(() => ws.send(JSON.stringify({ event: 'ping' })))), fromEvent(ws, 'open').pipe(tap(() => {
16
- console.log(this.$reconnect.getValue() == 0 ? 'Websocket connected' : `Websocket re-connected (${this.$reconnect.getValue()})`);
17
- this.$reconnect.next(this.$reconnect.getValue() + 1);
18
- ws.send(JSON.stringify({ event: 'start', data: { id: this.client_id } }));
19
- }), delay(1000), tap(() => !this.$gateway.getValue() && this.$gateway.next({ id: '' })), mergeMap(() => this.#$input), tap(data => ws.send(JSON.stringify(data)))), fromEvent(ws, 'message').pipe(tap((evt) => {
20
- const e = JSON.parse(evt.data);
21
- this[`$${e.event}`]?.(e);
22
- }))).pipe(finalize(() => ws.close()))), retry({ delay: 1000 })).subscribe();
23
- }
24
- constructor(ws_url_fatory) {
25
- this.ws_url_fatory = ws_url_fatory;
26
- this.#running = this.#init();
27
- }
28
- stop() {
29
- this.#running?.unsubscribe();
30
- }
31
- $sync(e) {
32
- for (const change of e.data.changes) {
33
- // Collection ref broadcast
34
- this.#topics.get(change.ref)?.stream.next(change);
35
- // Document ref broadcast
36
- const ref = `${change.ref}/${change.data.id}`;
37
- this.#topics.get(ref)?.stream.next({
38
- ...change,
39
- ref
40
- });
41
- }
42
- }
43
- $hello(e) {
44
- this.$gateway.next({ id: e.gid });
45
- }
46
- subscribe(realtime_token) {
47
- this.#$input.next({ event: 'subscribe', data: { realtime_token } });
48
- }
49
- listen(ref) {
50
- if (!this.#topics.has(ref)) {
51
- const stream = new Subject();
52
- this.#topics.set(ref, { stream, listen_count: 0 });
53
- }
54
- this.#topics.get(ref).listen_count++;
55
- return this.#topics.get(ref).stream.pipe(finalize(() => {
56
- this.#topics.get(ref).listen_count--;
57
- setTimeout(() => {
58
- if (this.#topics.get(ref).listen_count == 0) {
59
- this.#$input.next({ event: 'unsubscribe', data: { ref } });
60
- }
61
- }, 2000);
62
- }));
63
- }
64
- }
@@ -1,3 +0,0 @@
1
- import { Observable } from "rxjs";
2
- import { ApiRequest } from "../RestTransporter";
3
- export declare const AddHeadersHook: (get_headers: any) => (next: any) => import("rxjs").UnaryFunction<Observable<ApiRequest>, unknown>;
@@ -1,16 +0,0 @@
1
- import { pipe, mergeMap, firstValueFrom, Observable } from "rxjs";
2
- export const AddHeadersHook = (get_headers) => {
3
- return next => pipe(mergeMap(async (r) => {
4
- const headers = typeof get_headers == 'function' ? await firstValueFrom(get_headers()) : (get_headers instanceof Observable ? await firstValueFrom(get_headers) : get_headers);
5
- return {
6
- ...r,
7
- options: {
8
- ...r.options || {},
9
- headers: {
10
- ...r.options?.headers || {},
11
- ...headers
12
- }
13
- }
14
- };
15
- }), next());
16
- };
@@ -1,2 +0,0 @@
1
- import { ApiRequest } from "../RestTransporter";
2
- export declare const Deduplicate: (ms?: number) => (next: any) => import("rxjs").UnaryFunction<import("rxjs").Observable<ApiRequest>, import("rxjs").Observable<any>>;
@@ -1,25 +0,0 @@
1
- import { pipe, mergeMap, BehaviorSubject, tap, of, filter, first } from "rxjs";
2
- const requests = new Map();
3
- export const Deduplicate = (ms = 1000) => next => {
4
- return pipe(mergeMap(async (r) => {
5
- if (r.options.method != 'GET')
6
- return of(r).pipe(next());
7
- const url = r.url.toString();
8
- const cached = requests.get(url);
9
- if (cached) {
10
- if (cached.time > Date.now() - ms) {
11
- return cached.response.pipe(filter(Boolean), first());
12
- }
13
- else {
14
- requests.delete(url);
15
- }
16
- }
17
- requests.set(url, {
18
- response: new BehaviorSubject(undefined),
19
- time: Date.now()
20
- });
21
- return of(r).pipe(next(), tap(response => {
22
- requests.get(url)?.response.next(response);
23
- }));
24
- }), mergeMap($ => $));
25
- };
package/build/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export { Deduplicate } from './hooks/Deduplicate.js';
2
- export { RestTransporter, ApiRequest } from './RestTransporter.js';
3
- export { Socket } from './Socket.js';
4
- export { AddHeadersHook } from './hooks/AddHeadersHook.js';
package/build/index.js DELETED
@@ -1,4 +0,0 @@
1
- export { Deduplicate } from './hooks/Deduplicate.js';
2
- export { RestTransporter } from './RestTransporter.js';
3
- export { Socket } from './Socket.js';
4
- export { AddHeadersHook } from './hooks/AddHeadersHook.js';
@@ -1 +0,0 @@
1
- {"root":["../src/index.ts","../src/resttransporter.ts","../src/socket.ts","../src/hooks/addheadershook.ts","../src/hooks/deduplicate.ts"],"version":"5.6.3"}