bx-rest 0.0.1 → 0.0.2

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
@@ -1,36 +1,44 @@
1
1
  {
2
- "name": "bx-rest",
3
- "version": "0.0.1",
4
- "description": "bitrix rest api",
5
- "main": "index.ts",
6
- "dependencies": {
7
- "entities": "^4.5.0",
8
- "luxon": "^3.3.0",
9
- "parse5": "^7.1.2",
10
- "just-clone": "^6.2.0",
11
- "safevalues": "^0.3.4",
12
- "just-compare": "^2.3.0",
13
- "rxjs": "^7.8.1",
14
- "zone.js": "^0.13.1",
15
- "tslib": "^2.6.1"
16
- },
17
- "devDependencies": {},
18
- "scripts": {
19
- "test": "echo \"Error: no test specified\" && exit 1"
20
- },
21
- "repository": {
22
- "type": "git",
23
- "url": "git+https://github.com/Aricatofuka/bx-rest.git"
24
- },
25
- "keywords": [
26
- "bitrxi",
27
- "rest",
28
- "api"
29
- ],
30
- "author": "Aricatofuka",
31
- "license": "ISC",
32
- "bugs": {
33
- "url": "https://github.com/Aricatofuka/bx-rest/issues"
34
- },
35
- "homepage": "https://github.com/Aricatofuka/bx-rest#readme"
2
+ "name": "bx-rest",
3
+ "version": "0.0.2",
4
+ "description": "bitrix rest api",
5
+ "types": "./index.d.ts",
6
+ "type": "module",
7
+ "dependencies": {
8
+ "@angular/common": "^16.1.8",
9
+ "@angular/core": "^16.1.8",
10
+ "@angular/material": "^16.1.7",
11
+ "@angular/router": "^16.1.8",
12
+ "@ngrx/store": "^16.2.0",
13
+ "entities": "^4.5.0",
14
+ "just-clone": "^6.2.0",
15
+ "just-compare": "^2.3.0",
16
+ "luxon": "^3.3.0",
17
+ "parse5": "^7.1.2",
18
+ "rxjs": "^7.8.1",
19
+ "safevalues": "^0.3.4",
20
+ "tslib": "^2.6.1",
21
+ "zone.js": "^0.13.1"
22
+ },
23
+ "devDependencies": {
24
+ "just-flatten-it": "^5.2.0"
25
+ },
26
+ "scripts": {
27
+ "test": "echo \"Error: no test specified\" && exit 1"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/Aricatofuka/bx-rest.git"
32
+ },
33
+ "keywords": [
34
+ "bitrxi",
35
+ "rest",
36
+ "api"
37
+ ],
38
+ "author": "Aricatofuka",
39
+ "license": "ISC",
40
+ "bugs": {
41
+ "url": "https://github.com/Aricatofuka/bx-rest/issues"
42
+ },
43
+ "homepage": "https://github.com/Aricatofuka/bx-rest#readme"
36
44
  }
package/src/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { BaseHttp } from './services/http/base/base'
2
+
3
+ export { BaseHttp }
package/src/index.ts CHANGED
@@ -0,0 +1,3 @@
1
+ import { BaseHttp } from './services/http/base/base'
2
+
3
+ export { BaseHttp }
@@ -2,16 +2,16 @@ import { Observable, throwError, take, mergeMap, forkJoin } from 'rxjs'
2
2
  import { catchError, map } from 'rxjs/operators'
3
3
  import { Injectable } from '@angular/core'
4
4
  import { HttpClient } from '@angular/common/http'
5
- import SnackBarService from '@/lib/services/snack-bar/snack-bar.service'
6
- import SessionKeyServices from '@/lib/services/api/bitrix/http/sessionKey'
5
+ import SnackBarService from '@/services/snack-bar/snack-bar.service'
6
+ import SessionKeyServices from '@/services/http/sessionKey'
7
7
  import clone from 'just-clone'
