@pistonite/pure 0.23.1 → 0.24.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.
Files changed (2) hide show
  1. package/package.json +4 -6
  2. package/src/fs/FsSave.ts +216 -5
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pistonite/pure",
3
- "version": "0.23.1",
3
+ "version": "0.24.1",
4
4
  "type": "module",
5
5
  "description": "Pure TypeScript libraries for my projects",
6
6
  "homepage": "https://github.com/Pistonite/pure",
@@ -27,12 +27,10 @@
27
27
  "directory": "packages/pure"
28
28
  },
29
29
  "dependencies": {
30
- "denque": "2.1.0",
31
- "file-saver": "2.0.5"
30
+ "denque": "2.1.0"
32
31
  },
33
32
  "devDependencies": {
34
- "@types/file-saver": "^2.0.7",
35
- "vitest": "^3.0.5",
36
- "mono-dev": "0.0.0"
33
+ "vitest": "^3.0.9",
34
+ "mono-dev": "0.1.0"
37
35
  }
38
36
  }
package/src/fs/FsSave.ts CHANGED
@@ -1,12 +1,223 @@
1
- // workaround for CommonJS
2
- import pkg from "file-saver";
3
- const { saveAs } = pkg;
1
+ import { fsFail, type FsVoid } from "./FsError.ts";
4
2
 
5
3
  /** Save (download) a file using Blob */
