@hackmd/api 1.1.1 → 2.0.0-pre.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 CHANGED
@@ -1,11 +1,41 @@
1
1
  # HackMD Node.js API Client
2
2
 
3
+ ![npm](https://img.shields.io/npm/v/@hackmd/api)
4
+
5
+ ## About
6
+
7
+ This is a Node.js client for the [HackMD API](https://hackmd.io/).
8
+
9
+ You can sign up for an account at [hackmd.io](https://hackmd.io/), and then create access tokens for your projects by following the [HackMD API documentation](https://hackmd.io/@hackmd-api/developer-portal).
10
+
11
+ For bugs and feature requests, please open an issue or pull request on [GitHub](https://github.com/hackmdio/api-client).
12
+
13
+ ## **v2.0.0 Update Note**
14
+
15
+ `v2.0.0` is a completely rewrite and is incompatible with `v1.x.x`. But the best of all, it does not require Node.JS runtime anymore, which means you can use it in a browser. We recommend you to upgrade to `v2.0.0` if you are using the old one.
16
+
3
17
  ## Installation
4
18
 
5
19
  ```bash
6
20
  npm install @hackmd/api --save
7
21
  ```
8
22
 
9
- ## Usage
23
+ ## Example
24
+
25
+ ```javascript
26
+ import HackMDAPI from '@hackmd/api'
27
+
28
+ const client = new HackMDAPI('YOUR_ACCESS_TOKEN' /* required */, 'https://api.hackmd.io/v1' /* optional */)
29
+
30
+ client.getMe().then(me => {
31
+ console.log(me.email)
32
+ })
33
+ ```
34
+
35
+ ## API
36
+
37
+ See the [code](./src/index.ts) and [typings](./src/type.ts). The API client is written in TypeScript, so you can get auto-completion and type checking in any TypeScript Language Server powered editor or IDE.
38
+
39
+ ## License
10
40
 
11
- TODO
41
+ MIT
@@ -0,0 +1,13 @@
1
+ declare class HackMDError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ declare class HttpResponseError extends HackMDError {
5
+ readonly code: number;
6
+ readonly statusText: string;
7
+ constructor(message: string, code: number, statusText: string);
8
+ }
9
+ declare class MissingRequiredArgument extends HackMDError {
10
+ }
11
+ declare class InternalServerError extends HttpResponseError {
12
+ }
13
+ export { HackMDError, HttpResponseError, MissingRequiredArgument, InternalServerError };
package/dist/error.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class HackMDError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ Object.setPrototypeOf(this, new.target.prototype);
7
+ }
8
+ }
9
+ exports.HackMDError = HackMDError;
10
+ class HttpResponseError extends HackMDError {
11
+ constructor(message, code, statusText) {
12
+ super(message);
13
+ this.code = code;
14
+ this.statusText = statusText;
15
+ }
16
+ }
17
+ exports.HttpResponseError = HttpResponseError;
18
+ class MissingRequiredArgument extends HackMDError {
19
+ }
20
+ exports.MissingRequiredArgument = MissingRequiredArgument;
21
+ class InternalServerError extends HttpResponseError {
22
+ }
23
+ exports.InternalServerError = InternalServerError;
package/dist/index.d.ts CHANGED
@@ -1,53 +1,19 @@
1
- interface APIOptions {
2
- serverUrl: string;
3
- cookiePath: string;
4
- enterprise: boolean;
1
+ import { CreateNoteOptions, GetMe, GetUserHistory, GetUserNotes, GetUserNote, CreateUserNote, GetUserTeams, GetTeamNotes, CreateTeamNote, DeleteUserNote, DeleteTeamNote, UpdateUserNote, UpdateTeamNote } from './type';
2
+ export default class API {
3
+ readonly accessToken: string;
4
+ hackmdAPIEndpointURL: string;
5
+ private axios;
6
+ constructor(accessToken: string, hackmdAPIEndpointURL?: string);
7
+ getMe(): Promise<GetMe>;
8
+ getHistory(): Promise<GetUserHistory>;
9
+ getNoteList(): Promise<GetUserNotes>;
10
+ getNote(noteId: string): Promise<GetUserNote>;
11
+ createNote(options: CreateNoteOptions): Promise<CreateUserNote>;
12
+ updateNoteContent(noteId: string, content?: string): Promise<UpdateUserNote>;
13
+ deleteNote(noteId: string): Promise<DeleteUserNote>;
14
+ getTeams(): Promise<GetUserTeams>;
15
+ getTeamNotes(teamPath: string): Promise<GetTeamNotes>;
16
+ createTeamNote(teamPath: string, options: CreateNoteOptions): Promise<CreateTeamNote>;
17
+ updateTeamNoteContent(teamPath: string, noteId: string, content?: string): Promise<UpdateTeamNote>;
18
+ deleteTeamNote(teamPath: string, noteId: string): Promise<DeleteTeamNote>;
5
19
  }
6
- declare type nodeFetchType = (url: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;
7
- export declare enum ExportType {
8
- PDF = 0,
9
- SLIDE = 1,
10
- MD = 2,
11
- HTML = 3
12
- }
13
- export declare type HistoryItem = {
14
- id: string;
15
- text: string;
16
- time: number | string;
17
- tags: string[];
18
- };
19
- export declare type NewNoteOption = {
20
- team: string;
21
- };
22
- /**
23
- * codimd API Client
24
- */
25
- declare class API {
26
- readonly serverUrl: string;
27
- readonly enterprise: boolean;
28
- private readonly _fetch;
29
- constructor(config?: Partial<APIOptions>);
30
- login(email: string, password: string): Promise<void>;
31
- loginLdap(username: string, password: string): Promise<void>;
32
- logout(): Promise<boolean>;
33
- isLogin(): Promise<boolean>;
34
- getMe(): Promise<any>;
35
- getHistory(): Promise<{
36
- history: HistoryItem[];
37
- }>;
38
- newNote(body: string, options?: NewNoteOption): Promise<string>;
39
- private exportRes;
40
- exportString(noteId: string, type: ExportType): Promise<string>;
41
- exportStream(noteId: string, type: ExportType): Promise<ReadableStream<Uint8Array> | null>;
42
- getTeams(): Promise<any>;
43
- get fetch(): nodeFetchType;
44
- get domain(): string | null;
45
- get defaultFetchOptions(): {
46
- headers: {
47
- 'User-Agent': string;
48
- };
49
- };
50
- private wrapHeaders;
51
- private loadCSRFToken;
52
- }
53
- export default API;
package/dist/index.js CHANGED
@@ -1,190 +1,84 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
- const cheerio_1 = tslib_1.__importDefault(require("cheerio"));
5
- const fs = tslib_1.__importStar(require("fs-extra"));
6
- const os_1 = require("os");
7
- const path = tslib_1.__importStar(require("path"));
8
- const node_fetch_1 = tslib_1.__importDefault(require("node-fetch"));
9
- const tough = require("tough-cookie");
10
- const tough_cookie_filestore_1 = tslib_1.__importDefault(require("tough-cookie-filestore"));
11
- const url = tslib_1.__importStar(require("url"));
12
- const utils_1 = require("./utils");
13
- let version = '';
14
- try {
15
- version = require('../package.json').version;
16
- }
17
- catch (err) { }
18
- const defaultCookiePath = path.join(os_1.homedir(), '.hackmd', 'cookies.json');
19
- const defaultConfig = {
20
- cookiePath: defaultCookiePath,
21
- serverUrl: 'https://hackmd.io',
22
- enterprise: true
23
- };
24
- function encodeFormComponent(form) {
25
- return Object.entries(form).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&');
26
- }
27
- var ExportType;
28
- (function (ExportType) {
29
- ExportType[ExportType["PDF"] = 0] = "PDF";
30
- ExportType[ExportType["SLIDE"] = 1] = "SLIDE";
31
- ExportType[ExportType["MD"] = 2] = "MD";
32
- ExportType[ExportType["HTML"] = 3] = "HTML";
33
- })(ExportType = exports.ExportType || (exports.ExportType = {}));
34
- /**
35
- * codimd API Client
36
- */
4
+ const axios_1 = tslib_1.__importDefault(require("axios"));
5
+ const HackMDErrors = tslib_1.__importStar(require("./error"));
37
6
  class API {
38
- constructor(config = {}) {
39
- const { serverUrl, cookiePath, enterprise } = utils_1.defaults(config, defaultConfig);
40
- fs.ensureFileSync(cookiePath);
41
- const jar = new tough_cookie_filestore_1.default(cookiePath);
42
- const fetch = require('fetch-cookie')(node_fetch_1.default, new tough.CookieJar(jar));
43
- this._fetch = fetch;
44
- this.serverUrl = serverUrl;
45
- this.enterprise = enterprise;
46
- }
47
- async login(email, password) {
48
- await this.fetch(`${this.serverUrl}/login`, {
49
- method: 'post',
50
- body: encodeFormComponent({ email, password }),
51
- headers: await this.wrapHeaders({
52
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
53
- })
7
+ constructor(accessToken, hackmdAPIEndpointURL = "https://api.hackmd.io/v1") {
8
+ this.accessToken = accessToken;
9
+ this.hackmdAPIEndpointURL = hackmdAPIEndpointURL;
10
+ if (!accessToken) {
11
+ throw new HackMDErrors.MissingRequiredArgument('Missing access token when creating HackMD client');
12
+ }
13
+ this.axios = axios_1.default.create({
14
+ baseURL: hackmdAPIEndpointURL,
15
+ headers: {
16
+ "Content-Type": "application/json",
17
+ }
54
18
  });
55
- }
56
- async loginLdap(username, password) {
57
- await this.fetch(`${this.serverUrl}/auth/ldap`, {
58
- method: 'post',
59
- body: encodeFormComponent({ username, password }),
60
- headers: await this.wrapHeaders({
61
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
62
- })
19
+ this.axios.interceptors.request.use((config) => {
20
+ config.headers.Authorization = `Bearer ${accessToken}`;
21
+ return config;
22
+ }, (err) => {
23
+ return Promise.reject(err);
63
24
  });
64
- }
65
- async logout() {
66
- const response = await this.fetch(`${this.serverUrl}/logout`, {
67
- method: this.enterprise ? 'POST' : 'GET',
68
- headers: await this.wrapHeaders({
69
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
70
- })
25
+ this.axios.interceptors.response.use((response) => {
26
+ return response;
27
+ }, async (err) => {
28
+ if (!err.response) {
29
+ return Promise.reject(err);
30
+ }
31
+ if (err.response.status >= 500) {
32
+ throw new HackMDErrors.InternalServerError(`HackMD internal error (${err.response.status} ${err.response.statusText})`, err.response.status, err.response.statusText);
33
+ }
34
+ else {
35
+ throw new HackMDErrors.HttpResponseError(`Received an error response (${err.response.status} ${err.response.statusText}) from HackMD`, err.response.status, err.response.statusText);
36
+ }
71
37
  });
72
- return response.status === 200;
73
- }
74
- async isLogin() {
75
- try {
76
- const data = await this.getMe();
77
- return data.status === 'ok';
78
- }
79
- catch (err) {
80
- return false;
81
- }
82
38
  }
83
39
  async getMe() {
84
- const response = await this.fetch(`${this.serverUrl}/me`, this.defaultFetchOptions);
85
- return response.json();
40
+ const { data } = await this.axios.get("me");
41
+ return data;
86
42
  }
87
43
  async getHistory() {
88
- const response = await this.fetch(`${this.serverUrl}/history`, this.defaultFetchOptions);
89
- return response.json();
44
+ const { data } = await this.axios.get("history");
45
+ return data;
90
46
  }
91
- async newNote(body, options) {
92
- let response;
93
- if (this.enterprise) {
94
- let newNoteUrl;
95
- if (options === null || options === void 0 ? void 0 : options.team) {
96
- newNoteUrl = `${this.serverUrl}/team/${options.team}/new`;
97
- }
98
- else {
99
- newNoteUrl = `${this.serverUrl}/new`;
100
- }
101
- response = await this.fetch(newNoteUrl, {
102
- method: 'POST',
103
- body: encodeFormComponent({ content: body }),
104
- headers: await this.wrapHeaders({
105
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
106
- })
107
- });
108
- }
109
- else {
110
- const contentType = 'text/markdown;charset=UTF-8';
111
- response = await this.fetch(`${this.serverUrl}/new`, {
112
- method: 'POST',
113
- body,
114
- headers: await this.wrapHeaders({
115
- 'Content-Type': contentType
116
- })
117
- });
118
- }
119
- if (response.status === 200) {
120
- return response.url;
121
- }
122
- else {
123
- throw new Error('Create note failed');
124
- }
47
+ async getNoteList() {
48
+ const { data } = await this.axios.get("notes");
49
+ return data;
125
50
  }
126
- async exportRes(noteId, type) {
127
- let res;
128
- switch (type) {
129
- case ExportType.PDF:
130
- res = await this.fetch(`${this.serverUrl}/${noteId}/pdf`, this.defaultFetchOptions);
131
- break;
132
- case ExportType.HTML:
133
- res = await this.fetch(`${this.serverUrl}/s/${noteId}`, this.defaultFetchOptions);
134
- break;
135
- case ExportType.SLIDE:
136
- res = await this.fetch(`${this.serverUrl}/${noteId}/slide`, this.defaultFetchOptions);
137
- break;
138
- case ExportType.MD:
139
- default:
140
- res = await this.fetch(`${this.serverUrl}/${noteId}/download`, this.defaultFetchOptions);
141
- }
142
- return res;
51
+ async getNote(noteId) {
52
+ const { data } = await this.axios.get(`notes/${noteId}`);
53
+ return data;
143
54
  }
144
- async exportString(noteId, type) {
145
- const res = await this.exportRes(noteId, type);
146
- return res.text();
55
+ async createNote(options) {
56
+ const { data } = await this.axios.post("notes", options);
57
+ return data;
147
58
  }
148
- async exportStream(noteId, type) {
149
- const res = await this.exportRes(noteId, type);
150
- return res.body;
59
+ async updateNoteContent(noteId, content) {
60
+ await this.axios.patch(`notes/${noteId}`, { content });
151
61
  }
152
- async getTeams() {
153
- let data;
154
- try {
155
- data = await this.getMe();
156
- }
157
- catch (err) {
158
- return [];
159
- }
160
- return data.teams || [];
62
+ async deleteNote(noteId) {
63
+ await this.axios.delete(`notes/${noteId}`);
161
64
  }
162
- get fetch() {
163
- return this._fetch;
65
+ async getTeams() {
66
+ const { data } = await this.axios.get("teams");
67
+ return data;
164
68
  }
165
- get domain() {
166
- return url.parse(this.serverUrl).host;
69
+ async getTeamNotes(teamPath) {
70
+ const { data } = await this.axios.get(`teams/${teamPath}/notes`);
71
+ return data;
167
72
  }
168
- get defaultFetchOptions() {
169
- return {
170
- headers: {
171
- 'User-Agent': `HackMD API Client ${version} Node.js`
172
- }
173
- };
73
+ async createTeamNote(teamPath, options) {
74
+ const { data } = await this.axios.post(`teams/${teamPath}/notes`, options);
75
+ return data;
174
76
  }
175
- async wrapHeaders(headers) {
176
- if (this.enterprise) {
177
- const csrf = await this.loadCSRFToken();
178
- return Object.assign(Object.assign({}, headers), { 'User-Agent': `HackMD API Client ${version} Node.js`, 'X-XSRF-Token': csrf });
179
- }
180
- else {
181
- return Object.assign(Object.assign({}, headers), { 'User-Agent': `HackMD API Client ${version} Node.js` });
182
- }
77
+ async updateTeamNoteContent(teamPath, noteId, content) {
78
+ await this.axios.patch(`teams/${teamPath}/notes/${noteId}`, { content });
183
79
  }
184
- async loadCSRFToken() {
185
- const html = await this.fetch(`${this.serverUrl}`).then(r => r.text());
186
- const $ = cheerio_1.default.load(html);
187
- return $('meta[name="csrf-token"]').attr('content') || '';
80
+ async deleteTeamNote(teamPath, noteId) {
81
+ await this.axios.delete(`teams/${teamPath}/notes/${noteId}`);
188
82
  }
189
83
  }
190
84
  exports.default = API;
package/dist/type.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ export declare enum TeamVisibilityType {
2
+ PUBLIC = "public",
3
+ PRIVATE = "private"
4
+ }
5
+ export declare enum NotePublishType {
6
+ EDIT = "edit",
7
+ VIEW = "view",
8
+ SLIDE = "slide",
9
+ BOOK = "book"
10
+ }
11
+ export declare enum CommentPermissionType {
12
+ DISABLED = "disabled",
13
+ FORBIDDEN = "forbidden",
14
+ OWNERS = "owners",
15
+ SIGNED_IN_USERS = "signed_in_users",
16
+ EVERYONE = "everyone"
17
+ }
18
+ export declare type CreateNoteOptions = {
19
+ title?: string;
20
+ content?: string;
21
+ readPermission?: NotePermissionRole;
22
+ writePermission?: NotePermissionRole;
23
+ commentPermission?: CommentPermissionType;
24
+ };
25
+ export declare type Team = {
26
+ id: string;
27
+ ownerId: string;
28
+ name: string;
29
+ logo: string;
30
+ path: string;
31
+ description: string;
32
+ hardBreaks: boolean;
33
+ visibility: TeamVisibilityType;
34
+ createdAt: Date;
35
+ };
36
+ export declare type User = {
37
+ id: string;
38
+ email: string | null;
39
+ name: string;
40
+ userPath: string;
41
+ photo: string;
42
+ teams: Team[];
43
+ };
44
+ export declare type SimpleUserProfile = {
45
+ name: string;
46
+ userPath: string;
47
+ photo: string;
48
+ biography: string | null;
49
+ createdAt: Date;
50
+ };
51
+ export declare enum NotePermissionRole {
52
+ OWNER = "owner",
53
+ SIGNED_IN = "signed_in",
54
+ GUEST = "guest"
55
+ }
56
+ export declare type Note = {
57
+ id: string;
58
+ title: string;
59
+ tags: string[];
60
+ lastChangedAt: string;
61
+ createdAt: string;
62
+ lastChangeUser: SimpleUserProfile | null;
63
+ publishType: NotePublishType;
64
+ publishedAt: string | null;
65
+ userPath: string | null;
66
+ teamPath: string | null;
67
+ permalink: string | null;
68
+ shortId: string;
69
+ readPermission: NotePermissionRole;
70
+ writePermission: NotePermissionRole;
71
+ };
72
+ export declare type SingleNote = Note & {
73
+ content: string;
74
+ };
75
+ export declare type GetMe = User;
76
+ export declare type GetUserNotes = Note[];
77
+ export declare type GetUserNote = SingleNote;
78
+ export declare type GetUserHistory = Note[];
79
+ export declare type CreateUserNote = SingleNote;
80
+ export declare type UpdateUserNote = void;
81
+ export declare type DeleteUserNote = void;
82
+ export declare type GetUserTeams = Team[];
83
+ export declare type GetTeamNotes = Note[];
84
+ export declare type CreateTeamNote = SingleNote;
85
+ export declare type UpdateTeamNote = void;
86
+ export declare type DeleteTeamNote = void;
package/dist/type.js ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var TeamVisibilityType;
4
+ (function (TeamVisibilityType) {
5
+ TeamVisibilityType["PUBLIC"] = "public";
6
+ TeamVisibilityType["PRIVATE"] = "private";
7
+ })(TeamVisibilityType = exports.TeamVisibilityType || (exports.TeamVisibilityType = {}));
8
+ var NotePublishType;
9
+ (function (NotePublishType) {
10
+ NotePublishType["EDIT"] = "edit";
11
+ NotePublishType["VIEW"] = "view";
12
+ NotePublishType["SLIDE"] = "slide";
13
+ NotePublishType["BOOK"] = "book";
14
+ })(NotePublishType = exports.NotePublishType || (exports.NotePublishType = {}));
15
+ var CommentPermissionType;
16
+ (function (CommentPermissionType) {
17
+ CommentPermissionType["DISABLED"] = "disabled";
18
+ CommentPermissionType["FORBIDDEN"] = "forbidden";
19
+ CommentPermissionType["OWNERS"] = "owners";
20
+ CommentPermissionType["SIGNED_IN_USERS"] = "signed_in_users";
21
+ CommentPermissionType["EVERYONE"] = "everyone";
22
+ })(CommentPermissionType = exports.CommentPermissionType || (exports.CommentPermissionType = {}));
23
+ var NotePermissionRole;
24
+ (function (NotePermissionRole) {
25
+ NotePermissionRole["OWNER"] = "owner";
26
+ NotePermissionRole["SIGNED_IN"] = "signed_in";
27
+ NotePermissionRole["GUEST"] = "guest";
28
+ })(NotePermissionRole = exports.NotePermissionRole || (exports.NotePermissionRole = {}));
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@hackmd/api",
3
- "version": "1.1.1",
4
- "description": "HackMD/CodiMD Node.js API Client",
3
+ "version": "2.0.0-pre.1",
4
+ "description": "HackMD Node.js API Client",
5
5
  "main": "dist/index.js",
6
6
  "declaration": "./dist/index.d.ts",
7
7
  "scripts": {
8
8
  "build": "tsc -d",
9
9
  "watch": "tsc -w",
10
- "prepublishOnly": "npm run build"
10
+ "prepublishOnly": "npm run build",
11
+ "lint": "eslint src --fix --ext .ts"
11
12
  },
12
13
  "keywords": [
13
14
  "HackMD",
@@ -18,25 +19,24 @@
18
19
  "README.md",
19
20
  "LICENSE"
20
21
  ],
21
- "author": "",
22
- "license": "ISC",
22
+ "author": {
23
+ "name": "HackMD",
24
+ "email": "support@hackmd.io",
25
+ "url": "https://hackmd.io"
26
+ },
27
+ "license": "MIT",
23
28
  "devDependencies": {
24
- "@types/cheerio": "^0.22.17",
25
- "@types/fs-extra": "^8.1.0",
26
29
  "@types/node": "^13.11.1",
27
- "@types/node-fetch": "^2.5.6",
28
- "@types/tough-cookie": "^2.3.7",
29
- "@types/tough-cookie-filestore": "^0.0.0",
30
+ "@typescript-eslint/eslint-plugin": "^5.12.0",
31
+ "eslint": "^8.9.0",
32
+ "eslint-plugin-typescript": "^0.14.0",
30
33
  "ts-node": "^8.8.2",
31
- "typescript": "^3.8.3"
34
+ "typescript": "^3.8.3",
35
+ "typescript-eslint-parser": "^22.0.0"
32
36
  },
33
37
  "dependencies": {
34
- "cheerio": "^1.0.0-rc.3",
35
- "fetch-cookie": "^0.8.0",
36
- "fs-extra": "^9.0.0",
37
- "node-fetch": "^2.6.0",
38
- "tough-cookie": "^3.0.0",
39
- "tough-cookie-filestore": "^0.0.1",
40
- "tslib": "^1.11.1"
38
+ "axios": "^0.25.0",
39
+ "path": "^0.12.7",
40
+ "tslib": "^1.14.1"
41
41
  }
42
42
  }