8
- import { iHttpParamSettings } from '@/lib/typification/bitrix/api/rest/settings'
9
- import BaseHttpServices from '@/lib/services/http/http'
8
+ import { iHttpParamSettings } from '@/typification/rest/settings'
9
+ import BaseHttpServices from '@/services/http/http'
10
10
  import {
11
11
  iBatchRequestAnswer, iBatchRequestParam,
12
12
  iBatchRequestParamArr,
13
13
  iBatchRequestParamHttp, keyBatch
14
- } from '@/lib/typification/bitrix/api/rest/batch/batchRequestParam'
14
+ } from '@/typification/rest/batch/batchRequestParam'
15
15
  import flatten from 'just-flatten-it'
16
16
 
17
17
  @Injectable({
@@ -0,0 +1,214 @@
1
+ import { Injectable } from '@angular/core'
2
+ import Cookies from '@/services/vanilla/сookies'
3
+ import { Store } from '@ngrx/store'
4
+ import saveApplicationAuth from '@/typification/auth/save'
5
+ import { environment as env } from '@/environments/environment'
6
+ import { filter, Observable, of, Subscription, take } from 'rxjs'
7
+ import { ActivatedRoute, ParamMap } from '@angular/router'
8
+ import { saveAccessToken, saveApplicationAuthPath } from '@/store/auth'
9
+ import { map } from 'rxjs/operators'
10
+ import { BaseServices } from '@/services/base'
11
+ import { BxApiLibServices } from '@/services/bx-api-lib'
12
+ import { LocalStorageServices as LocalStorage } from '@/lib/services/vanilla/localStorage'
13
+
14
+ type IKeyAuth = 'sessid' | 'auth' | string
15
+
16
+ @Injectable({
17
+ providedIn: 'root'
18
+ })
19
+
20
+ export default class SessionKeyServices extends BaseServices {
21
+
22
+ authHave = false
23
+ authData$: Observable<saveApplicationAuth>
24
+ authData: saveApplicationAuth | undefined
25
+ subscribe = {
26
+ authData: new Subscription()
27
+ }
28
+
29
+ constructor(
30
+ public store: Store<{ auth: saveApplicationAuth }>,
31
+ private route: ActivatedRoute,
32
+ public BxApiLib: BxApiLibServices,
33
+ ) {
34
+ super()
35
+ this.authData$ = this.store.select('auth')
36
+ this.authData$.subscribe(authData => {
37
+ if ((authData && !authData.access_token.length && !env.component) || !authData) {
38
+ // получаем токен по собственным каналом (в битриксе приложение trace:apps.trace)
39
+ window.addEventListener('message', (event: MessageEvent) => {
40
+ if (event.origin !== window.origin) { // проверяем что это не наше сообщение (с текущего приложения)
41
+ if (event.data && event.data.param) {
42
+ if (typeof event.data.param === 'string') {
43
+ event.data.param = JSON.parse(event.data.param)
44
+ }
45
+
46
+ let save: saveApplicationAuthPath = {}
47
+
48
+ if (event.data.param.access_token) {
49
+ let param = event.data.param;
50
+ save.access_token = event.data.param.access_token
51
+ save = {
52
+ access_token: (param.access_token) ? param.access_token : undefined,
53
+ client_endpoint: (param.client_endpoint) ? param.client_endpoint : undefined,
54
+ domain: (param.domain) ? param.domain : undefined,
55
+ expires: (param.expires) ? param.expires : undefined,
56
+ expires_in: (param.expires_in) ? param.expires_in : undefined,
57
+ member_id: (param.member_id) ? param.member_id : undefined,
58
+ refresh_token: (param.refresh_token) ? param.refresh_token : undefined,
59
+ scope: (param.scope) ? param.scope : undefined,
60
+ server_endpoint: (param.server_endpoint) ? param.server_endpoint : undefined,
61
+ status: (param.status) ? param.status : undefined,
62
+ user_id: (param.user_id) ? param.user_id : undefined,
63
+ type: (param.type) ? param.type : undefined,
64
+ }
65
+ }
66
+
67
+ if (Object.keys(save).length && save.access_token) {
68
+ this.store.dispatch(saveAccessToken(save))
69
+ this.subscribeAll()
70
+ }
71
+ }
72
+ }
73
+ })
74
+
75
+ this.subscribe.authData = this.route.queryParamMap
76
+ .pipe(
77
+ filter(param =>
78
+ param.has('AUTH_ID')
79
+ || param.has('access_token')
80
+ || param.has('REFRESH_ID')
81
+ || param.has('DOMAIN')
82
+ )
83
+ )
84
+ .subscribe((param: ParamMap) => {
85
+ let save: saveApplicationAuthPath = {}
86
+ if (param.has('AUTH_ID') && !authData.access_token.length) {
87
+ const get = param.get('AUTH_ID')
88
+ if (get) {
89
+ Cookies.set('auth', get) // потом убрать
90
+ save.access_token = get
91
+ }
92
+ }
93
+
94
+ if (param.has('access_token') && !authData.access_token.length) {
95
+ const get = param.get('access_token')
96
+ if (get) {
97
+ Cookies.set('auth', get) // потом убрать
98
+ save.access_token = get
99
+ }
100
+ }
101
+
102
+ if (param.has('REFRESH_ID') && !authData.refresh_token.length) {
103
+ const get = param.get('REFRESH_ID')
104
+ if (get) {
105
+ save.refresh_token = get
106
+ }
107
+ }
108
+
109
+ if (param.has('DOMAIN') && !authData.domain.length) {
110
+ const get = param.get('DOMAIN')
111
+ if (get) {
112
+ save.domain = get
113
+ }
114
+ }
115
+ if (Object.keys(save).length && save.access_token) {
116
+ this.store.dispatch(saveAccessToken(save))
117
+ this.subscribeAll()
118
+ } else {
119
+ // если битрикс не шлёт нужные мне параметры на прямую
120
+ // просим их мне отдать так как описано это в документации
121
+ let f = () => {
122
+ if (this.BxApiLib.BX24) {
123
+ const initDate = this.BxApiLib.BX24.getAuth()
124
+ this.store.dispatch(saveAccessToken(initDate))
125
+ }
126
+ }
127
+
128
+ this.BxApiLib.init(f)
129
+ }
130
+
131
+ })
132
+ } else if (env.component && this.getAuth().length) {
133
+ this.authHave = true
134
+ }
135
+
136
+ this.authData = authData
137
+ })
138
+
139
+ if (!env.production) {
140
+ this.authHave = true
141
+ }
142
+ }
143
+
144
+ subscribeAll() {
145
+ this.subscribe.authData.unsubscribe()
146
+ }
147
+
148
+ getAuth(): string {
149
+ if ((<any>window).BX && (<any>window).BX.bitrix_sessid()) {
150
+ return (<any>window).BX.bitrix_sessid()
151
+ } else if (this.getSessid().length) {
152
+ let str = this.getSessid()
153
+ return (str) ? str : ''
154
+ } else {
155
+ return Cookies.get('auth')
156
+ }
157
+ }
158
+
159
+ getKeyAuth(): IKeyAuth {
160
+ if ((<any>window).BX && (<any>window).BX.bitrix_sessid()
161
+ || this.getSessid().length) {
162
+ return 'sessid'
163
+ } else {
164
+ return 'auth'
165
+ }
166
+ }
167
+
168
+ getSessid() {
169
+ const check = new URLSearchParams(document.location.search).get('sessid')
170
+ if (check) {
171
+ LocalStorage.set('sessid', check)
172
+ return check
173
+ } else if (LocalStorage.get('sessid')) {
174
+ return LocalStorage.get('sessid')
175
+ }
176
+ return ''
177
+ }
178
+
179
+ setAuthParams<T>(params: any): boolean {
180
+ const keyAuth = this.getKeyAuth()
181
+ if (params[keyAuth]) {
182
+ return true
183
+ } else if (keyAuth) {
184
+ params[keyAuth] = this.getAuth()
185
+ return true
186
+ }
187
+ return false
188
+ }
189
+
190
+ getAuthParams(): Observable<string | undefined> {
191
+ if (env.production && !env.component) {
192
+ return this.authData$.pipe(
193
+ take(1),
194
+ map(v => (v) ? v.access_token : undefined)
195
+ )
196
+ } else {
197
+ return of(this.getAuth())
198
+ }
199
+ }
200
+
201
+ getBaseUrl(): Observable<string | undefined> {
202
+ if (env.public) {
203
+ return this.authData$.pipe(
204
+ map(v => (v && v.domain) ? this.prepareBaseAddress(v.domain, env.urls.api.bitrix) : undefined)
205
+ )
206
+ } else {
207
+ return of(env.urls.api.bitrix)
208
+ }
209
+ }
210
+
211
+ getHomeUrl(): string {
212
+ return env.urls.home
213
+ }
214
+ }
@@ -0,0 +1,15 @@
1
+ import { Injectable } from '@angular/core'
2
+ import serialize from '@/lib/functions/serializeJavascript'
3
+
4
+ @Injectable({
5
+ providedIn: 'root'
6
+ })
7
+ export default class JSONServices {
8
+ static deserialize(data: any) {
9
+ return eval('(' + data + ')')
10
+ }
11
+
12
+ static serialize(data: any ) {
13
+ return serialize(data)
14
+ }
15
+ }
@@ -0,0 +1,57 @@
1
+ import { Injectable } from '@angular/core'
2
+ import SessionKeyServices from '@/lib/services/api/bitrix/http/sessionKey'
3
+ import { map, mergeMap, of } from 'rxjs'
4
+ import SnackBarService from '@/lib/services/snack-bar/snack-bar.service'
5
+
6
+ @Injectable({
7
+ providedIn: 'root'
8
+ })
9
+ export default class IFrameVanillaJS {
10
+ parent = window.parent
11
+
12
+ constructor(
13
+ private session: SessionKeyServices,
14
+ private snackBar: SnackBarService
15
+ ) {
16
+ }
17
+
18
+ sendMessage(message: any, targetOrigin = '') {
19
+ return this.session.authData$.pipe(
20
+ mergeMap(
21
+ v => {
22
+ if(v){
23
+ if (message && !message.id){
24
+ message.id = v.access_token
25
+ }
26
+ if (this.parent && this.parent['postMessage']) {
27
+ if (targetOrigin.length) {
28
+ this.parent.postMessage(message, targetOrigin)
29
+ return of(true)
30
+ } else {
31
+ return this.session.getBaseUrl().pipe(
32
+ map(v => {
33
+ if (v) {
34
+ this.parent.postMessage(message, v)
35
+ return true
36
+ }
37
+ this.snackBar.error('Не удалось получить адрес родителя для фрейма')
38
+ return false
39
+ })
40
+ )
41
+ }
42
+ }
43
+ this.snackBar.error('Не удалось получить адрес родителя для фрейма')
44
+ return of(false)
45
+ }
46
+ this.snackBar.error('Не удалось получить авторизационные данные')
47
+ return of(false)
48
+ }
49
+ )
50
+ )
51
+
52
+ }
53
+
54
+ getMassage(func: Function){
55
+ window.addEventListener('message', func())
56
+ }
57
+ }
@@ -0,0 +1,42 @@
1
+ import { Injectable } from '@angular/core'
2
+ import JSON from '@/lib/services/vanilla/JSON'
3
+
4
+ @Injectable({
5
+ providedIn: 'root'
6
+ })
7
+ export class LocalStorageServices {
8
+
9
+ static get(name: string): any {
10
+ return localStorage.getItem(name)
11
+ }
12
+
13
+ static getObj<T>(name: string): T | null {
14
+ return JSON.deserialize(localStorage.getItem(name))
15
+ }
16
+
17
+ static set(name: string, value: string): void {
18
+ localStorage.setItem(name, value)
19
+ }
20
+
21
+ static setObj(name: string, value: any): void {
22
+ let get = this.get(name)
23
+ if(get && typeof get === 'object'){
24
+ localStorage.setItem(
25
+ name,
26
+ JSON.serialize(
27
+ Object.assign(
28
+ get,
29
+ value
30
+ )
31
+ )
32
+ )
33
+ } else {
34
+ localStorage.setItem(name, JSON.serialize(value))
35
+ }
36
+ }
37
+
38
+ static del(name: string): void {
39
+ localStorage.removeItem(name)
40
+ }
41
+
42
+ }
@@ -0,0 +1,43 @@
1
+ import { Injectable } from '@angular/core'
2
+ import JSON from '@/lib/services/vanilla/JSON'
3
+
4
+ @Injectable({
5
+ providedIn: 'root'
6
+ })
7
+ export default class CookiesServices {
8
+
9
+ static get(name: string): string {
10
+ const results = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
11
+ if (results)
12
+ return results[2]
13
+ else
14
+ return ''
15
+ }
16
+
17
+ static set(name: string, value: string, age: number = 0) {
18
+ let string = name + '=' + value + ';'
19
+ if(age) {
20
+ string += ' max-age=' + age
21
+ }
22
+ string += '; SameSite=None; Secure'
23
+ document.cookie = string
24
+ }
25
+
26
+ static setObj(name: string, value: any, age: number = 0) {
27
+ let string = name + '=' + JSON.serialize(value) + ';'
28
+ if(age) {
29
+ string += ' max-age=' + age
30
+ }
31
+ string += '; SameSite=None; Secure'
32
+ document.cookie = string
33
+ }
34
+
35
+ static getObj<T>(name: string): T | false {
36
+ const results = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
37
+ if (results) {
38
+ return JSON.deserialize(results[2])
39
+ }
40
+
41
+ return false
42
+ }
43
+ }
@@ -0,0 +1,46 @@
1
+ import { Action, createReducer, on, props } from '@ngrx/store'
2
+ import { createAction } from '@ngrx/store'
3
+ import saveApplicationAuth from '@/typification/auth/save'
4
+ import clone from 'just-clone'
5
+ export interface saveApplicationAuthPath {
6
+ access_token?: string, // основной авторизационный токен, требуемый для доступа к REST API
7
+ client_endpoint?: string, // адрес REST-интерфейса портала
8
+ domain?: string,
9
+ expires?: number,
10
+ expires_in?: number,
11
+ member_id?: string,
12
+ refresh_token?: string, // дополнительный авторизационный токен, служащий для продления сохраненной авторизации
13
+ scope?: string,
14
+ server_endpoint?: string, // адрес REST-интерфейса сервера
15
+ status?: string, // статус приложения на портале
16
+ user_id?: number
17
+ type?: string
18
+ }
19
+ export const save = createAction('[Auth Component] Save', props<saveApplicationAuth | saveApplicationAuthPath>())
20
+ export const saveAccessToken = createAction('[Auth Component] SaveAccessToken', props<saveApplicationAuthPath>())
21
+
22
+ export const initialState: saveApplicationAuth = {
23
+ access_token: '',
24
+ client_endpoint: '',
25
+ domain: '',
26
+ expires: 0,
27
+ expires_in: 0,
28
+ member_id: '',
29
+ refresh_token: '',
30
+ scope: '',
31
+ server_endpoint: '',
32
+ status: '',
33
+ user_id: 0
34
+ }
35
+
36
+ const _authReducer = createReducer(
37
+ initialState,
38
+ on(saveAccessToken, (s, data) => {
39
+ let copy = clone(s)
40
+ return Object.assign(copy, data)
41
+ }),
42
+ );
43
+
44
+ export function authReducer(state = initialState, action: Action) {
45
+ return _authReducer(state, action);
46
+ }
@@ -0,0 +1,6 @@
1
+ export default interface OAuthBXParam {
2
+ code: string,
3
+ domain: string,
4
+ member_id: string,
5
+ scope: string
6
+ }
@@ -0,0 +1,8 @@
1
+ export default interface ApplicationAuth {
2
+ code?: string,
3
+ state?: string,
4
+ domain?: string,
5
+ member_id?: string,
6
+ scope?: string,
7
+ server_domain?: string
8
+ }
@@ -0,0 +1,14 @@
1
+ export default interface saveApplicationAuth {
2
+ access_token: string, // основной авторизационный токен, требуемый для доступа к REST API
3
+ client_endpoint: string, // адрес REST-интерфейса портала
4
+ domain: string,
5
+ expires: number,
6
+ expires_in: number,
7
+ member_id: string,
8
+ refresh_token: string, // дополнительный авторизационный токен, служащий для продления сохраненной авторизации
9
+ scope: string,
10
+ server_endpoint: string, // адрес REST-интерфейса сервера
11
+ status: string, // статус приложения на портале
12
+ user_id: number,
13
+ state?: any
14
+ }
@@ -0,0 +1,4 @@
1
+ export default interface UrlData {
2
+ REFRESH_ID?: string,
3
+ AUTH_ID?: string
4
+ }
@@ -0,0 +1,18 @@
1
+ import { Injectable } from '@angular/core'
2
+ import { iRestLib } from '@/typification/rest/lib'
3
+
4
+ @Injectable({
5
+ providedIn: 'root'
6
+ })
7
+ export class ApiLibServices {
8
+ BX24: iRestLib | false = false
9
+
10
+ constructor() {
11
+ // @ts-ignore
12
+ this.BX24 = (window.BX24) ? window.BX24 : false
13
+ }
14
+
15
+ init(callBack: Function) {
16
+ return (this.BX24) ? this.BX24.init(callBack) : false
17
+ }
18
+ }
@@ -0,0 +1,14 @@
1
+ import iHttpAnswerBX from '@/lib/typification/bitrix/api/rest/base/httpAnswerBX'
2
+
3
+ export type keyBatch = string | number
4
+
5
+ export interface iBatchRequestParam <T>{
6
+ name: string,
7
+ param: T
8
+ }
9
+
10
+ export type iBatchRequestParamHttp = {[key:keyBatch]: string}
11
+
12
+ export type iBatchRequestParamArr<T> = {[key:keyBatch]: iBatchRequestParam <T>}
13
+
14
+ export interface iBatchRequestAnswer<T> extends iHttpAnswerBX<iHttpAnswerBX<{[key:keyBatch]: T}>>{}
@@ -0,0 +1,19 @@
1
+ export interface iRestLib {
2
+ init: Function
3
+ getAuth: () => iRestLibGetAuth
4
+ placement: {
5
+ info: () => {
6
+ options: any,
7
+ placement: string
8
+ }
9
+ }
10
+ fitWindow: (func?: () => void) => void
11
+ }
12
+
13
+ export interface iRestLibGetAuth {
14
+ access_token: string,
15
+ domain: string,
16
+ expires_in: number
17
+ member_id: string
18
+ refresh_token: string
19
+ }
package/tsconfig.json CHANGED
@@ -1,5 +1,7 @@
1
1
  {
2
2
  "compilerOptions": {
3
+ "target": "es5",
4
+ "lib": ["esnext", "dom"],
3
5
  "paths": {
4
6
  "@/*": [
5
7
  "src/*"