6
- export function fsSave(content: string | Uint8Array, filename: string) {
4
+ export function fsSave(content: string | Uint8Array, filename: string): FsVoid {
7
5
  const blob = new Blob([content], {
8
6
  // maybe lying, but should be fine
9
7
  type: "text/plain;charset=utf-8",
10
8
  });
11
- saveAs(blob, filename);
9
+
10
+ try {
11
+ saveAs(blob, filename);
12
+ return {};
13
+ } catch (e) {
14
+ console.error(e);
15
+ return { err: fsFail("save failed") };
16
+ }
12
17
  }
18
+
19
+ // The following code is adopted from
20
+ // - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/file-saver/index.d.ts
21
+ // under this MIT license:
22
+ /*
23
+ This project is licensed under the MIT license.
24
+ Copyrights are respective of each contributor listed at the beginning of each definition file.
25
+
26
+ 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:
27
+
28
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
29
+
30
+ 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.
31
+ */
32
+
33
+ type SaveAsFn = (
34
+ data: Blob | string,
35
+ filename?: string,
36
+ options?: SaveAsFnOptions,
37
+ ) => void;
38
+ type SaveAsFnOptions = {
39
+ autoBom: boolean;
40
+ };
41
+
42
+ /* eslint-disable @typescript-eslint/no-explicit-any */
43
+
44
+ // The following code is vendored from
45
+ // - https://github.com/eligrey/FileSaver.js/blob/master/src/FileSaver.js
46
+ // under this MIT license:
47
+ /*
48
+ * FileSaver.js
49
+ * A saveAs() FileSaver implementation.
50
+ *
51
+ * By Eli Grey, http://eligrey.com
52
+ *
53
+ * License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT)
54
+ * source : http://purl.eligrey.com/github/FileSaver.js
55
+ */
56
+
57
+ // adoption note: this is now ECMA standard - https://github.com/tc39/proposal-global
58
+ // The one and only way of getting global scope in all environments
59
+ // https://stackoverflow.com/q/3277182/1008999
60
+ // const _global =
61
+ // typeof window === "object" && window.window === window
62
+ // ? window
63
+ // : typeof self === "object" && self.self === self
64
+ // ? self
65
+ // : typeof global === "object" && global.global === global
66
+ // ? global
67
+ // : this;
68
+
69
+ const download = (url: string | URL, name?: string, opts?: SaveAsFnOptions) => {
70
+ const xhr = new XMLHttpRequest();
71
+ xhr.open("GET", url);
72
+ xhr.responseType = "blob";
73
+ xhr.onload = function () {
74
+ saveAs(xhr.response, name, opts);
75
+ };
76
+ xhr.onerror = function () {
77
+ console.error("could not download file");
78
+ };
79
+ xhr.send();
80
+ };
81
+
82
+ const corsEnabled = (url: string | URL) => {
83
+ const xhr = new XMLHttpRequest();
84
+ // use sync to avoid popup blocker
85
+ xhr.open("HEAD", url, false);
86
+ try {
87
+ xhr.send();
88
+ } catch {
89
+ // ignore
90
+ }
91
+ return xhr.status >= 200 && xhr.status <= 299;
92
+ };
93
+
94
+ // adoption note: we drop support for old browsers, and just use click()
95
+ // original note: `a.click()` doesn't work for all browsers (#465)
96
+ // const click = (node: Node) => {
97
+ // try {
98
+ // node.dispatchEvent(new MouseEvent('click'))
99
+ // } catch {
100
+ // const evt = document.createEvent('MouseEvents')
101
+ // evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80,
102
+ // 20, false, false, false, false, 0, null)
103
+ // node.dispatchEvent(evt)
104
+ // }
105
+ // }
106
+
107
+ // adoption note: converted to check at call time, no need to
108
+ // do this check at boot load
109
+ const saveAs: SaveAsFn = (blob, name?, opts?) => {
110
+ // adoption note: this is likely to throw if window is not defined.. ?
111
+ if (typeof window !== "object" || window !== globalThis) {
112
+ // probably in some web worker
113
+ return;
114
+ }
115
+ // Detect WebView inside a native macOS app by ruling out all browsers
116
+ // We just need to check for 'Safari' because all other browsers (besides Firefox) include that too
117
+ // https://www.whatismybrowser.com/guides/the-latest-user-agent/macos
118
+ const isMacOSWebView =
119
+ globalThis.navigator &&
120
+ /Macintosh/.test(navigator.userAgent) &&
121
+ /AppleWebKit/.test(navigator.userAgent) &&
122
+ !/Safari/.test(navigator.userAgent);
123
+ // adoption note: removed blob.name, and pulled this line outside
124
+ name = name || "download";
125
+
126
+ if ("download" in HTMLAnchorElement.prototype && !isMacOSWebView) {
127
+ const URL = globalThis.URL || globalThis.webkitURL;
128
+ // Namespace is used to prevent conflict w/ Chrome Poper Blocker extension (Issue #561)
129
+ const a = document.createElementNS(
130
+ "http://www.w3.org/1999/xhtml",
131
+ "a",
132
+ ) as HTMLAnchorElement;
133
+
134
+ a.download = name;
135
+ a.rel = "noopener"; // tabnabbing
136
+
137
+ // TODO: detect chrome extensions & packaged apps
138
+ // a.target = '_blank'
139
+
140
+ if (typeof blob === "string") {
141
+ // Support regular links
142
+ a.href = blob;
143
+ if (a.origin !== location.origin) {
144
+ // adoption note: removed turnery and changed click()
145
+ if (corsEnabled(a.href)) {
146
+ download(blob, name, opts);
147
+ } else {
148
+ a.target = "_blank";
149
+ a.click();
150
+ }
151
+ } else {
152
+ // adoption note: changed click()
153
+ a.click();
154
+ }
155
+ } else {
156
+ // Support blobs
157
+ a.href = URL.createObjectURL(blob);
158
+ // adoption note: not sure why 40s
159
+ setTimeout(() => {
160
+ URL.revokeObjectURL(a.href);
161
+ }, 4e4); // 40s
162
+ // adoption note: changed click()
163
+ setTimeout(() => {
164
+ a.click();
165
+ }, 0);
166
+ }
167
+ return;
168
+ }
169
+
170
+ // adoption note: drop IE support
171
+
172
+ // Fallback to using FileReader and a popup
173
+ // Open a popup immediately do go around popup blocker
174
+ // Mostly only available on user interaction and the fileReader is async so...
175
+ let popup = (window as any).popup || open("", "_blank");
176
+ if (popup) {
177
+ popup.document.title = popup.document.body.innerText = "downloading...";
178
+ }
179
+
180
+ if (typeof blob === "string") {
181
+ return download(blob, name, opts);
182
+ }
183
+
184
+ const force = blob.type === "application/octet-stream";
185
+ // adoption note: add any
186
+ const isSafari =
187
+ /constructor/i.test((globalThis as any).HTMLElement) ||
188
+ (globalThis as any).safari;
189
+ const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
190
+
191
+ if (
192
+ (isChromeIOS || (force && isSafari) || isMacOSWebView) &&
193
+ typeof FileReader !== "undefined"
194
+ ) {
195
+ // Safari doesn't allow downloading of blob URLs
196
+ const reader = new FileReader();
197
+ reader.onloadend = function () {
198
+ let url = reader.result as string;
199
+ url = isChromeIOS
200
+ ? url
201
+ : url.replace(/^data:[^;]*;/, "data:attachment/file;");
202
+ if (popup) {
203
+ popup.location.href = url;
204
+ } else {
205
+ (location as any) = url;
206
+ }
207
+ popup = null; // reverse-tabnabbing #460
208
+ };
209
+ reader.readAsDataURL(blob);
210
+ } else {
211
+ const URL = globalThis.URL || globalThis.webkitURL;
212
+ const url = URL.createObjectURL(blob);
213
+ if (popup) {
214
+ popup.location = url;
215
+ } else {
216
+ location.href = url;
217
+ }
218
+ popup = null; // reverse-tabnabbing #460
219
+ setTimeout(function () {
220
+ URL.revokeObjectURL(url);
221
+ }, 4e4); // 40s
222
+ }
223
+ };