@lumi.new/sdk 0.0.1
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/README.md +189 -0
- package/dist/index.d.mts +93 -0
- package/dist/index.d.ts +93 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +34 -0
package/README.md
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# @lumi.new/sdk
|
|
2
|
+
|
|
3
|
+
SDK for Lumi.new
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
# pnpm
|
|
9
|
+
pnpm add @lumi.new/sdk
|
|
10
|
+
|
|
11
|
+
# npm
|
|
12
|
+
npm install @lumi.new/sdk
|
|
13
|
+
|
|
14
|
+
# yarn
|
|
15
|
+
yarn add @lumi.new/sdk
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Getting Started
|
|
19
|
+
|
|
20
|
+
First, initialize the Lumi client. You can get your `projectId` from your Lumi project settings.
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { createClient } from '@lumi.new/sdk'
|
|
24
|
+
|
|
25
|
+
const lumi = createClient({
|
|
26
|
+
projectId: 'YOUR_PROJECT_ID',
|
|
27
|
+
apiBaseUrl: 'https://your-api.lumi.new', // Your Lumi API endpoint
|
|
28
|
+
authOrigin: 'https://your-auth.lumi.new', // Your Lumi Auth origin
|
|
29
|
+
})
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Authentication
|
|
33
|
+
|
|
34
|
+
The Lumi SDK provides methods to handle user authentication.
|
|
35
|
+
|
|
36
|
+
### Sign In
|
|
37
|
+
|
|
38
|
+
To sign in a user, call the `signIn` method. This will open a popup window for the user to authenticate. Upon successful authentication, the access token will be automatically stored.
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
import { LumiClient } from '@lumi.new/sdk'
|
|
42
|
+
|
|
43
|
+
async function handleSignIn(lumi: LumiClient) {
|
|
44
|
+
try {
|
|
45
|
+
const { user, accessToken } = await lumi.auth.signIn()
|
|
46
|
+
console.log('Signed in as:', user)
|
|
47
|
+
console.log('Access Token:', accessToken)
|
|
48
|
+
} catch (error) {
|
|
49
|
+
console.error('Authentication failed:', error)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Sign Out
|
|
55
|
+
|
|
56
|
+
To sign out a user, simply call the `signOut` method. This will clear the stored access token.
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
function handleSignOut(lumi: LumiClient) {
|
|
60
|
+
lumi.auth.signOut()
|
|
61
|
+
console.log('User signed out.')
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Get Current User
|
|
66
|
+
|
|
67
|
+
Fetch the profile of the currently authenticated user. This method requires a valid access token.
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
async function fetchUser(lumi: LumiClient) {
|
|
71
|
+
if (lumi.auth.isAuthenticated) {
|
|
72
|
+
try {
|
|
73
|
+
const user = await lumi.auth.getUser()
|
|
74
|
+
console.log('Current user:', user)
|
|
75
|
+
} catch (error) {
|
|
76
|
+
console.error('Failed to fetch user:', error)
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
console.log('User is not authenticated.')
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Manage Access Token
|
|
85
|
+
|
|
86
|
+
You can directly access the access token.
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
// Get the access token
|
|
90
|
+
const token = lumi.auth.accessToken
|
|
91
|
+
|
|
92
|
+
// Check if the user is authenticated
|
|
93
|
+
const isAuthenticated = lumi.auth.isAuthenticated
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Entities
|
|
97
|
+
|
|
98
|
+
The `entities` client allows you to interact with your project's data collections. You can access a specific entity by its name.
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
const posts = lumi.entities.posts
|
|
102
|
+
const users = lumi.entities.users
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### List Records
|
|
106
|
+
|
|
107
|
+
Retrieve a list of records from an entity. You can use `filter`, `sort`, `limit`, and `skip` to control the query.
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
async function getPosts() {
|
|
111
|
+
const posts = await lumi.entities.posts.list({
|
|
112
|
+
filter: { published: true },
|
|
113
|
+
sort: '-createdAt', // Sort by creation date in descending order
|
|
114
|
+
limit: 10,
|
|
115
|
+
skip: 0,
|
|
116
|
+
})
|
|
117
|
+
console.log('Posts:', posts)
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Get a Single Record
|
|
122
|
+
|
|
123
|
+
Retrieve a single record by its ID.
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
async function getPost(id: string) {
|
|
127
|
+
const post = await lumi.entities.posts.get(id)
|
|
128
|
+
console.log('Post:', post)
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Create a Record
|
|
133
|
+
|
|
134
|
+
Create a new record in an entity.
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
async function createPost(title: string, content: string) {
|
|
138
|
+
const newPost = await lumi.entities.posts.create({
|
|
139
|
+
title,
|
|
140
|
+
content,
|
|
141
|
+
published: false,
|
|
142
|
+
})
|
|
143
|
+
console.log('Created post:', newPost)
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Create Multiple Records
|
|
148
|
+
|
|
149
|
+
Create multiple records in a single request.
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
async function createMultiplePosts(newPostsData) {
|
|
153
|
+
const newPosts = await lumi.entities.posts.createMany(newPostsData)
|
|
154
|
+
console.log('Created posts:', newPosts)
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Update a Record
|
|
159
|
+
|
|
160
|
+
Update an existing record by its ID.
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
async function updatePost(id: string, updates: Record<string, any>) {
|
|
164
|
+
const updatedPost = await lumi.entities.posts.update(id, updates)
|
|
165
|
+
console.log('Updated post:', updatedPost)
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Delete a Record
|
|
170
|
+
|
|
171
|
+
Delete a record by its ID.
|
|
172
|
+
|
|
173
|
+
```typescript
|
|
174
|
+
async function deletePost(id: string) {
|
|
175
|
+
await lumi.entities.posts.delete(id)
|
|
176
|
+
console.log('Post deleted.')
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Delete Multiple Records
|
|
181
|
+
|
|
182
|
+
Delete multiple records by their IDs in a single request.
|
|
183
|
+
|
|
184
|
+
```typescript
|
|
185
|
+
async function deleteMultiplePosts(ids: string[]) {
|
|
186
|
+
await lumi.entities.posts.deleteMany(ids)
|
|
187
|
+
console.log('Posts deleted.')
|
|
188
|
+
}
|
|
189
|
+
```
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
interface Entity extends Record<string, any> {
|
|
2
|
+
id: string;
|
|
3
|
+
}
|
|
4
|
+
declare class EntityClient {
|
|
5
|
+
#private;
|
|
6
|
+
readonly entityName: string;
|
|
7
|
+
constructor(lumi: LumiClient, entityName: string);
|
|
8
|
+
/** 查询文档列表 */
|
|
9
|
+
list({ filter, sort, limit, skip }: {
|
|
10
|
+
filter?: any;
|
|
11
|
+
sort?: string;
|
|
12
|
+
limit?: number;
|
|
13
|
+
skip?: number;
|
|
14
|
+
}): Promise<Entity[]>;
|
|
15
|
+
/** 获取单个文档 */
|
|
16
|
+
get(id: string): Promise<Entity | null>;
|
|
17
|
+
/** 创建文档 */
|
|
18
|
+
create(data: Record<string, any>): Promise<Entity>;
|
|
19
|
+
/** 批量创建文档 */
|
|
20
|
+
createMany(data: Record<string, any>[]): Promise<Entity[]>;
|
|
21
|
+
/** 更新文档 */
|
|
22
|
+
update(id: string, data: Record<string, any>): Promise<Entity>;
|
|
23
|
+
/** 删除文档 */
|
|
24
|
+
delete(id: string): Promise<void>;
|
|
25
|
+
/** 批量删除文档 */
|
|
26
|
+
deleteMany(ids: string[]): Promise<void>;
|
|
27
|
+
private uri;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
declare class EntitiesClient {
|
|
31
|
+
#private;
|
|
32
|
+
[key: string]: EntityClient;
|
|
33
|
+
constructor(lumi: LumiClient);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface LumiClientConfig {
|
|
37
|
+
projectId: string;
|
|
38
|
+
apiBaseUrl: string;
|
|
39
|
+
authOrigin: string;
|
|
40
|
+
}
|
|
41
|
+
declare class LumiClient {
|
|
42
|
+
config: LumiClientConfig;
|
|
43
|
+
auth: LumiAuthClient;
|
|
44
|
+
entities: EntitiesClient;
|
|
45
|
+
constructor(config: LumiClientConfig);
|
|
46
|
+
}
|
|
47
|
+
declare function createClient(config: LumiClientConfig): LumiClient;
|
|
48
|
+
|
|
49
|
+
declare enum MessageType {
|
|
50
|
+
READY = "lumi-ready",
|
|
51
|
+
INIT = "lumi-init",
|
|
52
|
+
SIGN_IN = "lumi-sign-in"
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface User {
|
|
56
|
+
userId: string;
|
|
57
|
+
email: string;
|
|
58
|
+
}
|
|
59
|
+
interface MessageSignInData {
|
|
60
|
+
projectId: string;
|
|
61
|
+
accessToken: string;
|
|
62
|
+
user: User;
|
|
63
|
+
}
|
|
64
|
+
type MessageDataReceive = {
|
|
65
|
+
type: MessageType.READY;
|
|
66
|
+
} | {
|
|
67
|
+
type: MessageType.SIGN_IN;
|
|
68
|
+
data: MessageSignInData;
|
|
69
|
+
};
|
|
70
|
+
interface MessageInitData {
|
|
71
|
+
projectId: string;
|
|
72
|
+
icon: string | null;
|
|
73
|
+
title: string | null;
|
|
74
|
+
}
|
|
75
|
+
interface MessageDataSend {
|
|
76
|
+
type: MessageType.INIT;
|
|
77
|
+
data: MessageInitData;
|
|
78
|
+
}
|
|
79
|
+
declare class LumiAuthClient {
|
|
80
|
+
#private;
|
|
81
|
+
constructor(lumi: LumiClient);
|
|
82
|
+
get accessToken(): string | null;
|
|
83
|
+
set accessToken(accessToken: string | null);
|
|
84
|
+
get isAuthenticated(): boolean;
|
|
85
|
+
/** 登录 */
|
|
86
|
+
signIn(): Promise<MessageSignInData>;
|
|
87
|
+
/** 退出登录 */
|
|
88
|
+
signOut(): void;
|
|
89
|
+
/** 获取当前用户 */
|
|
90
|
+
getUser(): Promise<User>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export { EntitiesClient, type Entity, EntityClient, LumiAuthClient, LumiClient, type LumiClientConfig, type MessageDataReceive, type MessageDataSend, type MessageInitData, type MessageSignInData, type User, createClient };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
interface Entity extends Record<string, any> {
|
|
2
|
+
id: string;
|
|
3
|
+
}
|
|
4
|
+
declare class EntityClient {
|
|
5
|
+
#private;
|
|
6
|
+
readonly entityName: string;
|
|
7
|
+
constructor(lumi: LumiClient, entityName: string);
|
|
8
|
+
/** 查询文档列表 */
|
|
9
|
+
list({ filter, sort, limit, skip }: {
|
|
10
|
+
filter?: any;
|
|
11
|
+
sort?: string;
|
|
12
|
+
limit?: number;
|
|
13
|
+
skip?: number;
|
|
14
|
+
}): Promise<Entity[]>;
|
|
15
|
+
/** 获取单个文档 */
|
|
16
|
+
get(id: string): Promise<Entity | null>;
|
|
17
|
+
/** 创建文档 */
|
|
18
|
+
create(data: Record<string, any>): Promise<Entity>;
|
|
19
|
+
/** 批量创建文档 */
|
|
20
|
+
createMany(data: Record<string, any>[]): Promise<Entity[]>;
|
|
21
|
+
/** 更新文档 */
|
|
22
|
+
update(id: string, data: Record<string, any>): Promise<Entity>;
|
|
23
|
+
/** 删除文档 */
|
|
24
|
+
delete(id: string): Promise<void>;
|
|
25
|
+
/** 批量删除文档 */
|
|
26
|
+
deleteMany(ids: string[]): Promise<void>;
|
|
27
|
+
private uri;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
declare class EntitiesClient {
|
|
31
|
+
#private;
|
|
32
|
+
[key: string]: EntityClient;
|
|
33
|
+
constructor(lumi: LumiClient);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface LumiClientConfig {
|
|
37
|
+
projectId: string;
|
|
38
|
+
apiBaseUrl: string;
|
|
39
|
+
authOrigin: string;
|
|
40
|
+
}
|
|
41
|
+
declare class LumiClient {
|
|
42
|
+
config: LumiClientConfig;
|
|
43
|
+
auth: LumiAuthClient;
|
|
44
|
+
entities: EntitiesClient;
|
|
45
|
+
constructor(config: LumiClientConfig);
|
|
46
|
+
}
|
|
47
|
+
declare function createClient(config: LumiClientConfig): LumiClient;
|
|
48
|
+
|
|
49
|
+
declare enum MessageType {
|
|
50
|
+
READY = "lumi-ready",
|
|
51
|
+
INIT = "lumi-init",
|
|
52
|
+
SIGN_IN = "lumi-sign-in"
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface User {
|
|
56
|
+
userId: string;
|
|
57
|
+
email: string;
|
|
58
|
+
}
|
|
59
|
+
interface MessageSignInData {
|
|
60
|
+
projectId: string;
|
|
61
|
+
accessToken: string;
|
|
62
|
+
user: User;
|
|
63
|
+
}
|
|
64
|
+
type MessageDataReceive = {
|
|
65
|
+
type: MessageType.READY;
|
|
66
|
+
} | {
|
|
67
|
+
type: MessageType.SIGN_IN;
|
|
68
|
+
data: MessageSignInData;
|
|
69
|
+
};
|
|
70
|
+
interface MessageInitData {
|
|
71
|
+
projectId: string;
|
|
72
|
+
icon: string | null;
|
|
73
|
+
title: string | null;
|
|
74
|
+
}
|
|
75
|
+
interface MessageDataSend {
|
|
76
|
+
type: MessageType.INIT;
|
|
77
|
+
data: MessageInitData;
|
|
78
|
+
}
|
|
79
|
+
declare class LumiAuthClient {
|
|
80
|
+
#private;
|
|
81
|
+
constructor(lumi: LumiClient);
|
|
82
|
+
get accessToken(): string | null;
|
|
83
|
+
set accessToken(accessToken: string | null);
|
|
84
|
+
get isAuthenticated(): boolean;
|
|
85
|
+
/** 登录 */
|
|
86
|
+
signIn(): Promise<MessageSignInData>;
|
|
87
|
+
/** 退出登录 */
|
|
88
|
+
signOut(): void;
|
|
89
|
+
/** 获取当前用户 */
|
|
90
|
+
getUser(): Promise<User>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export { EntitiesClient, type Entity, EntityClient, LumiAuthClient, LumiClient, type LumiClientConfig, type MessageDataReceive, type MessageDataSend, type MessageInitData, type MessageSignInData, type User, createClient };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var I=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames,S=Object.getOwnPropertySymbols;var M=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable;var R=i=>{throw TypeError(i)};var A=(i,e,t)=>e in i?I(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,L=(i,e)=>{for(var t in e||(e={}))M.call(e,t)&&A(i,t,e[t]);if(S)for(var t of S(e))j.call(e,t)&&A(i,t,e[t]);return i};var _=(i,e)=>{for(var t in e)I(i,t,{get:e[t],enumerable:!0})},q=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $(e))!M.call(i,n)&&n!==t&&I(i,n,{get:()=>e[n],enumerable:!(r=U(e,n))||r.enumerable});return i};var B=i=>q(I({},"__esModule",{value:!0}),i);var k=(i,e,t)=>e.has(i)||R("Cannot "+t);var s=(i,e,t)=>(k(i,e,"read from private field"),t?t.call(i):e.get(i)),h=(i,e,t)=>e.has(i)?R("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),d=(i,e,t,r)=>(k(i,e,"write to private field"),r?r.call(i,t):e.set(i,t),t);var l=(i,e,t)=>new Promise((r,n)=>{var m=c=>{try{f(t.next(c))}catch(y){n(y)}},a=c=>{try{f(t.throw(c))}catch(y){n(y)}},f=c=>c.done?r(c.value):Promise.resolve(c.value).then(m,a);f((t=t.apply(i,e)).next())});var G={};_(G,{EntitiesClient:()=>b,EntityClient:()=>E,LumiAuthClient:()=>w,LumiClient:()=>C,createClient:()=>K});module.exports=B(G);var P=require("ofetch");function u(i,e,t={}){return i.auth.accessToken&&(t.headers=L({Authorization:`Bearer ${i.auth.accessToken}`},t.headers)),(0,P.ofetch)(e,L({baseURL:i.config.apiBaseUrl},t))}function v(){var i,e;return(e=(i=document.querySelector('link[rel="icon"]'))==null?void 0:i.href)!=null?e:null}function D(){var i;return(i=document.title)!=null?i:null}var p,w=class{constructor(e){h(this,p);d(this,p,e)}get accessToken(){return localStorage.getItem("lumi-access-token")}set accessToken(e){e?localStorage.setItem("lumi-access-token",e):localStorage.removeItem("lumi-access-token")}get isAuthenticated(){return!!this.accessToken}signIn(){let r=(window.screen.width-800)/2,n=(window.screen.height-600)/2,m=window.open(s(this,p).config.apiBaseUrl,"_blank",`width=800,height=600,left=${r},top=${n}`),a;return new Promise((f,c)=>{if(!m)return c(new Error("Open auth window failed"));let y=setInterval(()=>{m.closed&&c(new Error("Auth window closed"))},1e3),x=({data:g,origin:O,source:N})=>{if(!(O!==s(this,p).config.authOrigin||N!==m))switch(g==null?void 0:g.type){case"lumi-ready":{m.postMessage({type:"lumi-init",data:{projectId:s(this,p).config.projectId,icon:v(),title:D()}},s(this,p).config.authOrigin);break}case"lumi-sign-in":{if(g.data.projectId!==s(this,p).config.projectId)break;m.close(),this.accessToken=g.data.accessToken,f(g.data);break}}};window.addEventListener("message",x),a=()=>{clearInterval(y),window.removeEventListener("message",x)}}).finally(()=>a==null?void 0:a())}signOut(){this.accessToken=null}getUser(){return l(this,null,function*(){let e=yield u(s(this,p),"/lm/user/info");if(e.code!==200)throw new Error(e.message);return e.data})}};p=new WeakMap;var o,E=class{constructor(e,t){h(this,o);d(this,o,e),this.entityName=t}list(m){return l(this,arguments,function*({filter:e,sort:t,limit:r,skip:n}){let a=yield u(s(this,o),this.uri("/find"),{method:"POST",body:{filter:e,sort:t,limit:r,skip:n}});if(a.code!==200)throw new Error(a.message);return a.data})}get(e){return l(this,null,function*(){let t=yield u(s(this,o),this.uri(`/${e}`),{method:"GET"});if(t.code!==200)throw new Error(t.message);return t.data})}create(e){return l(this,null,function*(){let t=yield u(s(this,o),this.uri(),{method:"POST",body:e});if(t.code!==200)throw new Error(t.message);return t.data})}createMany(e){return l(this,null,function*(){let t=yield u(s(this,o),this.uri("/batch"),{method:"POST",body:e});if(t.code!==200)throw new Error(t.message);return t.data})}update(e,t){return l(this,null,function*(){let r=yield u(s(this,o),this.uri(),{method:"PUT",body:{filter:{_id:e},update:t}});if(r.code!==200)throw new Error(r.message);return r.data})}delete(e){return l(this,null,function*(){let t=yield u(s(this,o),this.uri(`/${e}`),{method:"DELETE"});if(t.code!==200)throw new Error(t.message)})}deleteMany(e){return l(this,null,function*(){let t=yield u(s(this,o),this.uri("/batch-by-ids"),{method:"DELETE",params:{ids:e}});if(t.code!==200)throw new Error(t.message)})}uri(e=""){return`/lm/${s(this,o).config.projectId}/${this.entityName}/documents${e}`}};o=new WeakMap;var T,b=class{constructor(e){h(this,T);return d(this,T,e),new Proxy(this,{get(t,r){return r in t||(t[r]=new E(s(t,T),r)),t[r]}})}};T=new WeakMap;var C=class{constructor(e){this.config=e,this.auth=new w(this),this.entities=new b(this)}};function K(i){return new C(i)}0&&(module.exports={EntitiesClient,EntityClient,LumiAuthClient,LumiClient,createClient});
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/lib/request.ts","../src/utils/common.ts","../src/core/auth-client.ts","../src/core/entity-client.ts","../src/core/entities-client.ts","../src/core/lumi-client.ts"],"sourcesContent":["export * from './core/auth-client'\nexport * from './core/entities-client'\nexport * from './core/entity-client'\nexport * from './core/lumi-client'\n","import type { FetchOptions } from 'ofetch'\nimport type { LumiClient } from '@/core/lumi-client'\nimport { ofetch } from 'ofetch'\n\nexport interface ApiResponse<T> {\n code: number\n message: string\n data: T\n}\n\nexport function request<T>(lumi: LumiClient, uri: string, options: FetchOptions<'json'> = {}): Promise<T> {\n if (lumi.auth.accessToken) {\n options.headers = {\n Authorization: `Bearer ${lumi.auth.accessToken}`,\n ...options.headers,\n }\n }\n\n return ofetch<T>(uri, {\n baseURL: lumi.config.apiBaseUrl,\n ...options,\n })\n}\n","export function getIcon(): string | null {\n return document.querySelector<HTMLLinkElement>('link[rel=\"icon\"]')?.href ?? null\n}\n\nexport function getTitle(): string | null {\n return document.title ?? null\n}\n","import type { LumiClient } from '@/core/lumi-client'\nimport type { ApiResponse } from '@/lib/request'\nimport { MessageType, StorageKey } from '@/constants'\nimport { request } from '@/lib/request'\nimport { getIcon, getTitle } from '@/utils/common'\n\nexport interface User {\n userId: string\n email: string\n}\n\nexport interface MessageSignInData {\n projectId: string\n accessToken: string\n user: User\n}\n\nexport type MessageDataReceive = {\n type: MessageType.READY\n} | {\n type: MessageType.SIGN_IN\n data: MessageSignInData\n}\n\nexport interface MessageInitData {\n projectId: string\n icon: string | null\n title: string | null\n}\n\nexport interface MessageDataSend {\n type: MessageType.INIT\n data: MessageInitData\n}\n\nexport class LumiAuthClient {\n readonly #lumi: LumiClient\n\n constructor(lumi: LumiClient) {\n this.#lumi = lumi\n }\n\n public get accessToken(): string | null {\n return localStorage.getItem(StorageKey.ACCESS_TOKEN)\n }\n\n public set accessToken(accessToken: string | null) {\n if (accessToken)\n localStorage.setItem(StorageKey.ACCESS_TOKEN, accessToken)\n else\n localStorage.removeItem(StorageKey.ACCESS_TOKEN)\n }\n\n public get isAuthenticated(): boolean {\n return !!this.accessToken\n }\n\n /** 登录 */\n public signIn(): Promise<MessageSignInData> {\n const width = 800\n const height = 600\n const left = (window.screen.width - width) / 2\n const top = (window.screen.height - height) / 2\n const popup = window.open(this.#lumi.config.apiBaseUrl, '_blank', `width=${width},height=${height},left=${left},top=${top}`)\n\n let cleanup: () => void\n return new Promise<MessageSignInData>((resolve, reject) => {\n if (!popup)\n return reject(new Error('Open auth window failed'))\n\n const timer = setInterval(() => {\n if (popup.closed)\n reject(new Error('Auth window closed'))\n }, 1000)\n\n const handleMessage = ({ data, origin, source }: MessageEvent<MessageDataReceive | null>): void => {\n if (origin !== this.#lumi.config.authOrigin || source !== popup)\n return\n\n switch (data?.type) {\n case MessageType.READY: {\n popup.postMessage({\n type: MessageType.INIT,\n data: {\n projectId: this.#lumi.config.projectId,\n icon: getIcon(),\n title: getTitle(),\n },\n } satisfies MessageDataSend, this.#lumi.config.authOrigin)\n break\n }\n case MessageType.SIGN_IN: {\n if (data.data.projectId !== this.#lumi.config.projectId)\n break\n popup.close()\n this.accessToken = data.data.accessToken\n resolve(data.data)\n break\n }\n }\n }\n window.addEventListener('message', handleMessage)\n\n cleanup = () => {\n clearInterval(timer)\n window.removeEventListener('message', handleMessage)\n }\n }).finally(() => cleanup?.())\n }\n\n /** 退出登录 */\n public signOut(): void {\n this.accessToken = null\n }\n\n /** 获取当前用户 */\n public async getUser(): Promise<User> {\n const res = await request<ApiResponse<User>>(this.#lumi, '/lm/user/info')\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n}\n","import type { LumiClient } from '@/core/lumi-client'\nimport type { ApiResponse } from '@/lib/request'\nimport { request } from '@/lib/request'\n\nexport interface Entity extends Record<string, any> {\n id: string\n}\n\nexport class EntityClient {\n readonly #lumi: LumiClient\n public readonly entityName: string\n\n constructor(lumi: LumiClient, entityName: string) {\n this.#lumi = lumi\n this.entityName = entityName\n }\n\n /** 查询文档列表 */\n public async list({ filter, sort, limit, skip }: {\n filter?: any\n sort?: string\n limit?: number\n skip?: number\n }): Promise<Entity[]> {\n const res = await request<ApiResponse<Entity[]>>(this.#lumi, this.uri('/find'), {\n method: 'POST',\n body: { filter, sort, limit, skip },\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 获取单个文档 */\n public async get(id: string): Promise<Entity | null> {\n const res = await request<ApiResponse<Entity>>(this.#lumi, this.uri(`/${id}`), {\n method: 'GET',\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 创建文档 */\n public async create(data: Record<string, any>): Promise<Entity> {\n const res = await request<ApiResponse<Entity>>(this.#lumi, this.uri(), {\n method: 'POST',\n body: data,\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 批量创建文档 */\n public async createMany(data: Record<string, any>[]): Promise<Entity[]> {\n const res = await request<ApiResponse<Entity[]>>(this.#lumi, this.uri('/batch'), {\n method: 'POST',\n body: data,\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 更新文档 */\n public async update(id: string, data: Record<string, any>): Promise<Entity> {\n const res = await request<ApiResponse<Entity>>(this.#lumi, this.uri(), {\n method: 'PUT',\n body: { filter: { _id: id }, update: data },\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 删除文档 */\n public async delete(id: string): Promise<void> {\n const res = await request<ApiResponse<null>>(this.#lumi, this.uri(`/${id}`), {\n method: 'DELETE',\n })\n if (res.code !== 200)\n throw new Error(res.message)\n }\n\n /** 批量删除文档 */\n public async deleteMany(ids: string[]): Promise<void> {\n const res = await request<ApiResponse<null>>(this.#lumi, this.uri('/batch-by-ids'), {\n method: 'DELETE',\n params: { ids },\n })\n if (res.code !== 200)\n throw new Error(res.message)\n }\n\n private uri(suffix = ''): string {\n return `/lm/${this.#lumi.config.projectId}/${this.entityName}/documents${suffix}`\n }\n}\n","import type { LumiClient } from '@/core/lumi-client'\nimport { EntityClient } from '@/core/entity-client'\n\nexport class EntitiesClient {\n readonly #lumi: LumiClient\n [key: string]: EntityClient\n\n constructor(lumi: LumiClient) {\n this.#lumi = lumi\n return new Proxy(this, {\n get(target: EntitiesClient, p: string) {\n if (!(p in target))\n target[p] = new EntityClient(target.#lumi, p)\n return target[p]\n },\n }) as this\n }\n}\n","import { LumiAuthClient } from '@/core/auth-client'\nimport { EntitiesClient } from '@/core/entities-client'\n\nexport interface LumiClientConfig {\n projectId: string\n apiBaseUrl: string\n authOrigin: string\n}\n\nexport class LumiClient {\n public config: LumiClientConfig\n\n public auth: LumiAuthClient\n public entities: EntitiesClient\n\n constructor(config: LumiClientConfig) {\n this.config = config\n this.auth = new LumiAuthClient(this)\n this.entities = new EntitiesClient(this)\n }\n}\n\nexport function createClient(config: LumiClientConfig): LumiClient {\n return new LumiClient(config)\n}\n"],"mappings":"otCAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,iBAAAC,EAAA,mBAAAC,EAAA,eAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAP,GCEA,IAAAQ,EAAuB,kBAQhB,SAASC,EAAWC,EAAkBC,EAAaC,EAAgC,CAAC,EAAe,CACxG,OAAIF,EAAK,KAAK,cACZE,EAAQ,QAAUC,EAAA,CAChB,cAAe,UAAUH,EAAK,KAAK,WAAW,IAC3CE,EAAQ,aAIR,UAAUD,EAAKE,EAAA,CACpB,QAASH,EAAK,OAAO,YAClBE,EACJ,CACH,CCtBO,SAASE,GAAyB,CAAzC,IAAAC,EAAAC,EACE,OAAOA,GAAAD,EAAA,SAAS,cAA+B,kBAAkB,IAA1D,YAAAA,EAA6D,OAA7D,KAAAC,EAAqE,IAC9E,CAEO,SAASC,GAA0B,CAJ1C,IAAAF,EAKE,OAAOA,EAAA,SAAS,QAAT,KAAAA,EAAkB,IAC3B,CCNA,IAAAG,EAmCaC,EAAN,KAAqB,CAG1B,YAAYC,EAAkB,CAF9BC,EAAA,KAASH,GAGPI,EAAA,KAAKJ,EAAQE,EACf,CAEA,IAAW,aAA6B,CACtC,OAAO,aAAa,2BAA+B,CACrD,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KAASH,GAIP,OAAAI,EAAA,KAAKJ,EAAQE,GACN,IAAI,MAAM,KAAM,CACrB,IAAIG,EAAwBC,EAAW,CACrC,OAAMA,KAAKD,IACTA,EAAOC,CAAC,EAAI,IAAIC,EAAaC,EAAAH,EAAOL,GAAOM,CAAC,GACvCD,EAAOC,CAAC,CACjB,CACF,CAAC,CACH,CACF,EAbWN,EAAA,YCKJ,IAAMS,EAAN,KAAiB,CAMtB,YAAYC,EAA0B,CACpC,KAAK,OAASA,EACd,KAAK,KAAO,IAAIC,EAAe,IAAI,EACnC,KAAK,SAAW,IAAIC,EAAe,IAAI,CACzC,CACF,EAEO,SAASC,EAAaH,EAAsC,CACjE,OAAO,IAAID,EAAWC,CAAM,CAC9B","names":["index_exports","__export","EntitiesClient","EntityClient","LumiAuthClient","LumiClient","createClient","__toCommonJS","import_ofetch","request","lumi","uri","options","__spreadValues","getIcon","_a","_b","getTitle","_lumi","LumiAuthClient","lumi","__privateAdd","__privateSet","accessToken","left","top","popup","__privateGet","cleanup","resolve","reject","timer","handleMessage","data","origin","source","getIcon","getTitle","__async","res","request","_lumi","EntityClient","lumi","entityName","__privateAdd","__privateSet","_0","__async","filter","sort","limit","skip","res","request","__privateGet","id","data","ids","suffix","_lumi","EntitiesClient","lumi","__privateAdd","__privateSet","target","p","EntityClient","__privateGet","LumiClient","config","LumiAuthClient","EntitiesClient","createClient"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var D=Object.defineProperty;var x=Object.getOwnPropertySymbols;var O=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable;var A=i=>{throw TypeError(i)};var S=(i,e,t)=>e in i?D(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,I=(i,e)=>{for(var t in e||(e={}))O.call(e,t)&&S(i,t,e[t]);if(x)for(var t of x(e))N.call(e,t)&&S(i,t,e[t]);return i};var M=(i,e,t)=>e.has(i)||A("Cannot "+t);var r=(i,e,t)=>(M(i,e,"read from private field"),t?t.call(i):e.get(i)),h=(i,e,t)=>e.has(i)?A("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),d=(i,e,t,s)=>(M(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t);var c=(i,e,t)=>new Promise((s,m)=>{var p=a=>{try{f(t.next(a))}catch(y){m(y)}},o=a=>{try{f(t.throw(a))}catch(y){m(y)}},f=a=>a.done?s(a.value):Promise.resolve(a.value).then(p,o);f((t=t.apply(i,e)).next())});import{ofetch as U}from"ofetch";function l(i,e,t={}){return i.auth.accessToken&&(t.headers=I({Authorization:`Bearer ${i.auth.accessToken}`},t.headers)),U(e,I({baseURL:i.config.apiBaseUrl},t))}function R(){var i,e;return(e=(i=document.querySelector('link[rel="icon"]'))==null?void 0:i.href)!=null?e:null}function k(){var i;return(i=document.title)!=null?i:null}var u,E=class{constructor(e){h(this,u);d(this,u,e)}get accessToken(){return localStorage.getItem("lumi-access-token")}set accessToken(e){e?localStorage.setItem("lumi-access-token",e):localStorage.removeItem("lumi-access-token")}get isAuthenticated(){return!!this.accessToken}signIn(){let s=(window.screen.width-800)/2,m=(window.screen.height-600)/2,p=window.open(r(this,u).config.apiBaseUrl,"_blank",`width=800,height=600,left=${s},top=${m}`),o;return new Promise((f,a)=>{if(!p)return a(new Error("Open auth window failed"));let y=setInterval(()=>{p.closed&&a(new Error("Auth window closed"))},1e3),L=({data:g,origin:P,source:v})=>{if(!(P!==r(this,u).config.authOrigin||v!==p))switch(g==null?void 0:g.type){case"lumi-ready":{p.postMessage({type:"lumi-init",data:{projectId:r(this,u).config.projectId,icon:R(),title:k()}},r(this,u).config.authOrigin);break}case"lumi-sign-in":{if(g.data.projectId!==r(this,u).config.projectId)break;p.close(),this.accessToken=g.data.accessToken,f(g.data);break}}};window.addEventListener("message",L),o=()=>{clearInterval(y),window.removeEventListener("message",L)}}).finally(()=>o==null?void 0:o())}signOut(){this.accessToken=null}getUser(){return c(this,null,function*(){let e=yield l(r(this,u),"/lm/user/info");if(e.code!==200)throw new Error(e.message);return e.data})}};u=new WeakMap;var n,b=class{constructor(e,t){h(this,n);d(this,n,e),this.entityName=t}list(p){return c(this,arguments,function*({filter:e,sort:t,limit:s,skip:m}){let o=yield l(r(this,n),this.uri("/find"),{method:"POST",body:{filter:e,sort:t,limit:s,skip:m}});if(o.code!==200)throw new Error(o.message);return o.data})}get(e){return c(this,null,function*(){let t=yield l(r(this,n),this.uri(`/${e}`),{method:"GET"});if(t.code!==200)throw new Error(t.message);return t.data})}create(e){return c(this,null,function*(){let t=yield l(r(this,n),this.uri(),{method:"POST",body:e});if(t.code!==200)throw new Error(t.message);return t.data})}createMany(e){return c(this,null,function*(){let t=yield l(r(this,n),this.uri("/batch"),{method:"POST",body:e});if(t.code!==200)throw new Error(t.message);return t.data})}update(e,t){return c(this,null,function*(){let s=yield l(r(this,n),this.uri(),{method:"PUT",body:{filter:{_id:e},update:t}});if(s.code!==200)throw new Error(s.message);return s.data})}delete(e){return c(this,null,function*(){let t=yield l(r(this,n),this.uri(`/${e}`),{method:"DELETE"});if(t.code!==200)throw new Error(t.message)})}deleteMany(e){return c(this,null,function*(){let t=yield l(r(this,n),this.uri("/batch-by-ids"),{method:"DELETE",params:{ids:e}});if(t.code!==200)throw new Error(t.message)})}uri(e=""){return`/lm/${r(this,n).config.projectId}/${this.entityName}/documents${e}`}};n=new WeakMap;var w,T=class{constructor(e){h(this,w);return d(this,w,e),new Proxy(this,{get(t,s){return s in t||(t[s]=new b(r(t,w),s)),t[s]}})}};w=new WeakMap;var C=class{constructor(e){this.config=e,this.auth=new E(this),this.entities=new T(this)}};function ee(i){return new C(i)}export{T as EntitiesClient,b as EntityClient,E as LumiAuthClient,C as LumiClient,ee as createClient};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/request.ts","../src/utils/common.ts","../src/core/auth-client.ts","../src/core/entity-client.ts","../src/core/entities-client.ts","../src/core/lumi-client.ts"],"sourcesContent":["import type { FetchOptions } from 'ofetch'\nimport type { LumiClient } from '@/core/lumi-client'\nimport { ofetch } from 'ofetch'\n\nexport interface ApiResponse<T> {\n code: number\n message: string\n data: T\n}\n\nexport function request<T>(lumi: LumiClient, uri: string, options: FetchOptions<'json'> = {}): Promise<T> {\n if (lumi.auth.accessToken) {\n options.headers = {\n Authorization: `Bearer ${lumi.auth.accessToken}`,\n ...options.headers,\n }\n }\n\n return ofetch<T>(uri, {\n baseURL: lumi.config.apiBaseUrl,\n ...options,\n })\n}\n","export function getIcon(): string | null {\n return document.querySelector<HTMLLinkElement>('link[rel=\"icon\"]')?.href ?? null\n}\n\nexport function getTitle(): string | null {\n return document.title ?? null\n}\n","import type { LumiClient } from '@/core/lumi-client'\nimport type { ApiResponse } from '@/lib/request'\nimport { MessageType, StorageKey } from '@/constants'\nimport { request } from '@/lib/request'\nimport { getIcon, getTitle } from '@/utils/common'\n\nexport interface User {\n userId: string\n email: string\n}\n\nexport interface MessageSignInData {\n projectId: string\n accessToken: string\n user: User\n}\n\nexport type MessageDataReceive = {\n type: MessageType.READY\n} | {\n type: MessageType.SIGN_IN\n data: MessageSignInData\n}\n\nexport interface MessageInitData {\n projectId: string\n icon: string | null\n title: string | null\n}\n\nexport interface MessageDataSend {\n type: MessageType.INIT\n data: MessageInitData\n}\n\nexport class LumiAuthClient {\n readonly #lumi: LumiClient\n\n constructor(lumi: LumiClient) {\n this.#lumi = lumi\n }\n\n public get accessToken(): string | null {\n return localStorage.getItem(StorageKey.ACCESS_TOKEN)\n }\n\n public set accessToken(accessToken: string | null) {\n if (accessToken)\n localStorage.setItem(StorageKey.ACCESS_TOKEN, accessToken)\n else\n localStorage.removeItem(StorageKey.ACCESS_TOKEN)\n }\n\n public get isAuthenticated(): boolean {\n return !!this.accessToken\n }\n\n /** 登录 */\n public signIn(): Promise<MessageSignInData> {\n const width = 800\n const height = 600\n const left = (window.screen.width - width) / 2\n const top = (window.screen.height - height) / 2\n const popup = window.open(this.#lumi.config.apiBaseUrl, '_blank', `width=${width},height=${height},left=${left},top=${top}`)\n\n let cleanup: () => void\n return new Promise<MessageSignInData>((resolve, reject) => {\n if (!popup)\n return reject(new Error('Open auth window failed'))\n\n const timer = setInterval(() => {\n if (popup.closed)\n reject(new Error('Auth window closed'))\n }, 1000)\n\n const handleMessage = ({ data, origin, source }: MessageEvent<MessageDataReceive | null>): void => {\n if (origin !== this.#lumi.config.authOrigin || source !== popup)\n return\n\n switch (data?.type) {\n case MessageType.READY: {\n popup.postMessage({\n type: MessageType.INIT,\n data: {\n projectId: this.#lumi.config.projectId,\n icon: getIcon(),\n title: getTitle(),\n },\n } satisfies MessageDataSend, this.#lumi.config.authOrigin)\n break\n }\n case MessageType.SIGN_IN: {\n if (data.data.projectId !== this.#lumi.config.projectId)\n break\n popup.close()\n this.accessToken = data.data.accessToken\n resolve(data.data)\n break\n }\n }\n }\n window.addEventListener('message', handleMessage)\n\n cleanup = () => {\n clearInterval(timer)\n window.removeEventListener('message', handleMessage)\n }\n }).finally(() => cleanup?.())\n }\n\n /** 退出登录 */\n public signOut(): void {\n this.accessToken = null\n }\n\n /** 获取当前用户 */\n public async getUser(): Promise<User> {\n const res = await request<ApiResponse<User>>(this.#lumi, '/lm/user/info')\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n}\n","import type { LumiClient } from '@/core/lumi-client'\nimport type { ApiResponse } from '@/lib/request'\nimport { request } from '@/lib/request'\n\nexport interface Entity extends Record<string, any> {\n id: string\n}\n\nexport class EntityClient {\n readonly #lumi: LumiClient\n public readonly entityName: string\n\n constructor(lumi: LumiClient, entityName: string) {\n this.#lumi = lumi\n this.entityName = entityName\n }\n\n /** 查询文档列表 */\n public async list({ filter, sort, limit, skip }: {\n filter?: any\n sort?: string\n limit?: number\n skip?: number\n }): Promise<Entity[]> {\n const res = await request<ApiResponse<Entity[]>>(this.#lumi, this.uri('/find'), {\n method: 'POST',\n body: { filter, sort, limit, skip },\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 获取单个文档 */\n public async get(id: string): Promise<Entity | null> {\n const res = await request<ApiResponse<Entity>>(this.#lumi, this.uri(`/${id}`), {\n method: 'GET',\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 创建文档 */\n public async create(data: Record<string, any>): Promise<Entity> {\n const res = await request<ApiResponse<Entity>>(this.#lumi, this.uri(), {\n method: 'POST',\n body: data,\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 批量创建文档 */\n public async createMany(data: Record<string, any>[]): Promise<Entity[]> {\n const res = await request<ApiResponse<Entity[]>>(this.#lumi, this.uri('/batch'), {\n method: 'POST',\n body: data,\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 更新文档 */\n public async update(id: string, data: Record<string, any>): Promise<Entity> {\n const res = await request<ApiResponse<Entity>>(this.#lumi, this.uri(), {\n method: 'PUT',\n body: { filter: { _id: id }, update: data },\n })\n if (res.code !== 200)\n throw new Error(res.message)\n return res.data\n }\n\n /** 删除文档 */\n public async delete(id: string): Promise<void> {\n const res = await request<ApiResponse<null>>(this.#lumi, this.uri(`/${id}`), {\n method: 'DELETE',\n })\n if (res.code !== 200)\n throw new Error(res.message)\n }\n\n /** 批量删除文档 */\n public async deleteMany(ids: string[]): Promise<void> {\n const res = await request<ApiResponse<null>>(this.#lumi, this.uri('/batch-by-ids'), {\n method: 'DELETE',\n params: { ids },\n })\n if (res.code !== 200)\n throw new Error(res.message)\n }\n\n private uri(suffix = ''): string {\n return `/lm/${this.#lumi.config.projectId}/${this.entityName}/documents${suffix}`\n }\n}\n","import type { LumiClient } from '@/core/lumi-client'\nimport { EntityClient } from '@/core/entity-client'\n\nexport class EntitiesClient {\n readonly #lumi: LumiClient\n [key: string]: EntityClient\n\n constructor(lumi: LumiClient) {\n this.#lumi = lumi\n return new Proxy(this, {\n get(target: EntitiesClient, p: string) {\n if (!(p in target))\n target[p] = new EntityClient(target.#lumi, p)\n return target[p]\n },\n }) as this\n }\n}\n","import { LumiAuthClient } from '@/core/auth-client'\nimport { EntitiesClient } from '@/core/entities-client'\n\nexport interface LumiClientConfig {\n projectId: string\n apiBaseUrl: string\n authOrigin: string\n}\n\nexport class LumiClient {\n public config: LumiClientConfig\n\n public auth: LumiAuthClient\n public entities: EntitiesClient\n\n constructor(config: LumiClientConfig) {\n this.config = config\n this.auth = new LumiAuthClient(this)\n this.entities = new EntitiesClient(this)\n }\n}\n\nexport function createClient(config: LumiClientConfig): LumiClient {\n return new LumiClient(config)\n}\n"],"mappings":"i3BAEA,OAAS,UAAAA,MAAc,SAQhB,SAASC,EAAWC,EAAkBC,EAAaC,EAAgC,CAAC,EAAe,CACxG,OAAIF,EAAK,KAAK,cACZE,EAAQ,QAAUC,EAAA,CAChB,cAAe,UAAUH,EAAK,KAAK,WAAW,IAC3CE,EAAQ,UAIRE,EAAUH,EAAKE,EAAA,CACpB,QAASH,EAAK,OAAO,YAClBE,EACJ,CACH,CCtBO,SAASG,GAAyB,CAAzC,IAAAC,EAAAC,EACE,OAAOA,GAAAD,EAAA,SAAS,cAA+B,kBAAkB,IAA1D,YAAAA,EAA6D,OAA7D,KAAAC,EAAqE,IAC9E,CAEO,SAASC,GAA0B,CAJ1C,IAAAF,EAKE,OAAOA,EAAA,SAAS,QAAT,KAAAA,EAAkB,IAC3B,CCNA,IAAAG,EAmCaC,EAAN,KAAqB,CAG1B,YAAYC,EAAkB,CAF9BC,EAAA,KAASH,GAGPI,EAAA,KAAKJ,EAAQE,EACf,CAEA,IAAW,aAA6B,CACtC,OAAO,aAAa,2BAA+B,CACrD,CAEA,IAAW,YAAYG,EAA4B,CAC7CA,EACF,aAAa,4BAAiCA,CAAW,EAEzD,aAAa,8BAAkC,CACnD,CAEA,IAAW,iBAA2B,CACpC,MAAO,CAAC,CAAC,KAAK,WAChB,CAGO,QAAqC,CAG1C,IAAMC,GAAQ,OAAO,OAAO,M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CAAC,CACjB,CACF,CAAC,CACH,CACF,EAbWN,EAAA,YCKJ,IAAMS,EAAN,KAAiB,CAMtB,YAAYC,EAA0B,CACpC,KAAK,OAASA,EACd,KAAK,KAAO,IAAIC,EAAe,IAAI,EACnC,KAAK,SAAW,IAAIC,EAAe,IAAI,CACzC,CACF,EAEO,SAASC,GAAaH,EAAsC,CACjE,OAAO,IAAID,EAAWC,CAAM,CAC9B","names":["ofetch","request","lumi","uri","options","__spreadValues","ofetch","getIcon","_a","_b","getTitle","_lumi","LumiAuthClient","lumi","__privateAdd","__privateSet","accessToken","left","top","popup","__privateGet","cleanup","resolve","reject","timer","handleMessage","data","origin","source","getIcon","getTitle","__async","res","request","_lumi","EntityClient","lumi","entityName","__privateAdd","__privateSet","_0","__async","filter","sort","limit","skip","res","request","__privateGet","id","data","ids","suffix","_lumi","EntitiesClient","lumi","__privateAdd","__privateSet","target","p","EntityClient","__privateGet","LumiClient","config","LumiAuthClient","EntitiesClient","createClient"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@lumi.new/sdk",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "SDK for Lumi.new",
|
|
5
|
+
"sideEffects": false,
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"module": "dist/index.mjs",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsup",
|
|
14
|
+
"lint": "eslint --fix",
|
|
15
|
+
"test": "jest"
|
|
16
|
+
},
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"ofetch": "^1.4.1",
|
|
21
|
+
"uuid": "^11.1.0"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@antfu/eslint-config": "^4.13.3",
|
|
25
|
+
"@types/jest": "^29.5.14",
|
|
26
|
+
"eslint": "^9.28.0",
|
|
27
|
+
"jest": "^29.7.0",
|
|
28
|
+
"jest-environment-jsdom": "^29.7.0",
|
|
29
|
+
"ts-jest": "^29.3.4",
|
|
30
|
+
"ts-node": "^10.9.2",
|
|
31
|
+
"tsup": "^8.5.0",
|
|
32
|
+
"typescript": "^5.8.3"
|
|
33
|
+
}
|
|
34
|
+
}
|