Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Adding the JS SDK to the core repo * Create tough-crews-shout.md * cleaning up some files * Removed generated files * updated tests to vitest * migrating to vitest * updated api mocking * updated api mocking for tfa * updated comments and fields tests * updated the rest of the handler tests * updated the rest of the tests * fix build output * update license year * moved package to packages/sdk * updated package lock * Move vitest config to 'vitest.config.ts' As we have it in the api (since no vite only vitest) * Sort package.json file As we did for the other packages * remove argon2 dependency --------- Co-authored-by: rijkvanzanten <rijkvanzanten@me.com> Co-authored-by: Pascal Jufer <pascal-jufer@bluewin.ch>
- Loading branch information
1 parent
4c45f96
commit 2016afa
Showing
74 changed files
with
5,149 additions
and
68 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
--- | ||
"directus": patch | ||
"@directus/sdk": patch | ||
--- | ||
|
||
Moved the JS SDK to the monorepo |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './dist/sdk.cjs.js'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
Copyright 2023 Monospace Inc. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
{ | ||
"name": "@directus/sdk", | ||
"version": "10.3.3", | ||
"description": "The official Directus SDK for use in JavaScript!", | ||
"keywords": [ | ||
"api", | ||
"client", | ||
"cms", | ||
"directus", | ||
"headless", | ||
"javascript", | ||
"node", | ||
"sdk" | ||
], | ||
"bugs": { | ||
"url": "https://github.com/directus/directus/issues" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/directus/directus.git", | ||
"directory": "packages/sdk" | ||
}, | ||
"license": "MIT", | ||
"author": "Rijk van Zanten <rijkvanzanten@me.com>", | ||
"exports": { | ||
".": { | ||
"types": "./dist/index.d.ts", | ||
"import": { | ||
"node": "./index.mjs", | ||
"default": "./dist/sdk.bundler.js" | ||
}, | ||
"require": "./dist/sdk.cjs.js" | ||
}, | ||
"./package.json": "./package.json" | ||
}, | ||
"main": "dist/sdk.cjs.js", | ||
"unpkg": "dist/sdk.esm.min.js", | ||
"module": "dist/sdk.bundler.js", | ||
"types": "dist/index.d.ts", | ||
"files": [ | ||
"dist", | ||
"index.mjs" | ||
], | ||
"scripts": { | ||
"build": "tsc --project tsconfig.prod.json", | ||
"dev": "tsc --watch", | ||
"test": "vitest --watch=false" | ||
}, | ||
"dependencies": { | ||
"axios": "^0.27.2" | ||
}, | ||
"devDependencies": { | ||
"@directus/tsconfig": "0.0.7", | ||
"@types/node": "^18.0.3", | ||
"@typescript-eslint/eslint-plugin": "^5.30.5", | ||
"@typescript-eslint/parser": "^5.30.5", | ||
"dotenv": "16.0.1", | ||
"jsdom": "^22.0.0", | ||
"msw": "^1.2.1", | ||
"typescript": "4.7.4", | ||
"vitest": "0.31.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
# Directus JS SDK | ||
|
||
## Installation | ||
|
||
``` | ||
npm install @directus/sdk | ||
``` | ||
|
||
## Basic Usage | ||
|
||
```js | ||
import { Directus } from '@directus/sdk'; | ||
|
||
const directus = new Directus('http://directus.example.com'); | ||
|
||
const items = await directus.items('articles').readOne(15); | ||
console.log(items); | ||
``` | ||
|
||
```js | ||
import { Directus } from '@directus/sdk'; | ||
|
||
const directus = new Directus('http://directus.example.com'); | ||
|
||
directus | ||
.items('articles') | ||
.readOne(15) | ||
.then((item) => { | ||
console.log(item); | ||
}); | ||
``` | ||
|
||
## Reference | ||
|
||
See [the docs](https://docs.directus.io/reference/sdk/) for a full usage reference and all supported methods. | ||
|
||
## Contributing | ||
|
||
### Requirements | ||
|
||
- NodeJS LTS | ||
- pnpm 7.5.0 or newer | ||
|
||
### Commands | ||
|
||
The following `pnpm` scripts are available: | ||
|
||
- `pnpm lint` – Lint the code using Eslint / Prettier | ||
- `pnpm test` – Run the unit tests | ||
|
||
Make sure that both commands pass locally before creating a Pull Request. | ||
|
||
### Pushing a Release | ||
|
||
_This applies to maintainers only_ | ||
|
||
1. Create a new version / tag by running `pnpm version <version>`. Tip: use `pnpm version patch|minor|major` to | ||
auto-bump the version number | ||
1. Push the version commit / tag to GitHub (`git push && git push --tags`) | ||
|
||
The CI will automatically build and release to npm, and generate the release notes. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { IStorage } from './storage'; | ||
import { ITransport } from './transport'; | ||
import { PasswordsHandler } from './handlers/passwords'; | ||
|
||
export type AuthCredentials = { | ||
email: string; | ||
password: string; | ||
otp?: string; | ||
}; | ||
|
||
export type AuthToken = string; | ||
|
||
export type AuthTokenType = 'DynamicToken' | 'StaticToken' | null; | ||
|
||
export type AuthResult = { | ||
access_token: string; | ||
expires: number; | ||
refresh_token?: string; | ||
}; | ||
|
||
export type AuthMode = 'json' | 'cookie'; | ||
|
||
export type AuthOptions = { | ||
mode?: AuthMode; | ||
autoRefresh?: boolean; | ||
msRefreshBeforeExpires?: number; | ||
staticToken?: string; | ||
transport: ITransport; | ||
storage: IStorage; | ||
}; | ||
|
||
export abstract class IAuth { | ||
mode = (typeof window === 'undefined' ? 'json' : 'cookie') as AuthMode; | ||
|
||
abstract readonly token: Promise<string | null>; | ||
abstract readonly password: PasswordsHandler; | ||
|
||
abstract login(credentials: AuthCredentials): Promise<AuthResult>; | ||
abstract refresh(): Promise<AuthResult | false>; | ||
abstract refreshIfExpired(): Promise<void>; | ||
abstract static(token: AuthToken): Promise<boolean>; | ||
abstract logout(): Promise<void>; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,185 @@ | ||
import { IAuth, AuthCredentials, AuthResult, AuthToken, AuthOptions, AuthTokenType } from '../auth'; | ||
import { PasswordsHandler } from '../handlers/passwords'; | ||
import { IStorage } from '../storage'; | ||
import { ITransport } from '../transport'; | ||
|
||
export type AuthStorage<T extends AuthTokenType = 'DynamicToken'> = { | ||
access_token: T extends 'DynamicToken' | 'StaticToken' ? string : null; | ||
expires: T extends 'DynamicToken' ? number : null; | ||
refresh_token?: T extends 'DynamicToken' ? string : null; | ||
}; | ||
|
||
export class Auth extends IAuth { | ||
autoRefresh = true; | ||
msRefreshBeforeExpires = 30000; | ||
staticToken = ''; | ||
|
||
private _storage: IStorage; | ||
private _transport: ITransport; | ||
private passwords?: PasswordsHandler; | ||
|
||
private _refreshPromise?: Promise<AuthResult | false>; | ||
|
||
constructor(options: AuthOptions) { | ||
super(); | ||
|
||
this._transport = options.transport; | ||
this._storage = options.storage; | ||
|
||
this.autoRefresh = options?.autoRefresh ?? this.autoRefresh; | ||
this.mode = options?.mode ?? this.mode; | ||
this.msRefreshBeforeExpires = options?.msRefreshBeforeExpires ?? this.msRefreshBeforeExpires; | ||
|
||
if (options?.staticToken) { | ||
this.staticToken = options?.staticToken; | ||
|
||
this.updateStorage<'StaticToken'>({ | ||
access_token: this.staticToken, | ||
expires: null, | ||
refresh_token: null, | ||
}); | ||
} | ||
} | ||
|
||
get storage(): IStorage { | ||
return this._storage; | ||
} | ||
|
||
get transport(): ITransport { | ||
return this._transport; | ||
} | ||
|
||
get token(): Promise<string | null> { | ||
return (async () => { | ||
if (this._refreshPromise) { | ||
try { | ||
await this._refreshPromise; | ||
} finally { | ||
this._refreshPromise = undefined; | ||
} | ||
} | ||
|
||
return this._storage.auth_token; | ||
})(); | ||
} | ||
|
||
get password(): PasswordsHandler { | ||
return (this.passwords = this.passwords || new PasswordsHandler(this._transport)); | ||
} | ||
|
||
private resetStorage() { | ||
this._storage.auth_token = null; | ||
this._storage.auth_refresh_token = null; | ||
this._storage.auth_expires = null; | ||
this._storage.auth_expires_at = null; | ||
} | ||
|
||
private updateStorage<T extends AuthTokenType>(result: AuthStorage<T>) { | ||
const expires = result.expires ?? null; | ||
this._storage.auth_token = result.access_token; | ||
this._storage.auth_refresh_token = result.refresh_token ?? null; | ||
this._storage.auth_expires = expires; | ||
this._storage.auth_expires_at = new Date().getTime() + (expires ?? 0); | ||
} | ||
|
||
async refreshIfExpired() { | ||
if (this.staticToken) return; | ||
if (!this.autoRefresh) return; | ||
|
||
if (!this._storage.auth_expires_at) { | ||
// wait because resetStorage() call in refresh() | ||
try { | ||
await this._refreshPromise; | ||
} finally { | ||
this._refreshPromise = undefined; | ||
} | ||
|
||
return; | ||
} | ||
|
||
if (this._storage.auth_expires_at < new Date().getTime() + this.msRefreshBeforeExpires) { | ||
this.refresh(); | ||
} | ||
|
||
try { | ||
await this._refreshPromise; // wait for refresh | ||
} finally { | ||
this._refreshPromise = undefined; | ||
} | ||
} | ||
|
||
refresh(): Promise<AuthResult | false> { | ||
const refreshPromise = async () => { | ||
const refresh_token = this._storage.auth_refresh_token; | ||
|
||
this.resetStorage(); | ||
|
||
const response = await this._transport.post<AuthResult>('/auth/refresh', { | ||
refresh_token: this.mode === 'json' ? refresh_token : undefined, | ||
}); | ||
|
||
this.updateStorage<'DynamicToken'>(response.data!); | ||
|
||
return { | ||
access_token: response.data!.access_token, | ||
...(response.data?.refresh_token && { refresh_token: response.data.refresh_token }), | ||
expires: response.data!.expires, | ||
}; | ||
}; | ||
|
||
return (this._refreshPromise = refreshPromise()); | ||
} | ||
|
||
async login(credentials: AuthCredentials): Promise<AuthResult> { | ||
this.resetStorage(); | ||
|
||
const response = await this._transport.post<AuthResult>( | ||
'/auth/login', | ||
{ mode: this.mode, ...credentials }, | ||
{ headers: { Authorization: null } } | ||
); | ||
|
||
this.updateStorage(response.data!); | ||
|
||
return { | ||
access_token: response.data!.access_token, | ||
...(response.data?.refresh_token && { | ||
refresh_token: response.data.refresh_token, | ||
}), | ||
expires: response.data!.expires, | ||
}; | ||
} | ||
|
||
async static(token: AuthToken): Promise<boolean> { | ||
if (!this.staticToken) this.staticToken = token; | ||
|
||
await this._transport.get('/users/me', { | ||
params: { access_token: token }, | ||
headers: { Authorization: null }, | ||
}); | ||
|
||
this.updateStorage<'StaticToken'>({ | ||
access_token: token, | ||
expires: null, | ||
refresh_token: null, | ||
}); | ||
|
||
return true; | ||
} | ||
|
||
async logout(): Promise<void> { | ||
let refresh_token: string | undefined; | ||
|
||
if (this.mode === 'json') { | ||
refresh_token = this._storage.auth_refresh_token || undefined; | ||
} | ||
|
||
await this._transport.post('/auth/logout', { refresh_token }); | ||
|
||
this.updateStorage<null>({ | ||
access_token: null, | ||
expires: null, | ||
refresh_token: null, | ||
}); | ||
} | ||
} |
Oops, something went wrong.