@basictech/nextjs 0.1.0 → 0.1.1-beta.0

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,6 +1,6 @@
1
1
  {
2
2
  "name": "@basictech/nextjs",
3
- "version": "0.1.0",
3
+ "version": "0.1.1-beta.0",
4
4
  "description": "",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -17,14 +17,23 @@
17
17
  "author": "",
18
18
  "license": "ISC",
19
19
  "dependencies": {
20
- "jwt-decode": "^4.0.0"
20
+ "@radix-ui/react-avatar": "^1.1.1",
21
+ "@radix-ui/react-popover": "^1.1.2",
22
+ "dexie": "^4.0.8",
23
+ "dexie-observable": "^4.0.1-beta.13",
24
+ "dexie-react-hooks": "^1.1.7",
25
+ "dexie-syncable": "^4.0.1-beta.13",
26
+ "jwt-decode": "^4.0.0",
27
+ "uuid": "^10.0.0"
21
28
  },
22
29
  "devDependencies": {
30
+ "@repo/typescript-config": "*",
31
+ "@types/uuid": "^10.0.0",
23
32
  "tsup": "^7.2.0",
24
- "typescript": "^5.0.0",
25
- "@repo/typescript-config": "*"
33
+ "typescript": "^5.0.0"
26
34
  },
27
35
  "peerDependencies": {
28
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
36
+ "react": "^18.3.1",
37
+ "rxjs": "^7.8.1"
29
38
  }
30
- }
39
+ }
package/readme.md ADDED
@@ -0,0 +1,105 @@
1
+ # @basictech/nextjs
2
+
3
+ A Next.js package for integrating Basic authentication and database functionality into your Next.js applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @basictech/nextjs
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### 1. Wrap your application with BasicProvider
14
+
15
+ In your `_app.tsx` or `layout.tsx` file, wrap your application with the `BasicProvider`:
16
+
17
+ ```typescript
18
+ import { BasicProvider } from '@basictech/nextjs';
19
+
20
+ function MyApp({ Component, pageProps }) {
21
+ return (
22
+ <BasicProvider project_id="YOUR_PROJECT_ID">
23
+ <Component {...pageProps} />
24
+ </BasicProvider>
25
+ );
26
+ }
27
+
28
+ export default MyApp;
29
+ ```
30
+
31
+ Replace `YOUR_PROJECT_ID` with your actual Basic project ID.
32
+
33
+ ### 2. Use the useBasic hook
34
+
35
+ In your components, you can use the `useBasic` hook to access authentication and database functionality:
36
+
37
+ ```typescript
38
+ import { useBasic } from '@basictech/nextjs';
39
+
40
+ function MyComponent() {
41
+ const { user, isSignedIn, signin, signout, db } = useBasic();
42
+
43
+ if (!isSignedIn) {
44
+ return <button onClick={signin}>Sign In</button>;
45
+ }
46
+
47
+ return (
48
+ <div>
49
+ <h1>Welcome, {user.name}!</h1>
50
+ <button onClick={signout}>Sign Out</button>
51
+ </div>
52
+ );
53
+ }
54
+ ```
55
+
56
+ ### 3. Database Operations
57
+
58
+ You can perform database operations using the `db` object:
59
+
60
+ ```typescript
61
+ const { db } = useBasic();
62
+
63
+ // Get data
64
+ const getData = async () => {
65
+ const data = await db.table('myTable').get();
66
+ console.log(data);
67
+ };
68
+
69
+ // Add data
70
+ const addData = async () => {
71
+ const result = await db.table('myTable').add({ key: 'value' });
72
+ console.log(result);
73
+ };
74
+
75
+ // Update data
76
+ const updateData = async () => {
77
+ const result = await db.table('myTable').update('itemId', { key: 'newValue' });
78
+ console.log(result);
79
+ };
80
+ ```
81
+
82
+ ## API Reference
83
+
84
+ ### useBasic()
85
+
86
+ Returns an object with the following properties and methods:
87
+
88
+ - `user`: The current user object
89
+ - `isSignedIn`: Boolean indicating if the user is signed in
90
+ - `signin()`: Function to initiate the sign-in process
91
+ - `signout()`: Function to sign out the user
92
+ - `db`: Object for database operations
93
+
94
+ ### db
95
+
96
+ The `db` object provides the following methods:
97
+
98
+ - `table(tableName)`: Selects a table for operations
99
+ - `get()`: Retrieves all items from the table
100
+ - `add(value)`: Adds a new item to the table
101
+ - `update(id, value)`: Updates an item in the table
102
+
103
+ ## License
104
+
105
+ ISC
@@ -0,0 +1,85 @@
1
+ import React from 'react';
2
+ import * as Avatar from '@radix-ui/react-avatar';
3
+ import * as Popover from '@radix-ui/react-popover';
4
+
5
+ const LoginButton = () => {
6
+ return (
7
+ <Popover.Root>
8
+ {/* Trigger: Avatar that will be clicked */}
9
+ <Popover.Trigger asChild>
10
+ <Avatar.Root style={avatarContainerStyle}>
11
+ <Avatar.Image
12
+ src="https://via.placeholder.com/150"
13
+ alt="User Avatar"
14
+ style={avatarImageStyle}
15
+ />
16
+ <Avatar.Fallback delayMs={600} style={avatarFallbackStyle}>
17
+ U
18
+ </Avatar.Fallback>
19
+ </Avatar.Root>
20
+ </Popover.Trigger>
21
+
22
+ {/* Popover content */}
23
+ <Popover.Portal>
24
+ <Popover.Content style={popoverContentStyle} sideOffset={10}>
25
+ <p style={{ marginBottom: '10px' }}>Hello, User!</p>
26
+ <button style={buttonStyle}>Logout</button>
27
+ <Popover.Arrow style={popoverArrowStyle} />
28
+ </Popover.Content>
29
+ </Popover.Portal>
30
+ </Popover.Root>
31
+ );
32
+ };
33
+
34
+ // Basic styles
35
+ const avatarContainerStyle = {
36
+ display: 'inline-flex',
37
+ alignItems: 'center',
38
+ justifyContent: 'center',
39
+ width: '40px',
40
+ height: '40px',
41
+ borderRadius: '100%',
42
+ backgroundColor: '#ccc',
43
+ cursor: 'pointer',
44
+ };
45
+
46
+ const avatarImageStyle = {
47
+ width: '100%',
48
+ height: '100%',
49
+ borderRadius: '100%',
50
+ // objectFit: 'cover',
51
+ };
52
+
53
+ const avatarFallbackStyle = {
54
+ width: '100%',
55
+ height: '100%',
56
+ borderRadius: '100%',
57
+ backgroundColor: '#007bff',
58
+ color: 'white',
59
+ display: 'flex',
60
+ alignItems: 'center',
61
+ justifyContent: 'center',
62
+ fontSize: '20px',
63
+ };
64
+
65
+ const popoverContentStyle = {
66
+ padding: '20px',
67
+ borderRadius: '8px',
68
+ // backgroundColor: 'white',
69
+ boxShadow: '0 2px 10px rgba(0, 0, 0, 0.2)',
70
+ };
71
+
72
+ const buttonStyle = {
73
+ padding: '8px 16px',
74
+ backgroundColor: '#007bff',
75
+ color: '#fff',
76
+ border: 'none',
77
+ borderRadius: '4px',
78
+ cursor: 'pointer',
79
+ };
80
+
81
+ const popoverArrowStyle = {
82
+ fill: 'white',
83
+ };
84
+
85
+ export default LoginButton;
package/src/index.ts CHANGED
@@ -1,8 +1,18 @@
1
1
  "use client"
