@tauri-apps/plugin-http 2.0.0-alpha.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/LICENSE.spdx ADDED
@@ -0,0 +1,20 @@
1
+ SPDXVersion: SPDX-2.1
2
+ DataLicense: CC0-1.0
3
+ PackageName: tauri
4
+ DataFormat: SPDXRef-1
5
+ PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
6
+ PackageHomePage: https://tauri.app
7
+ PackageLicenseDeclared: Apache-2.0
8
+ PackageLicenseDeclared: MIT
9
+ PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
10
+ PackageSummary: <text>Tauri is a rust project that enables developers to make secure
11
+ and small desktop applications using a web frontend.
12
+ </text>
13
+ PackageComment: <text>The package includes the following libraries; see
14
+ Relationship information.
15
+ </text>
16
+ Created: 2019-05-20T09:00:00Z
17
+ PackageDownloadLocation: git://github.com/tauri-apps/tauri
18
+ PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
19
+ PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
20
+ Creator: Person: Daniel Thompson-Yvetot
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # HTTP
2
+
3
+ Access the HTTP client written in Rust.
4
+
5
+ ## Install
6
+
7
+ _This plugin requires a Rust version of at least **1.65**_
8
+
9
+ There are three general methods of installation that we can recommend.
10
+
11
+ 1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
12
+ 2. Pull sources directly from Github using git tags / revision hashes (most secure)
13
+ 3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
14
+
15
+ Install the Core plugin by adding the following to your `Cargo.toml` file:
16
+
17
+ `src-tauri/Cargo.toml`
18
+
19
+ ```toml
20
+ [dependencies]
21
+ tauri-plugin-http = "2.0.0-alpha"
22
+ # alternatively with Git:
23
+ tauri-plugin-http = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
24
+ ```
25
+
26
+ You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
27
+
28
+ > Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
29
+
30
+ ```sh
31
+ pnpm add @tauri-apps/plugin-http
32
+ # or
33
+ npm add @tauri-apps/plugin-http
34
+ # or
35
+ yarn add @tauri-apps/plugin-http
36
+
37
+ # alternatively with Git:
38
+ pnpm add https://github.com/tauri-apps/tauri-plugin-http#v2
39
+ # or
40
+ npm add https://github.com/tauri-apps/tauri-plugin-http#v2
41
+ # or
42
+ yarn add https://github.com/tauri-apps/tauri-plugin-http#v2
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ First you need to register the core plugin with Tauri:
48
+
49
+ `src-tauri/src/main.rs`
50
+
51
+ ```rust
52
+ fn main() {
53
+ tauri::Builder::default()
54
+ .plugin(tauri_plugin_http::init())
55
+ .run(tauri::generate_context!())
56
+ .expect("error while running tauri application");
57
+ }
58
+ ```
59
+
60
+ Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
61
+
62
+ ```javascript
63
+ import { fetch } from "@tauri-apps/plugin-http";
64
+ const response = await fetch("http://localhost:3003/users/2", {
65
+ method: "GET",
66
+ timeout: 30,
67
+ });
68
+ ```
69
+
70
+ ## Contributing
71
+
72
+ PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
73
+
74
+ ## License
75
+
76
+ Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
77
+
78
+ MIT or MIT/Apache 2.0 where applicable.
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Access the HTTP client written in Rust.
3
+ *
4
+ * ## Security
5
+ *
6
+ * This API has a scope configuration that forces you to restrict the URLs and paths that can be accessed using glob patterns.
7
+ *
8
+ * For instance, this scope configuration only allows making HTTP requests to the GitHub API for the `tauri-apps` organization:
9
+ * ```json
10
+ * {
11
+ * "plugins": {
12
+ * "http": {
13
+ * "scope": ["https://api.github.com/repos/tauri-apps/*"]
14
+ * }
15
+ * }
16
+ * }
17
+ * ```
18
+ * Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
19
+ *
20
+ * @module
21
+ */
22
+ declare global {
23
+ interface Window {
24
+ __TAURI_INVOKE__: <T>(cmd: string, args?: unknown) => Promise<T>;
25
+ }
26
+ }
27
+ /**
28
+ * @since 2.0.0
29
+ */
30
+ interface Duration {
31
+ secs: number;
32
+ nanos: number;
33
+ }
34
+ /**
35
+ * @since 2.0.0
36
+ */
37
+ interface ClientOptions {
38
+ /**
39
+ * Defines the maximum number of redirects the client should follow.
40
+ * If set to 0, no redirects will be followed.
41
+ */
42
+ maxRedirections?: number;
43
+ connectTimeout?: number | Duration;
44
+ }
45
+ /**
46
+ * @since 2.0.0
47
+ */
48
+ declare enum ResponseType {
49
+ JSON = 1,
50
+ Text = 2,
51
+ Binary = 3
52
+ }
53
+ /**
54
+ * @since 2.0.0
55
+ */
56
+ interface FilePart<T> {
57
+ file: string | T;
58
+ mime?: string;
59
+ fileName?: string;
60
+ }
61
+ type Part = string | Uint8Array | FilePart<Uint8Array>;
62
+ /**
63
+ * The body object to be used on POST and PUT requests.
64
+ *
65
+ * @since 2.0.0
66
+ */
67
+ declare class Body {
68
+ type: string;
69
+ payload: unknown;
70
+ /** @ignore */
71
+ private constructor();
72
+ /**
73
+ * Creates a new form data body. The form data is an object where each key is the entry name,
74
+ * and the value is either a string or a file object.
75
+ *
76
+ * By default it sets the `application/x-www-form-urlencoded` Content-Type header,
77
+ * but you can set it to `multipart/form-data` if the Cargo feature `multipart` is enabled.
78
+ *
79
+ * Note that a file path must be allowed in the `fs` scope.
80
+ * @example
81
+ * ```typescript
82
+ * import { Body } from "@tauri-apps/plugin-http"
83
+ * const body = Body.form({
84
+ * key: 'value',
85
+ * image: {
86
+ * file: '/path/to/file', // either a path or an array buffer of the file contents
87
+ * mime: 'image/jpeg', // optional
88
+ * fileName: 'image.jpg' // optional
89
+ * }
90
+ * });
91
+ *
92
+ * // alternatively, use a FormData:
93
+ * const form = new FormData();
94
+ * form.append('key', 'value');
95
+ * form.append('image', file, 'image.png');
96
+ * const formBody = Body.form(form);
97
+ * ```
98
+ *
99
+ * @param data The body data.
100
+ *
101
+ * @returns The body object ready to be used on the POST and PUT requests.
102
+ *
103
+ * @since 2.0.0
104
+ */
105
+ static form(data: Record<string, Part> | FormData): Body;
106
+ /**
107
+ * Creates a new JSON body.
108
+ * @example
109
+ * ```typescript
110
+ * import { Body } from "@tauri-apps/plugin-http"
111
+ * Body.json({
112
+ * registered: true,
113
+ * name: 'tauri'
114
+ * });
115
+ * ```
116
+ *
117
+ * @param data The body JSON object.
118
+ *
119
+ * @returns The body object ready to be used on the POST and PUT requests.
120
+ *
121
+ * @since 2.0.0
122
+ */
123
+ static json<K extends string | number | symbol, V>(data: Record<K, V>): Body;
124
+ /**
125
+ * Creates a new UTF-8 string body.
126
+ * @example
127
+ * ```typescript
128
+ * import { Body } from "@tauri-apps/plugin-http"
129
+ * Body.text('The body content as a string');
130
+ * ```
131
+ *
132
+ * @param value The body string.
133
+ *
134
+ * @returns The body object ready to be used on the POST and PUT requests.
135
+ *
136
+ * @since 2.0.0
137
+ */
138
+ static text(value: string): Body;
139
+ /**
140
+ * Creates a new byte array body.
141
+ * @example
142
+ * ```typescript
143
+ * import { Body } from "@tauri-apps/plugin-http"
144
+ * Body.bytes(new Uint8Array([1, 2, 3]));
145
+ * ```
146
+ *
147
+ * @param bytes The body byte array.
148
+ *
149
+ * @returns The body object ready to be used on the POST and PUT requests.
150
+ *
151
+ * @since 2.0.0
152
+ */
153
+ static bytes(bytes: Iterable<number> | ArrayLike<number> | ArrayBuffer): Body;
154
+ }
155
+ /** The request HTTP verb. */
156
+ type HttpVerb = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "CONNECT" | "TRACE";
157
+ /**
158
+ * Options object sent to the backend.
159
+ *
160
+ * @since 2.0.0
161
+ */
162
+ interface HttpOptions {
163
+ method: HttpVerb;
164
+ url: string;
165
+ headers?: Record<string, unknown>;
166
+ query?: Record<string, unknown>;
167
+ body?: Body;
168
+ timeout?: number | Duration;
169
+ responseType?: ResponseType;
170
+ }
171
+ /** Request options. */
172
+ type RequestOptions = Omit<HttpOptions, "method" | "url">;
173
+ /** Options for the `fetch` API. */
174
+ type FetchOptions = Omit<HttpOptions, "url">;
175
+ /** @ignore */
176
+ interface IResponse<T> {
177
+ url: string;
178
+ status: number;
179
+ headers: Record<string, string>;
180
+ rawHeaders: Record<string, string[]>;
181
+ data: T;
182
+ }
183
+ /**
184
+ * Response object.
185
+ *
186
+ * @since 2.0.0
187
+ * */
188
+ declare class Response<T> {
189
+ /** The request URL. */
190
+ url: string;
191
+ /** The response status code. */
192
+ status: number;
193
+ /** A boolean indicating whether the response was successful (status in the range 200–299) or not. */
194
+ ok: boolean;
195
+ /** The response headers. */
196
+ headers: Record<string, string>;
197
+ /** The response raw headers. */
198
+ rawHeaders: Record<string, string[]>;
199
+ /** The response data. */
200
+ data: T;
201
+ /** @ignore */
202
+ constructor(response: IResponse<T>);
203
+ }
204
+ /**
205
+ * @since 2.0.0
206
+ */
207
+ declare class Client {
208
+ id: number;
209
+ /** @ignore */
210
+ constructor(id: number);
211
+ /**
212
+ * Drops the client instance.
213
+ * @example
214
+ * ```typescript
215
+ * import { getClient } from '@tauri-apps/plugin-http';
216
+ * const client = await getClient();
217
+ * await client.drop();
218
+ * ```
219
+ */
220
+ drop(): Promise<void>;
221
+ /**
222
+ * Makes an HTTP request.
223
+ * @example
224
+ * ```typescript
225
+ * import { getClient } from '@tauri-apps/plugin-http';
226
+ * const client = await getClient();
227
+ * const response = await client.request({
228
+ * method: 'GET',
229
+ * url: 'http://localhost:3003/users',
230
+ * });
231
+ * ```
232
+ */
233
+ request<T>(options: HttpOptions): Promise<Response<T>>;
234
+ /**
235
+ * Makes a GET request.
236
+ * @example
237
+ * ```typescript
238
+ * import { getClient, ResponseType } from '@tauri-apps/plugin-http';
239
+ * const client = await getClient();
240
+ * const response = await client.get('http://localhost:3003/users', {
241
+ * timeout: 30,
242
+ * // the expected response type
243
+ * responseType: ResponseType.JSON
244
+ * });
245
+ * ```
246
+ */
247
+ get<T>(url: string, options?: RequestOptions): Promise<Response<T>>;
248
+ /**
249
+ * Makes a POST request.
250
+ * @example
251
+ * ```typescript
252
+ * import { getClient, Body, ResponseType } from '@tauri-apps/plugin-http';
253
+ * const client = await getClient();
254
+ * const response = await client.post('http://localhost:3003/users', {
255
+ * body: Body.json({
256
+ * name: 'tauri',
257
+ * password: 'awesome'
258
+ * }),
259
+ * // in this case the server returns a simple string
260
+ * responseType: ResponseType.Text,
261
+ * });
262
+ * ```
263
+ */
264
+ post<T>(url: string, body?: Body, options?: RequestOptions): Promise<Response<T>>;
265
+ /**
266
+ * Makes a PUT request.
267
+ * @example
268
+ * ```typescript
269
+ * import { getClient, Body } from '@tauri-apps/plugin-http';
270
+ * const client = await getClient();
271
+ * const response = await client.put('http://localhost:3003/users/1', {
272
+ * body: Body.form({
273
+ * file: {
274
+ * file: '/home/tauri/avatar.png',
275
+ * mime: 'image/png',
276
+ * fileName: 'avatar.png'
277
+ * }
278
+ * })
279
+ * });
280
+ * ```
281
+ */
282
+ put<T>(url: string, body?: Body, options?: RequestOptions): Promise<Response<T>>;
283
+ /**
284
+ * Makes a PATCH request.
285
+ * @example
286
+ * ```typescript
287
+ * import { getClient, Body } from '@tauri-apps/plugin-http';
288
+ * const client = await getClient();
289
+ * const response = await client.patch('http://localhost:3003/users/1', {
290
+ * body: Body.json({ email: 'contact@tauri.app' })
291
+ * });
292
+ * ```
293
+ */
294
+ patch<T>(url: string, options?: RequestOptions): Promise<Response<T>>;
295
+ /**
296
+ * Makes a DELETE request.
297
+ * @example
298
+ * ```typescript
299
+ * import { getClient } from '@tauri-apps/plugin-http';
300
+ * const client = await getClient();
301
+ * const response = await client.delete('http://localhost:3003/users/1');
302
+ * ```
303
+ */
304
+ delete<T>(url: string, options?: RequestOptions): Promise<Response<T>>;
305
+ }
306
+ /**
307
+ * Creates a new client using the specified options.
308
+ * @example
309
+ * ```typescript
310
+ * import { getClient } from '@tauri-apps/plugin-http';
311
+ * const client = await getClient();
312
+ * ```
313
+ *
314
+ * @param options Client configuration.
315
+ *
316
+ * @returns A promise resolving to the client instance.
317
+ *
318
+ * @since 2.0.0
319
+ */
320
+ declare function getClient(options?: ClientOptions): Promise<Client>;
321
+ /**
322
+ * Perform an HTTP request using the default client.
323
+ * @example
324
+ * ```typescript
325
+ * import { fetch } from '@tauri-apps/plugin-http';
326
+ * const response = await fetch('http://localhost:3003/users/2', {
327
+ * method: 'GET',
328
+ * timeout: 30,
329
+ * });
330
+ * ```
331
+ */
332
+ declare function fetch<T>(url: string, options?: FetchOptions): Promise<Response<T>>;
333
+ export type { Duration, ClientOptions, Part, HttpVerb, HttpOptions, RequestOptions, FetchOptions, };
334
+ export { getClient, fetch, Body, Client, Response, ResponseType, type FilePart, };
@@ -0,0 +1,381 @@
1
+ // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // SPDX-License-Identifier: MIT
4
+ /**
5
+ * @since 2.0.0
6
+ */
7
+ var ResponseType;
8
+ (function (ResponseType) {
9
+ ResponseType[ResponseType["JSON"] = 1] = "JSON";
10
+ ResponseType[ResponseType["Text"] = 2] = "Text";
11
+ ResponseType[ResponseType["Binary"] = 3] = "Binary";
12
+ })(ResponseType || (ResponseType = {}));
13
+ /**
14
+ * The body object to be used on POST and PUT requests.
15
+ *
16
+ * @since 2.0.0
17
+ */
18
+ class Body {
19
+ /** @ignore */
20
+ constructor(type, payload) {
21
+ this.type = type;
22
+ this.payload = payload;
23
+ }
24
+ /**
25
+ * Creates a new form data body. The form data is an object where each key is the entry name,
26
+ * and the value is either a string or a file object.
27
+ *
28
+ * By default it sets the `application/x-www-form-urlencoded` Content-Type header,
29
+ * but you can set it to `multipart/form-data` if the Cargo feature `multipart` is enabled.
30
+ *
31
+ * Note that a file path must be allowed in the `fs` scope.
32
+ * @example
33
+ * ```typescript
34
+ * import { Body } from "@tauri-apps/plugin-http"
35
+ * const body = Body.form({
36
+ * key: 'value',
37
+ * image: {
38
+ * file: '/path/to/file', // either a path or an array buffer of the file contents
39
+ * mime: 'image/jpeg', // optional
40
+ * fileName: 'image.jpg' // optional
41
+ * }
42
+ * });
43
+ *
44
+ * // alternatively, use a FormData:
45
+ * const form = new FormData();
46
+ * form.append('key', 'value');
47
+ * form.append('image', file, 'image.png');
48
+ * const formBody = Body.form(form);
49
+ * ```
50
+ *
51
+ * @param data The body data.
52
+ *
53
+ * @returns The body object ready to be used on the POST and PUT requests.
54
+ *
55
+ * @since 2.0.0
56
+ */
57
+ static form(data) {
58
+ const form = {};
59
+ const append = (key, v) => {
60
+ if (v !== null) {
61
+ let r;
62
+ if (typeof v === "string") {
63
+ r = v;
64
+ }
65
+ else if (v instanceof Uint8Array || Array.isArray(v)) {
66
+ r = Array.from(v);
67
+ }
68
+ else if (v instanceof File) {
69
+ r = { file: v.name, mime: v.type, fileName: v.name };
70
+ }
71
+ else if (typeof v.file === "string") {
72
+ r = { file: v.file, mime: v.mime, fileName: v.fileName };
73
+ }
74
+ else {
75
+ r = { file: Array.from(v.file), mime: v.mime, fileName: v.fileName };
76
+ }
77
+ form[String(key)] = r;
78
+ }
79
+ };
80
+ if (data instanceof FormData) {
81
+ for (const [key, value] of data) {
82
+ append(key, value);
83
+ }
84
+ }
85
+ else {
86
+ for (const [key, value] of Object.entries(data)) {
87
+ append(key, value);
88
+ }
89
+ }
90
+ return new Body("Form", form);
91
+ }
92
+ /**
93
+ * Creates a new JSON body.
94
+ * @example
95
+ * ```typescript
96
+ * import { Body } from "@tauri-apps/plugin-http"
97
+ * Body.json({
98
+ * registered: true,
99
+ * name: 'tauri'
100
+ * });
101
+ * ```
102
+ *
103
+ * @param data The body JSON object.
104
+ *
105
+ * @returns The body object ready to be used on the POST and PUT requests.
106
+ *
107
+ * @since 2.0.0
108
+ */
109
+ static json(data) {
110
+ return new Body("Json", data);
111
+ }
112
+ /**
113
+ * Creates a new UTF-8 string body.
114
+ * @example
115
+ * ```typescript
116
+ * import { Body } from "@tauri-apps/plugin-http"
117
+ * Body.text('The body content as a string');
118
+ * ```
119
+ *
120
+ * @param value The body string.
121
+ *
122
+ * @returns The body object ready to be used on the POST and PUT requests.
123
+ *
124
+ * @since 2.0.0
125
+ */
126
+ static text(value) {
127
+ return new Body("Text", value);
128
+ }
129
+ /**
130
+ * Creates a new byte array body.
131
+ * @example
132
+ * ```typescript
133
+ * import { Body } from "@tauri-apps/plugin-http"
134
+ * Body.bytes(new Uint8Array([1, 2, 3]));
135
+ * ```
136
+ *
137
+ * @param bytes The body byte array.
138
+ *
139
+ * @returns The body object ready to be used on the POST and PUT requests.
140
+ *
141
+ * @since 2.0.0
142
+ */
143
+ static bytes(bytes) {
144
+ // stringifying Uint8Array doesn't return an array of numbers, so we create one here
145
+ return new Body("Bytes", Array.from(bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : bytes));
146
+ }
147
+ }
148
+ /**
149
+ * Response object.
150
+ *
151
+ * @since 2.0.0
152
+ * */
153
+ class Response {
154
+ /** @ignore */
155
+ constructor(response) {
156
+ this.url = response.url;
157
+ this.status = response.status;
158
+ this.ok = this.status >= 200 && this.status < 300;
159
+ this.headers = response.headers;
160
+ this.rawHeaders = response.rawHeaders;
161
+ this.data = response.data;
162
+ }
163
+ }
164
+ /**
165
+ * @since 2.0.0
166
+ */
167
+ class Client {
168
+ /** @ignore */
169
+ constructor(id) {
170
+ this.id = id;
171
+ }
172
+ /**
173
+ * Drops the client instance.
174
+ * @example
175
+ * ```typescript
176
+ * import { getClient } from '@tauri-apps/plugin-http';
177
+ * const client = await getClient();
178
+ * await client.drop();
179
+ * ```
180
+ */
181
+ async drop() {
182
+ return window.__TAURI_INVOKE__("plugin:http|drop_client", {
183
+ client: this.id,
184
+ });
185
+ }
186
+ /**
187
+ * Makes an HTTP request.
188
+ * @example
189
+ * ```typescript
190
+ * import { getClient } from '@tauri-apps/plugin-http';
191
+ * const client = await getClient();
192
+ * const response = await client.request({
193
+ * method: 'GET',
194
+ * url: 'http://localhost:3003/users',
195
+ * });
196
+ * ```
197
+ */
198
+ async request(options) {
199
+ const jsonResponse = !options.responseType || options.responseType === ResponseType.JSON;
200
+ if (jsonResponse) {
201
+ options.responseType = ResponseType.Text;
202
+ }
203
+ return window
204
+ .__TAURI_INVOKE__("plugin:http|request", {
205
+ clientId: this.id,
206
+ options,
207
+ })
208
+ .then((res) => {
209
+ const response = new Response(res);
210
+ if (jsonResponse) {
211
+ /* eslint-disable */
212
+ try {
213
+ response.data = JSON.parse(response.data);
214
+ }
215
+ catch (e) {
216
+ if (response.ok && response.data === "") {
217
+ response.data = {};
218
+ }
219
+ else if (response.ok) {
220
+ throw Error(`Failed to parse response \`${response.data}\` as JSON: ${e};
221
+ try setting the \`responseType\` option to \`ResponseType.Text\` or \`ResponseType.Binary\` if the API does not return a JSON response.`);
222
+ }
223
+ }
224
+ /* eslint-enable */
225
+ return response;
226
+ }
227
+ return response;
228
+ });
229
+ }
230
+ /**
231
+ * Makes a GET request.
232
+ * @example
233
+ * ```typescript
234
+ * import { getClient, ResponseType } from '@tauri-apps/plugin-http';
235
+ * const client = await getClient();
236
+ * const response = await client.get('http://localhost:3003/users', {
237
+ * timeout: 30,
238
+ * // the expected response type
239
+ * responseType: ResponseType.JSON
240
+ * });
241
+ * ```
242
+ */
243
+ async get(url, options) {
244
+ return this.request({
245
+ method: "GET",
246
+ url,
247
+ ...options,
248
+ });
249
+ }
250
+ /**
251
+ * Makes a POST request.
252
+ * @example
253
+ * ```typescript
254
+ * import { getClient, Body, ResponseType } from '@tauri-apps/plugin-http';
255
+ * const client = await getClient();
256
+ * const response = await client.post('http://localhost:3003/users', {
257
+ * body: Body.json({
258
+ * name: 'tauri',
259
+ * password: 'awesome'
260
+ * }),
261
+ * // in this case the server returns a simple string
262
+ * responseType: ResponseType.Text,
263
+ * });
264
+ * ```
265
+ */
266
+ async post(url, body, options) {
267
+ return this.request({
268
+ method: "POST",
269
+ url,
270
+ body,
271
+ ...options,
272
+ });
273
+ }
274
+ /**
275
+ * Makes a PUT request.
276
+ * @example
277
+ * ```typescript
278
+ * import { getClient, Body } from '@tauri-apps/plugin-http';
279
+ * const client = await getClient();
280
+ * const response = await client.put('http://localhost:3003/users/1', {
281
+ * body: Body.form({
282
+ * file: {
283
+ * file: '/home/tauri/avatar.png',
284
+ * mime: 'image/png',
285
+ * fileName: 'avatar.png'
286
+ * }
287
+ * })
288
+ * });
289
+ * ```
290
+ */
291
+ async put(url, body, options) {
292
+ return this.request({
293
+ method: "PUT",
294
+ url,
295
+ body,
296
+ ...options,
297
+ });
298
+ }
299
+ /**
300
+ * Makes a PATCH request.
301
+ * @example
302
+ * ```typescript
303
+ * import { getClient, Body } from '@tauri-apps/plugin-http';
304
+ * const client = await getClient();
305
+ * const response = await client.patch('http://localhost:3003/users/1', {
306
+ * body: Body.json({ email: 'contact@tauri.app' })
307
+ * });
308
+ * ```
309
+ */
310
+ async patch(url, options) {
311
+ return this.request({
312
+ method: "PATCH",
313
+ url,
314
+ ...options,
315
+ });
316
+ }
317
+ /**
318
+ * Makes a DELETE request.
319
+ * @example
320
+ * ```typescript
321
+ * import { getClient } from '@tauri-apps/plugin-http';
322
+ * const client = await getClient();
323
+ * const response = await client.delete('http://localhost:3003/users/1');
324
+ * ```
325
+ */
326
+ async delete(url, options) {
327
+ return this.request({
328
+ method: "DELETE",
329
+ url,
330
+ ...options,
331
+ });
332
+ }
333
+ }
334
+ /**
335
+ * Creates a new client using the specified options.
336
+ * @example
337
+ * ```typescript
338
+ * import { getClient } from '@tauri-apps/plugin-http';
339
+ * const client = await getClient();
340
+ * ```
341
+ *
342
+ * @param options Client configuration.
343
+ *
344
+ * @returns A promise resolving to the client instance.
345
+ *
346
+ * @since 2.0.0
347
+ */
348
+ async function getClient(options) {
349
+ return window
350
+ .__TAURI_INVOKE__("plugin:http|create_client", {
351
+ options,
352
+ })
353
+ .then((id) => new Client(id));
354
+ }
355
+ /** @internal */
356
+ let defaultClient = null;
357
+ /**
358
+ * Perform an HTTP request using the default client.
359
+ * @example
360
+ * ```typescript
361
+ * import { fetch } from '@tauri-apps/plugin-http';
362
+ * const response = await fetch('http://localhost:3003/users/2', {
363
+ * method: 'GET',
364
+ * timeout: 30,
365
+ * });
366
+ * ```
367
+ */
368
+ async function fetch(url, options) {
369
+ var _a;
370
+ if (defaultClient === null) {
371
+ defaultClient = await getClient();
372
+ }
373
+ return defaultClient.request({
374
+ url,
375
+ method: (_a = options === null || options === void 0 ? void 0 : options.method) !== null && _a !== void 0 ? _a : "GET",
376
+ ...options,
377
+ });
378
+ }
379
+
380
+ export { Body, Client, Response, ResponseType, fetch, getClient };
381
+ //# sourceMappingURL=index.min.js.map
@@ -0,0 +1,381 @@
1
+ // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // SPDX-License-Identifier: MIT
4
+ /**
5
+ * @since 2.0.0
6
+ */
7
+ var ResponseType;
8
+ (function (ResponseType) {
9
+ ResponseType[ResponseType["JSON"] = 1] = "JSON";
10
+ ResponseType[ResponseType["Text"] = 2] = "Text";
11
+ ResponseType[ResponseType["Binary"] = 3] = "Binary";
12
+ })(ResponseType || (ResponseType = {}));
13
+ /**
14
+ * The body object to be used on POST and PUT requests.
15
+ *
16
+ * @since 2.0.0
17
+ */
18
+ class Body {
19
+ /** @ignore */
20
+ constructor(type, payload) {
21
+ this.type = type;
22
+ this.payload = payload;
23
+ }
24
+ /**
25
+ * Creates a new form data body. The form data is an object where each key is the entry name,
26
+ * and the value is either a string or a file object.
27
+ *
28
+ * By default it sets the `application/x-www-form-urlencoded` Content-Type header,
29
+ * but you can set it to `multipart/form-data` if the Cargo feature `multipart` is enabled.
30
+ *
31
+ * Note that a file path must be allowed in the `fs` scope.
32
+ * @example
33
+ * ```typescript
34
+ * import { Body } from "@tauri-apps/plugin-http"
35
+ * const body = Body.form({
36
+ * key: 'value',
37
+ * image: {
38
+ * file: '/path/to/file', // either a path or an array buffer of the file contents
39
+ * mime: 'image/jpeg', // optional
40
+ * fileName: 'image.jpg' // optional
41
+ * }
42
+ * });
43
+ *
44
+ * // alternatively, use a FormData:
45
+ * const form = new FormData();
46
+ * form.append('key', 'value');
47
+ * form.append('image', file, 'image.png');
48
+ * const formBody = Body.form(form);
49
+ * ```
50
+ *
51
+ * @param data The body data.
52
+ *
53
+ * @returns The body object ready to be used on the POST and PUT requests.
54
+ *
55
+ * @since 2.0.0
56
+ */
57
+ static form(data) {
58
+ const form = {};
59
+ const append = (key, v) => {
60
+ if (v !== null) {
61
+ let r;
62
+ if (typeof v === "string") {
63
+ r = v;
64
+ }
65
+ else if (v instanceof Uint8Array || Array.isArray(v)) {
66
+ r = Array.from(v);
67
+ }
68
+ else if (v instanceof File) {
69
+ r = { file: v.name, mime: v.type, fileName: v.name };
70
+ }
71
+ else if (typeof v.file === "string") {
72
+ r = { file: v.file, mime: v.mime, fileName: v.fileName };
73
+ }
74
+ else {
75
+ r = { file: Array.from(v.file), mime: v.mime, fileName: v.fileName };
76
+ }
77
+ form[String(key)] = r;
78
+ }
79
+ };
80
+ if (data instanceof FormData) {
81
+ for (const [key, value] of data) {
82
+ append(key, value);
83
+ }
84
+ }
85
+ else {
86
+ for (const [key, value] of Object.entries(data)) {
87
+ append(key, value);
88
+ }
89
+ }
90
+ return new Body("Form", form);
91
+ }
92
+ /**
93
+ * Creates a new JSON body.
94
+ * @example
95
+ * ```typescript
96
+ * import { Body } from "@tauri-apps/plugin-http"
97
+ * Body.json({
98
+ * registered: true,
99
+ * name: 'tauri'
100
+ * });
101
+ * ```
102
+ *
103
+ * @param data The body JSON object.
104
+ *
105
+ * @returns The body object ready to be used on the POST and PUT requests.
106
+ *
107
+ * @since 2.0.0
108
+ */
109
+ static json(data) {
110
+ return new Body("Json", data);
111
+ }
112
+ /**
113
+ * Creates a new UTF-8 string body.
114
+ * @example
115
+ * ```typescript
116
+ * import { Body } from "@tauri-apps/plugin-http"
117
+ * Body.text('The body content as a string');
118
+ * ```
119
+ *
120
+ * @param value The body string.
121
+ *
122
+ * @returns The body object ready to be used on the POST and PUT requests.
123
+ *
124
+ * @since 2.0.0
125
+ */
126
+ static text(value) {
127
+ return new Body("Text", value);
128
+ }
129
+ /**
130
+ * Creates a new byte array body.
131
+ * @example
132
+ * ```typescript
133
+ * import { Body } from "@tauri-apps/plugin-http"
134
+ * Body.bytes(new Uint8Array([1, 2, 3]));
135
+ * ```
136
+ *
137
+ * @param bytes The body byte array.
138
+ *
139
+ * @returns The body object ready to be used on the POST and PUT requests.
140
+ *
141
+ * @since 2.0.0
142
+ */
143
+ static bytes(bytes) {
144
+ // stringifying Uint8Array doesn't return an array of numbers, so we create one here
145
+ return new Body("Bytes", Array.from(bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : bytes));
146
+ }
147
+ }
148
+ /**
149
+ * Response object.
150
+ *
151
+ * @since 2.0.0
152
+ * */
153
+ class Response {
154
+ /** @ignore */
155
+ constructor(response) {
156
+ this.url = response.url;
157
+ this.status = response.status;
158
+ this.ok = this.status >= 200 && this.status < 300;
159
+ this.headers = response.headers;
160
+ this.rawHeaders = response.rawHeaders;
161
+ this.data = response.data;
162
+ }
163
+ }
164
+ /**
165
+ * @since 2.0.0
166
+ */
167
+ class Client {
168
+ /** @ignore */
169
+ constructor(id) {
170
+ this.id = id;
171
+ }
172
+ /**
173
+ * Drops the client instance.
174
+ * @example
175
+ * ```typescript
176
+ * import { getClient } from '@tauri-apps/plugin-http';
177
+ * const client = await getClient();
178
+ * await client.drop();
179
+ * ```
180
+ */
181
+ async drop() {
182
+ return window.__TAURI_INVOKE__("plugin:http|drop_client", {
183
+ client: this.id,
184
+ });
185
+ }
186
+ /**
187
+ * Makes an HTTP request.
188
+ * @example
189
+ * ```typescript
190
+ * import { getClient } from '@tauri-apps/plugin-http';
191
+ * const client = await getClient();
192
+ * const response = await client.request({
193
+ * method: 'GET',
194
+ * url: 'http://localhost:3003/users',
195
+ * });
196
+ * ```
197
+ */
198
+ async request(options) {
199
+ const jsonResponse = !options.responseType || options.responseType === ResponseType.JSON;
200
+ if (jsonResponse) {
201
+ options.responseType = ResponseType.Text;
202
+ }
203
+ return window
204
+ .__TAURI_INVOKE__("plugin:http|request", {
205
+ clientId: this.id,
206
+ options,
207
+ })
208
+ .then((res) => {
209
+ const response = new Response(res);
210
+ if (jsonResponse) {
211
+ /* eslint-disable */
212
+ try {
213
+ response.data = JSON.parse(response.data);
214
+ }
215
+ catch (e) {
216
+ if (response.ok && response.data === "") {
217
+ response.data = {};
218
+ }
219
+ else if (response.ok) {
220
+ throw Error(`Failed to parse response \`${response.data}\` as JSON: ${e};
221
+ try setting the \`responseType\` option to \`ResponseType.Text\` or \`ResponseType.Binary\` if the API does not return a JSON response.`);
222
+ }
223
+ }
224
+ /* eslint-enable */
225
+ return response;
226
+ }
227
+ return response;
228
+ });
229
+ }
230
+ /**
231
+ * Makes a GET request.
232
+ * @example
233
+ * ```typescript
234
+ * import { getClient, ResponseType } from '@tauri-apps/plugin-http';
235
+ * const client = await getClient();
236
+ * const response = await client.get('http://localhost:3003/users', {
237
+ * timeout: 30,
238
+ * // the expected response type
239
+ * responseType: ResponseType.JSON
240
+ * });
241
+ * ```
242
+ */
243
+ async get(url, options) {
244
+ return this.request({
245
+ method: "GET",
246
+ url,
247
+ ...options,
248
+ });
249
+ }
250
+ /**
251
+ * Makes a POST request.
252
+ * @example
253
+ * ```typescript
254
+ * import { getClient, Body, ResponseType } from '@tauri-apps/plugin-http';
255
+ * const client = await getClient();
256
+ * const response = await client.post('http://localhost:3003/users', {
257
+ * body: Body.json({
258
+ * name: 'tauri',
259
+ * password: 'awesome'
260
+ * }),
261
+ * // in this case the server returns a simple string
262
+ * responseType: ResponseType.Text,
263
+ * });
264
+ * ```
265
+ */
266
+ async post(url, body, options) {
267
+ return this.request({
268
+ method: "POST",
269
+ url,
270
+ body,
271
+ ...options,
272
+ });
273
+ }
274
+ /**
275
+ * Makes a PUT request.
276
+ * @example
277
+ * ```typescript
278
+ * import { getClient, Body } from '@tauri-apps/plugin-http';
279
+ * const client = await getClient();
280
+ * const response = await client.put('http://localhost:3003/users/1', {
281
+ * body: Body.form({
282
+ * file: {
283
+ * file: '/home/tauri/avatar.png',
284
+ * mime: 'image/png',
285
+ * fileName: 'avatar.png'
286
+ * }
287
+ * })
288
+ * });
289
+ * ```
290
+ */
291
+ async put(url, body, options) {
292
+ return this.request({
293
+ method: "PUT",
294
+ url,
295
+ body,
296
+ ...options,
297
+ });
298
+ }
299
+ /**
300
+ * Makes a PATCH request.
301
+ * @example
302
+ * ```typescript
303
+ * import { getClient, Body } from '@tauri-apps/plugin-http';
304
+ * const client = await getClient();
305
+ * const response = await client.patch('http://localhost:3003/users/1', {
306
+ * body: Body.json({ email: 'contact@tauri.app' })
307
+ * });
308
+ * ```
309
+ */
310
+ async patch(url, options) {
311
+ return this.request({
312
+ method: "PATCH",
313
+ url,
314
+ ...options,
315
+ });
316
+ }
317
+ /**
318
+ * Makes a DELETE request.
319
+ * @example
320
+ * ```typescript
321
+ * import { getClient } from '@tauri-apps/plugin-http';
322
+ * const client = await getClient();
323
+ * const response = await client.delete('http://localhost:3003/users/1');
324
+ * ```
325
+ */
326
+ async delete(url, options) {
327
+ return this.request({
328
+ method: "DELETE",
329
+ url,
330
+ ...options,
331
+ });
332
+ }
333
+ }
334
+ /**
335
+ * Creates a new client using the specified options.
336
+ * @example
337
+ * ```typescript
338
+ * import { getClient } from '@tauri-apps/plugin-http';
339
+ * const client = await getClient();
340
+ * ```
341
+ *
342
+ * @param options Client configuration.
343
+ *
344
+ * @returns A promise resolving to the client instance.
345
+ *
346
+ * @since 2.0.0
347
+ */
348
+ async function getClient(options) {
349
+ return window
350
+ .__TAURI_INVOKE__("plugin:http|create_client", {
351
+ options,
352
+ })
353
+ .then((id) => new Client(id));
354
+ }
355
+ /** @internal */
356
+ let defaultClient = null;
357
+ /**
358
+ * Perform an HTTP request using the default client.
359
+ * @example
360
+ * ```typescript
361
+ * import { fetch } from '@tauri-apps/plugin-http';
362
+ * const response = await fetch('http://localhost:3003/users/2', {
363
+ * method: 'GET',
364
+ * timeout: 30,
365
+ * });
366
+ * ```
367
+ */
368
+ async function fetch(url, options) {
369
+ var _a;
370
+ if (defaultClient === null) {
371
+ defaultClient = await getClient();
372
+ }
373
+ return defaultClient.request({
374
+ url,
375
+ method: (_a = options === null || options === void 0 ? void 0 : options.method) !== null && _a !== void 0 ? _a : "GET",
376
+ ...options,
377
+ });
378
+ }
379
+
380
+ export { Body, Client, Response, ResponseType, fetch, getClient };
381
+ //# sourceMappingURL=index.mjs.map
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@tauri-apps/plugin-http",
3
+ "version": "2.0.0-alpha.0",
4
+ "license": "MIT or APACHE-2.0",
5
+ "authors": [
6
+ "Tauri Programme within The Commons Conservancy"
7
+ ],
8
+ "type": "module",
9
+ "browser": "dist-js/index.min.js",
10
+ "module": "dist-js/index.mjs",
11
+ "types": "dist-js/index.d.ts",
12
+ "exports": {
13
+ "import": "./dist-js/index.mjs",
14
+ "types": "./dist-js/index.d.ts",
15
+ "browser": "./dist-js/index.min.js"
16
+ },
17
+ "files": [
18
+ "dist-js",
19
+ "!dist-js/**/*.map",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "devDependencies": {
24
+ "tslib": "^2.5.0"
25
+ },
26
+ "dependencies": {
27
+ "@tauri-apps/api": "2.0.0-alpha.4"
28
+ },
29
+ "scripts": {
30
+ "build": "rollup -c"
31
+ }
32
+ }