2
2
 
3
- import { useBasic, BasicProvider } from "./AuthContext";
3
+ // import { useBasic, BasicProvider } from "./AuthContext";
4
+ // import { useLiveQuery as useQuery } from "dexie-react-hooks"
4
5
 
6
+ import { useBasic, BasicProvider, useQuery } from "@basictech/react"
7
+ import LoginButton from "./componets";
8
+
9
+ // import dynamic from 'next/dynamic'
10
+
11
+ // const BasicSync = dynamic(() => import('./sync'), { ssr: false })
12
+ // import { BasicSync } from "./sync"
5
13
 
6
14
  export {
7
- useBasic, BasicProvider
8
- }
15
+ useBasic, BasicProvider, useQuery, LoginButton
16
+ }
17
+
18
+
package/src/sync.ts ADDED
@@ -0,0 +1,75 @@
1
+ import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
2
+
3
+ export function sync() {
4
+ console.log("sync");
5
+
6
+ async function storeFileToOPFS(fileName: string, fileContent: string | ArrayBuffer) {
7
+ if (!('storage' in navigator && 'getDirectory' in navigator.storage)) {
8
+ console.error('OPFS is not supported in this browser');
9
+ return;
10
+ }
11
+
12
+ try {
13
+ const root = await navigator.storage.getDirectory();
14
+
15
+ // Create or open a file
16
+ const fileHandle = await root.getFileHandle(fileName, { create: true });
17
+
18
+ const writable = await fileHandle.createWritable();
19
+
20
+ await writable.write(fileContent);
21
+
22
+ await writable.close();
23
+
24
+ console.log(`File "${fileName}" has been stored in OPFS`);
25
+ } catch (error) {
26
+ console.error('Error storing file to OPFS:', error);
27
+ }
28
+ }
29
+
30
+
31
+ // storeFileToOPFS(fileName, fileContent);
32
+
33
+ const log = console.log;
34
+ const error = console.error;
35
+
36
+ // const start = (sqlite3 : any) => {
37
+ // log('Running SQLite3 version', sqlite3.version.libVersion);
38
+ // const db = new sqlite3.oo1.DB('/mydb.sqlite3', 'ct');
39
+
40
+ // const result = db.exec('SELECT * FROM sqlite_master');
41
+ // // Your SQLite code here.
42
+ // };
43
+
44
+ const initializeSQLite = async () => {
45
+ try {
46
+ log('Loading and initializing SQLite3 module...');
47
+ const sqlite3 = await sqlite3InitModule({
48
+ print: log,
49
+ printErr: error,
50
+ });
51
+ log('Done initializing. Running demo...');
52
+ log(sqlite3.version.libVersion);
53
+
54
+ const db = new sqlite3.oo1.DB('/mydb.sqlite3', 'ct');
55
+ const result = db.exec('SELECT * FROM sqlite_master');
56
+
57
+
58
+
59
+ log(result);
60
+
61
+
62
+ // start(sqlite3);
63
+ } catch (err: any) {
64
+
65
+ error('Initialization error:', err.name, err.message);
66
+ }
67
+ };
68
+
69
+ initializeSQLite();
70
+
71
+
72
+
73
+
74
+
75
+ }
@@ -1,268 +0,0 @@
1
- //@ts-nocheck
2
- import React, { createContext, useContext, useEffect, useState } from 'react'
3
- import { jwtDecode} from 'jwt-decode'
4
-
5
- import { get, add, update, deleteRecord } from './db'
6
-
7
- type User = {
8
- name?: string,
9
- email?: string,
10
- id?: string,
11
- primaryEmailAddress?: {
12
- emailAddress: string
13
- },
14
- fullName?: string
15
- }
16
-
17
- export const BasicContext = createContext<{
18
- unicorn: string,
19
- isLoaded: boolean,
20
- isSignedIn: boolean,
21
- user: User | null,
22
- signout: () => void,
23
- signin: () => void,
24
- getToken: () => Promise<string>,
25
- getSignInLink: () => string,
26
- db: any
27
- }>({
28
- unicorn: "🦄",
29
- isLoaded: false,
30
- isSignedIn: false,
31
- user: null,
32
- signout: () => {},
33
- signin: () => {},
34
- getToken: () => new Promise(() => {}),
35
- getSignInLink: () => "",
36
- db: {}
37
- });
38
-
39
- type Token = {
40
- access_token: string,
41
- token_type: string,
42
- expires_in: number,
43
- refresh: string,
44
- }
45
-
46
- export function BasicProvider({children, project_id}: {children: React.ReactNode, project_id: string}) {
47
- const [isLoaded, setIsLoaded] = useState(false)
48
- const [isSignedIn, setIsSignedIn] = useState(false)
49
- const [token, setToken] = useState<Token | null>(null)
50
- const [authCode, setAuthCode] = useState<string | null>(null)
51
- const [user, setUser] = useState<User>({})
52
-
53
- //todo:
54
- //add random state to signin link & verify random state
55
-
56
- const getSignInLink = () => {
57
- console.log('getting sign in link...')
58
-
59
- const randomState = Math.random().toString(36).substring(7);
60
-
61
- let baseUrl = "https://api.basic.tech/auth/authorize"
62
- baseUrl += `?client_id=${project_id}`
63
- baseUrl += `&redirect_uri=${encodeURIComponent(window.location.href)}`
64
- baseUrl += `&response_type=code`
65
- baseUrl += `&scope=openid`
66
- baseUrl += `&state=1234zyx`
67
-
68
- return baseUrl;
69
- }
70
-
71
- const signin = () => {
72
- console.log('signing in: ', getSignInLink())
73
- const signInLink = getSignInLink()
74
- //todo: change to the other thing?
75
- window.location.href = signInLink;
76
- }
77
-
78
- const signout = () => {
79
- console.log('signing out!')
80
- setUser({})
81
- setIsSignedIn(false)
82
- setToken(null)
83
- setAuthCode(null)
84
- document.cookie = `basic_token=; Secure; SameSite=Strict`;
85
- }
86
-
87
- const getToken = async () : Promise<string> => {
88
- console.log('getting token...')
89
-
90
- if (!token) {
91
- console.log('no token found')
92
- return ''
93
- }
94
-
95
- const decoded = jwtDecode(token?.access_token)
96
- const isExpired = decoded.exp && decoded.exp < Date.now() / 1000
97
-
98
- if (isExpired) {
99
- console.log('token is expired - refreshing ...')
100
- const newToken = await fetchToken(token?.refresh)
101
- return newToken?.access_token || ''
102
- }
103
-
104
- return token?.access_token || ''
105
- }
106
-
107
- function getCookie(name: string) {
108
- let cookieValue = '';
109
- if (document.cookie && document.cookie !== '') {
110
- const cookies = document.cookie.split(';');
111
- for (let i = 0; i < cookies.length; i++) {
112
- const cookie = cookies[i].trim();
113
- if (cookie.substring(0, name.length + 1) === (name + '=')) {
114
- cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
115
- break;
116
- }
117
- }
118
- }
119
- return cookieValue;
120
- }
121
-
122
- const fetchToken = async (code: string) => {
123
- const token = await fetch('https://api.basic.tech/auth/token', {
124
- method: 'POST',
125
- headers: {
126
- 'Content-Type': 'application/json'
127
- },
128
- body: JSON.stringify({code: code})
129
- })
130
- .then(response => response.json())
131
- .catch(error => console.error('Error:', error))
132
-
133
- if (token.error) {
134
- console.log('error fetching token', token.error)
135
- return
136
- } else {
137
- // console.log('token', token)
138
- setToken(token)
139
- }
140
- return token
141
- }
142
-
143
- useEffect(() => {
144
- let cookie_token = getCookie('basic_token')
145
- if (cookie_token !== '') {
146
- setToken(JSON.parse(cookie_token))
147
- }
148
-
149
- if (window.location.search.includes('code')) {
150
- let code = window.location.search.split('code=')[1].split('&')[0]
151
- // console.log('code found', code)
152
-
153
- // todo: check state is valid
154
- setAuthCode(code) // remove this? dont need to store code?
155
- fetchToken(code)
156
-
157
- window.history.pushState({}, document.title, "/");
158
-
159
- } else {
160
- setIsLoaded(true)
161
- }
162
- }, [])
163
-
164
- useEffect(() => {
165
- async function fetchUser (acc_token: string) {
166
- const user = await fetch('https://api.basic.tech/auth/userInfo', {
167
- method: 'GET',
168
- headers: {
169
- 'Authorization': `Bearer ${acc_token}`
170
- }
171
- })
172
- .then(response => response.json())
173
- .catch(error => console.error('Error:', error))
174
-
175
- if (user.error) {
176
- console.log('error fetching user', user.error)
177
- // refreshToken()
178
- return
179
- } else {
180
- // console.log('user', user)
181
- document.cookie = `basic_token=${JSON.stringify(token)}; Secure; SameSite=Strict`;
182
- setUser(user)
183
- setIsSignedIn(true)
184
- setIsLoaded(true)
185
- }
186
- }
187
-
188
- async function checkToken () {
189
- if (!token) {
190
- console.log('error: no user token found')
191
- return
192
- }
193
-
194
- const decoded = jwtDecode(token?.access_token)
195
- const isExpired = decoded.exp && decoded.exp < Date.now() / 1000
196
-
197
- if (isExpired) {
198
- console.log('token is expired - refreshing ...')
199
- const newToken = await fetchToken(token?.refresh)
200
- fetchUser(newToken.access_token)
201
- } else {
202
- fetchUser(token.access_token)
203
- }
204
- }
205
-
206
- if (token) {
207
- checkToken()
208
- setIsLoaded(true)
209
- }
210
- }, [token])
211
-
212
-
213
-
214
-
215
- const db = (tableName : string) => {
216
- const checkSignIn = () => {
217
- if (!isSignedIn) {
218
- throw new Error('cannot use db. user not logged in.')
219
- }
220
- }
221
-
222
- return {
223
- get: async () => {
224
- checkSignIn()
225
- const tok = await getToken()
226
- return get({projectId: project_id, accountId: user.id, tableName: tableName, token: tok } )
227
- },
228
- add: async (value: any) => {
229
- checkSignIn()
230
- const tok = await getToken()
231
- return add({projectId: project_id, accountId: user.id, tableName: tableName, value: value, token: tok } )
232
- },
233
- update: async (id: string,value : any) => {
234
- checkSignIn()
235
- const tok = await getToken()
236
- return update({projectId: project_id, accountId: user.id, tableName: tableName, id: id, value: value, token: tok } )
237
- },
238
- delete: async (id: string) => {
239
- checkSignIn()
240
- const tok = await getToken()
241
- return deleteRecord({projectId: project_id, accountId: user.id, tableName: tableName, id: id, token: tok } )
242
- }
243
-
244
- }
245
-
246
- }
247
-
248
- return (
249
- <BasicContext.Provider value={{
250
- unicorn: "🦄",
251
- isLoaded,
252
- isSignedIn,
253
- user,
254
- signout,
255
- signin,
256
- getToken,
257
- getSignInLink,
258
- db,
259
-
260
- }}>
261
- {children}
262
- </BasicContext.Provider>
263
- )
264
- }
265
-
266
- export function useBasic() {
267
- return useContext(BasicContext);
268
- }
package/src/db.ts DELETED
@@ -1,55 +0,0 @@
1
- //@ts-nocheck
2
-
3
- const baseUrl = 'https://api.basic.tech';
4
- // const baseUrl = 'http://localhost:3000';
5
-
6
-
7
- async function get({ projectId, accountId, tableName, token }) {
8
- const url = `${baseUrl}/project/${projectId}/db/${accountId}/${tableName}`;
9
- const response = await fetch(url, {
10
- headers: {
11
- 'Authorization': `Bearer ${token}`
12
- }
13
- });
14
- return response.json();
15
- }
16
-
17
- async function add({ projectId, accountId, tableName, value, token }) {
18
- const url = `${baseUrl}/project/${projectId}/db/${accountId}/${tableName}`;
19
- const response = await fetch(url, {
20
- method: 'POST',
21
- headers: {
22
- 'Content-Type': 'application/json',
23
- 'Authorization': `Bearer ${token}`
24
- },
25
- body: JSON.stringify({"value": value})
26
- });
27
- return response.json();
28
- }
29
-
30
- async function update({ projectId, accountId, tableName, id, value, token }) {
31
- const url = `${baseUrl}/project/${projectId}/db/${accountId}/${tableName}/${id}`;
32
- const response = await fetch(url, {
33
- method: 'PATCH',
34
- headers: {
35
- 'Content-Type': 'application/json',
36
- 'Authorization': `Bearer ${token}`
37
- },
38
- body: JSON.stringify({id: id, value: value})
39
- });
40
- return response.json();
41
- }
42
-
43
- async function deleteRecord({ projectId, accountId, tableName, id, token }) {
44
- const url = `${baseUrl}/project/${projectId}/db/${accountId}/${tableName}/${id}`;
45
- const response = await fetch(url, {
46
- method: 'DELETE',
47
- headers: {
48
- 'Authorization': `Bearer ${token}`
49
- }
50
- });
51
- return response.json();
52
- }
53
-
54
- export { get, add, update, deleteRecord };
55
-