cf-workers-native 0.1.5 → 0.1.7

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 (197) hide show
  1. package/README.md +2 -2
  2. package/dist/browser/documents/page-source.js +1 -1
  3. package/dist/browser/headers/index.d.ts +2 -0
  4. package/dist/browser/headers/index.js +5 -0
  5. package/dist/browser/response/index.d.ts +2 -0
  6. package/dist/browser/response/index.js +11 -3
  7. package/dist/browser/structured-clone/index.d.ts +3 -0
  8. package/dist/browser/structured-clone/index.js +75 -7
  9. package/dist/browser/websocket/attachment-size.d.ts +3 -0
  10. package/dist/browser/websocket/attachment-size.js +336 -0
  11. package/dist/browser/websocket/brand.d.ts +4 -0
  12. package/dist/browser/websocket/brand.js +16 -0
  13. package/dist/browser/websocket/close-event.d.ts +7 -0
  14. package/dist/browser/websocket/close-event.js +30 -0
  15. package/dist/browser/websocket/compression.d.ts +5 -0
  16. package/dist/browser/websocket/compression.js +124 -0
  17. package/dist/browser/websocket/conversion.d.ts +2 -0
  18. package/dist/browser/websocket/conversion.js +13 -0
  19. package/dist/browser/websocket/endpoint.d.ts +39 -0
  20. package/dist/browser/websocket/endpoint.js +379 -0
  21. package/dist/browser/websocket/frames.d.ts +21 -0
  22. package/dist/browser/websocket/frames.js +121 -0
  23. package/dist/browser/websocket/native.d.ts +14 -0
  24. package/dist/browser/websocket/native.js +226 -0
  25. package/dist/cloudflare/apis/cloudflare-node/index.js +11 -23
  26. package/dist/compat/crypto/LICENSE-3RD-PARTY.md +20 -0
  27. package/dist/compat/crypto/LICENSE.boringssl +238 -0
  28. package/dist/compat/crypto/LICENSE.ncrypto +21 -0
  29. package/dist/compat/crypto/asymmetric.js +141 -68
  30. package/dist/compat/crypto/cipher-handle.d.ts +27 -0
  31. package/dist/compat/crypto/cipher-handle.js +239 -0
  32. package/dist/compat/crypto/cipher-info.d.ts +12 -0
  33. package/dist/compat/crypto/cipher-info.js +324 -0
  34. package/dist/compat/crypto/constants.d.ts +62 -0
  35. package/dist/compat/crypto/constants.js +68 -0
  36. package/dist/compat/crypto/dh-handle.d.ts +17 -0
  37. package/dist/compat/crypto/dh-handle.js +180 -0
  38. package/dist/compat/crypto/dh.d.ts +53 -0
  39. package/dist/compat/crypto/dh.js +138 -0
  40. package/dist/compat/crypto/digest-stream.d.ts +15 -0
  41. package/dist/compat/crypto/digest-stream.js +213 -0
  42. package/dist/compat/crypto/digests.d.ts +3 -0
  43. package/dist/compat/crypto/digests.js +32 -0
  44. package/dist/compat/crypto/ecdh.d.ts +16 -6
  45. package/dist/compat/crypto/hash-handle.d.ts +23 -0
  46. package/dist/compat/crypto/hash-handle.js +70 -0
  47. package/dist/compat/crypto/hash.d.ts +37 -0
  48. package/dist/compat/crypto/hash.js +218 -0
  49. package/dist/compat/crypto/hkdf.js +40 -14
  50. package/dist/compat/crypto/index.d.cts +168 -1
  51. package/dist/compat/crypto/index.d.ts +191 -8
  52. package/dist/compat/crypto/index.js +36 -23
  53. package/dist/compat/crypto/key-errors.d.ts +10 -0
  54. package/dist/compat/crypto/key-errors.js +17 -0
  55. package/dist/compat/crypto/key-export.d.ts +8 -0
  56. package/dist/compat/crypto/key-export.js +49 -0
  57. package/dist/compat/crypto/key-formats.d.ts +2 -1
  58. package/dist/compat/crypto/key-formats.js +162 -31
  59. package/dist/compat/crypto/key-options.d.ts +1 -0
  60. package/dist/compat/crypto/key-options.js +74 -0
  61. package/dist/compat/crypto/key-state.d.ts +1 -0
  62. package/dist/compat/crypto/keys.d.ts +20 -12
  63. package/dist/compat/crypto/keys.js +129 -59
  64. package/dist/compat/crypto/metadata.d.ts +9 -0
  65. package/dist/compat/crypto/metadata.js +89 -2
  66. package/dist/compat/crypto/native-cipher.d.ts +17 -0
  67. package/dist/compat/crypto/native-cipher.js +192 -0
  68. package/dist/compat/crypto/native-crypto.d.ts +14 -1
  69. package/dist/compat/crypto/native-crypto.js +182 -6
  70. package/dist/compat/crypto/pbkdf2-handle.d.ts +4 -0
  71. package/dist/compat/crypto/pbkdf2-handle.js +26 -0
  72. package/dist/compat/crypto/pbkdf2.d.ts +5 -0
  73. package/dist/compat/crypto/pbkdf2.js +60 -0
  74. package/dist/compat/crypto/prime.js +4 -4
  75. package/dist/compat/crypto/random.d.ts +11 -0
  76. package/dist/compat/crypto/random.js +86 -6
  77. package/dist/compat/crypto/rsa.d.ts +17 -1
  78. package/dist/compat/crypto/rsa.js +8 -4
  79. package/dist/compat/crypto/scrypt.d.ts +3 -3
  80. package/dist/compat/crypto/scrypt.js +25 -23
  81. package/dist/compat/crypto/sign-handle.d.ts +3 -3
  82. package/dist/compat/crypto/sign-handle.js +55 -11
  83. package/dist/compat/crypto/signatures.d.ts +17 -11
  84. package/dist/compat/crypto/subtle-digest.d.ts +1 -0
  85. package/dist/compat/crypto/subtle-digest.js +56 -0
  86. package/dist/compat/crypto/symmetric.d.ts +40 -24
  87. package/dist/compat/crypto/symmetric.js +229 -94
  88. package/dist/compat/crypto/validation.d.ts +4 -0
  89. package/dist/compat/crypto/validation.js +29 -2
  90. package/dist/compat/crypto/webcrypto.d.ts +13 -0
  91. package/dist/compat/crypto/webcrypto.js +51 -0
  92. package/dist/compat/crypto/x509.js +2 -1
  93. package/dist/compat/events/index.js +1 -1
  94. package/dist/compat/fs/LICENSE-3RD-PARTY.md +11 -0
  95. package/dist/compat/fs/LICENSE-APACHE +177 -0
  96. package/dist/compat/fs/directory-backend.d.ts +6 -0
  97. package/dist/compat/fs/directory-backend.js +51 -0
  98. package/dist/compat/fs/directory.d.ts +37 -0
  99. package/dist/compat/fs/directory.js +137 -0
  100. package/dist/compat/fs/embedded.d.ts +1 -1
  101. package/dist/compat/fs/embedded.js +7 -2
  102. package/dist/compat/fs/file-handle.d.ts +75 -0
  103. package/dist/compat/fs/file-handle.js +249 -0
  104. package/dist/compat/fs/glob-internal.d.ts +15 -0
  105. package/dist/compat/fs/glob-internal.js +417 -0
  106. package/dist/compat/fs/glob.d.ts +10 -0
  107. package/dist/compat/fs/glob.js +71 -0
  108. package/dist/compat/fs/index.d.ts +6 -3
  109. package/dist/compat/fs/index.js +596 -50
  110. package/dist/compat/fs/io-validation.d.ts +14 -0
  111. package/dist/compat/fs/io-validation.js +130 -0
  112. package/dist/compat/fs/io.d.ts +1 -0
  113. package/dist/compat/fs/io.js +283 -0
  114. package/dist/compat/fs/promises/index.d.ts +3 -1
  115. package/dist/compat/fs/public-types.d.ts +120 -0
  116. package/dist/compat/fs/public-types.js +1 -0
  117. package/dist/compat/fs/stream-errors.d.ts +6 -0
  118. package/dist/compat/fs/stream-errors.js +8 -0
  119. package/dist/compat/fs/stream-utils.d.ts +16 -0
  120. package/dist/compat/fs/stream-utils.js +29 -0
  121. package/dist/compat/fs/streams.d.ts +104 -0
  122. package/dist/compat/fs/streams.js +794 -0
  123. package/dist/compat/fs/writable.d.ts +8 -0
  124. package/dist/compat/fs/writable.js +412 -22
  125. package/dist/compat/http/index.d.ts +11 -28
  126. package/dist/compat/http/index.js +81 -125
  127. package/dist/compat/http/server-options.d.ts +1 -0
  128. package/dist/compat/http/server-options.js +87 -0
  129. package/dist/compat/http/unique-headers.d.ts +1 -0
  130. package/dist/compat/http/unique-headers.js +21 -0
  131. package/dist/compat/http-outgoing/index.d.ts +2 -1
  132. package/dist/compat/http-outgoing/index.js +2 -17
  133. package/dist/compat/http-server/index.d.ts +2 -2
  134. package/dist/compat/http-server/index.js +4 -85
  135. package/dist/compat/https/index.d.ts +4 -2
  136. package/dist/compat/net/sockets.js +98 -20
  137. package/dist/compat/net/validators.d.ts +1 -0
  138. package/dist/compat/net/validators.js +8 -0
  139. package/dist/compat/process/configuration.d.ts +113 -0
  140. package/dist/compat/process/configuration.js +115 -0
  141. package/dist/compat/process/directory.d.ts +4 -0
  142. package/dist/compat/process/directory.js +28 -0
  143. package/dist/compat/process/files.d.ts +3 -0
  144. package/dist/compat/process/files.js +10 -0
  145. package/dist/compat/process/index.d.ts +15 -13
  146. package/dist/compat/process/index.js +47 -74
  147. package/dist/compat/process/scheduling.d.ts +2 -0
  148. package/dist/compat/process/scheduling.js +60 -0
  149. package/dist/compat/process/state.js +1 -0
  150. package/dist/compat/process/stdio.d.ts +18 -0
  151. package/dist/compat/process/stdio.js +66 -0
  152. package/dist/compat/stream/destroy.d.ts +1 -0
  153. package/dist/compat/stream/destroy.js +21 -1
  154. package/dist/compat/stream/readable.js +10 -2
  155. package/dist/compat/tls/jsstream.js +16 -6
  156. package/dist/compat/tls/wrap.d.ts +1 -1
  157. package/dist/compat/tls/wrap.js +0 -3
  158. package/dist/compat/util/inspect.js +5 -1
  159. package/dist/compat/zlib/LICENSE-3RD-PARTY.md +11 -0
  160. package/dist/compat/zlib/LICENSE-APACHE +177 -0
  161. package/dist/compat/zlib/LICENSE.zlib +22 -0
  162. package/dist/compat/zlib/classic-base.cjs +600 -0
  163. package/dist/compat/zlib/classic-base.d.cts +39 -0
  164. package/dist/compat/zlib/classic-binding.d.ts +28 -0
  165. package/dist/compat/zlib/classic-binding.js +105 -0
  166. package/dist/compat/zlib/classic.d.ts +44 -0
  167. package/dist/compat/zlib/classic.js +199 -0
  168. package/dist/compat/zlib/codec-binding.d.ts +33 -0
  169. package/dist/compat/zlib/codec-binding.js +141 -0
  170. package/dist/compat/zlib/compression.d.ts +22 -51
  171. package/dist/compat/zlib/compression.js +129 -218
  172. package/dist/compat/zlib/errors.d.ts +21 -0
  173. package/dist/compat/zlib/errors.js +32 -0
  174. package/dist/compat/zlib/index.d.ts +367 -3
  175. package/dist/compat/zlib/index.js +28 -11
  176. package/dist/compat/zlib/input.d.ts +16 -0
  177. package/dist/compat/zlib/input.js +132 -0
  178. package/dist/compat/zlib/native-codecs.d.ts +7 -0
  179. package/dist/compat/zlib/native-codecs.js +22 -10
  180. package/dist/compat/zlib/native-zlib.d.ts +5 -0
  181. package/dist/compat/zlib/native-zlib.js +52 -0
  182. package/dist/compat/zlib/public-types.d.ts +48 -0
  183. package/dist/compat/zlib/public-types.js +1 -0
  184. package/dist/compat/zlib/validators.d.ts +3 -0
  185. package/dist/compat/zlib/validators.js +18 -0
  186. package/dist/shared/buffer-source.d.ts +5 -0
  187. package/dist/shared/buffer-source.js +70 -0
  188. package/dist/shared/globals/platform.d.ts +8 -0
  189. package/dist/shared/globals/platform.js +1 -0
  190. package/dist/shared/globals/web.js +5 -0
  191. package/dist/shared/request-context.d.ts +2 -0
  192. package/dist/shared/request-context.js +11 -0
  193. package/dist/shared/request-scope.js +4 -1
  194. package/dist/tooling/shared.js +6 -0
  195. package/dist/tooling/vite.js +4 -0
  196. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkerSockets.java +38 -7
  197. package/package.json +2 -2
@@ -1,9 +1,16 @@
1
+ import { createFileHandle, FileHandle } from "./file-handle.js";
2
+ import { installIo } from "./io.js";
3
+ import * as fileStreams from "./streams.js";
4
+ import { Dir as WorkersDir, Dirent as WorkersDirent } from "./directory.js";
5
+ import { readDirectory } from "./directory-backend.js";
6
+ import { globSync as workersGlob } from "./glob.js";
1
7
  import { fileMode } from "./mode.js";
2
8
  import { validateInteger } from "../crypto/validation.js";
3
9
  import * as embedded from "./embedded.js";
4
- import { temporary, temporaryPath, clearTemporaryFiles, writablePath, pathOf, } from "./writable.js";
10
+ import { temporary, retainTemporaryFiles, temporaryPath, clearTemporaryFiles, writablePath, pathOf, readonlyFile, embeddedStat, } from "./writable.js";
5
11
  import { Buffer } from "node:buffer";
6
- import { validateFunction, validateObject, validateBoolean, } from "../net/validators.js";
12
+ import { validateFunction, validateObject, validateBoolean, validateUint32, } from "../net/validators.js";
13
+ import { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE } from "../net/errors.js";
7
14
  export const registerVirtualFiles = embedded.registerVirtualFiles;
8
15
  export function clearVirtualFiles() {
9
16
  embedded.clearVirtualFiles();
@@ -21,6 +28,20 @@ const reads = new Set([
21
28
  "existsSync",
22
29
  ]);
23
30
  const api = { ...temporary };
31
+ // Stats values are produced by the filesystem; Workers forbids public construction.
32
+ api.Stats = new Proxy(api.Stats, {
33
+ construct() {
34
+ throw new TypeError("Illegal constructor");
35
+ },
36
+ apply() {
37
+ throw new TypeError("Class constructor Stats cannot be invoked without 'new'");
38
+ },
39
+ });
40
+ Object.defineProperty(api.Stats.prototype, "constructor", {
41
+ value: api.Stats,
42
+ configurable: true,
43
+ writable: true,
44
+ });
24
45
  for (const name of Object.keys(api))
25
46
  if (typeof api[name] === "function" && /^[a-z]/.test(name))
26
47
  api[name] = (...args) => temporary[name](...args);
@@ -32,8 +53,10 @@ for (const name of [
32
53
  ]) {
33
54
  api[name] = new Proxy(api[name], {
34
55
  construct(_target, args) {
56
+ if (name === "ReadStream" || name === "FileReadStream")
57
+ return temporary.createReadStream(...args);
35
58
  args[0] = writablePath(args[0], name);
36
- return Reflect.construct(temporary[name], args);
59
+ return temporary.createWriteStream(...args);
37
60
  },
38
61
  });
39
62
  }
@@ -56,10 +79,10 @@ for (const name of ["writeFileSync", "appendFileSync"])
56
79
  ? Buffer.byteLength(args[1], encoding)
57
80
  : args[1].byteLength;
58
81
  };
59
- const promises = { ...temporary.promises };
60
- for (const name of Object.keys(promises))
61
- if (typeof promises[name] === "function" && /^[a-z]/.test(name))
62
- promises[name] = (...args) => temporary.promises[name](...args);
82
+ const promiseImpl = { ...temporary.promises };
83
+ for (const name of Object.keys(promiseImpl))
84
+ if (typeof promiseImpl[name] === "function" && /^[a-z]/.test(name))
85
+ promiseImpl[name] = (...args) => temporary.promises[name](...args);
63
86
  for (const name of [
64
87
  "readFile",
65
88
  "readdir",
@@ -69,7 +92,7 @@ for (const name of [
69
92
  "access",
70
93
  ]) {
71
94
  const old = embedded.promises[name];
72
- promises[name] = (...args) => temporaryPath(args[0]) ? temporary.promises[name](...args) : old(...args);
95
+ promiseImpl[name] = async (...args) => temporaryPath(args[0]) ? temporary.promises[name](...args) : old(...args);
73
96
  }
74
97
  // Keep all writes inside the memory volume, including FileHandle operations.
75
98
  for (const name of [
@@ -87,14 +110,11 @@ for (const name of [
87
110
  "chown",
88
111
  "lchmod",
89
112
  "lchown",
90
- "open",
91
113
  "rename",
92
114
  "copyFile",
93
- "cp",
94
- "link",
95
115
  "symlink",
96
116
  ]) {
97
- promises[name] = async (...args) => {
117
+ promiseImpl[name] = async (...args) => {
98
118
  if (name === "symlink") {
99
119
  return new Promise((resolve, reject) => temporary.symlink(...args, (error) => error ? reject(error) : resolve(undefined)));
100
120
  }
@@ -106,15 +126,15 @@ for (const name of [
106
126
  args[i] instanceof URL ||
107
127
  Buffer.isBuffer(args[i])) {
108
128
  if (!temporaryPath(args[i]))
109
- throw Object.assign(new Error("EROFS: read-only file system"), {
110
- code: "EROFS",
129
+ throw Object.assign(new Error("operation not permitted"), {
130
+ code: "EPERM",
111
131
  });
112
132
  }
113
133
  return temporary.promises[name](...args);
114
134
  };
115
135
  }
116
- promises.watch = async function* () {
117
- api.watch();
136
+ promiseImpl.watch = function () {
137
+ throw new Error("Not implemented");
118
138
  };
119
139
  // Workers validates ownership/permission requests but has no mutable Unix
120
140
  // ownership or permissions. These operations must not change the memory VFS.
@@ -128,39 +148,143 @@ function installOperation(name, handler, promise = true) {
128
148
  .then((value) => callback(null, value), (error) => callback(error));
129
149
  };
130
150
  if (promise)
131
- promises[name] = async (...args) => handler(...args);
151
+ promiseImpl[name] = async (...args) => handler(...args);
132
152
  }
133
- function temporaryStats(stat) {
153
+ function temporaryStats(stat, readonly = false) {
134
154
  if (stat == null)
135
155
  return stat;
136
156
  const bigint = typeof stat.mode === "bigint";
137
- const mode = (Number(stat.mode) & ~0o777) | 0o666;
157
+ const mode = (Number(stat.mode) & ~0o777) |
158
+ (readonly || stat.isSymbolicLink() ? 0o444 : 0o666);
138
159
  stat.mode = bigint ? BigInt(mode) : mode;
139
- stat.uid = stat.gid = bigint ? 0n : 0;
160
+ for (const name of [
161
+ "dev",
162
+ "ino",
163
+ "uid",
164
+ "gid",
165
+ "rdev",
166
+ "blksize",
167
+ "blocks",
168
+ "atimeMs",
169
+ ])
170
+ stat[name] = bigint ? 0n : 0;
171
+ stat.dev = bigint
172
+ ? BigInt(stat.isCharacterDevice())
173
+ : Number(stat.isCharacterDevice());
174
+ stat.nlink = bigint ? 1n : 1;
175
+ stat.atime = new Date(0);
176
+ stat.ctime = stat.mtime;
177
+ stat.ctimeMs = stat.mtimeMs;
178
+ if (bigint) {
179
+ stat.atimeNs = 0n;
180
+ stat.ctimeNs = stat.mtimeNs;
181
+ }
182
+ if (readonly)
183
+ for (const name of ["mtime", "ctime", "birthtime"]) {
184
+ stat[name] = new Date(0);
185
+ stat[name + "Ms"] = bigint ? 0n : 0;
186
+ if (bigint)
187
+ stat[name + "Ns"] = 0n;
188
+ }
140
189
  return stat;
141
190
  }
191
+ // Workers has no executable files. Read-only bundle files also report ENOENT
192
+ // for W_OK rather than exposing host-style permission bits.
193
+ function accessArgs(path, mode = 0) {
194
+ const normalized = pathOf(path);
195
+ mode ??= 0;
196
+ validateInteger(mode, "mode", 0, 7);
197
+ return { path: normalized, mode: mode };
198
+ }
199
+ function checkAccess({ path, mode }) {
200
+ if (mode & 1 || (mode & 2 && readonlyFile(path)) || !api.existsSync(path))
201
+ throw Object.assign(new Error(`ENOENT: no such file or directory, access '${path}'`), {
202
+ code: "ENOENT",
203
+ errno: -2,
204
+ syscall: "access",
205
+ path,
206
+ });
207
+ }
208
+ api.accessSync = (path, mode) => checkAccess(accessArgs(path, mode));
209
+ api.access = (path, mode, callback) => {
210
+ if (typeof mode === "function") {
211
+ callback = mode;
212
+ mode = undefined;
213
+ }
214
+ const args = accessArgs(path, mode);
215
+ validateFunction(callback, "callback");
216
+ let failure = null;
217
+ try {
218
+ checkAccess(args);
219
+ }
220
+ catch (error) {
221
+ failure = error;
222
+ }
223
+ queueMicrotask(() => callback(failure));
224
+ };
225
+ promiseImpl.access = async (path, mode) => checkAccess(accessArgs(path, mode));
226
+ function statOptions(options = {}) {
227
+ validateObject(options, "options");
228
+ validateBoolean(options.bigint ?? false, "options.bigint");
229
+ validateBoolean(options.throwIfNoEntry ?? true, "options.throwIfNoEntry");
230
+ return options;
231
+ }
142
232
  for (const name of ["stat", "lstat"])
143
- installOperation(name, (path, options) => temporaryPath(path)
144
- ? temporaryStats(temporary[name + "Sync"](path, options))
145
- : embedded.statSync(path));
146
- installOperation("fstat", (...args) => temporaryStats(temporary.fstatSync(...args)), false);
233
+ installOperation(name, (path, options = {}) => {
234
+ statOptions(options);
235
+ return temporaryPath(path)
236
+ ? temporaryStats(temporary[name + "Sync"](path, options), readonlyFile(path, name !== "lstat"))
237
+ : temporaryStats(embeddedStat(path, options), true);
238
+ });
239
+ installOperation("fstat", (fd, options = {}) => {
240
+ statOptions(options);
241
+ validateInteger(fd, "fd", 0, 2147483647);
242
+ return temporaryStats(temporary.fstatSync(fd, options), readonlyFile(fd));
243
+ }, false);
147
244
  for (const name of ["chmod", "lchmod", "fchmod", "chown", "lchown", "fchown"]) {
148
- installOperation(name, (path, value, gid) => {
245
+ const count = name.endsWith("chmod") ? 2 : 3;
246
+ const prepare = (args) => {
247
+ const [path, value, gid] = args;
149
248
  if (name.endsWith("chmod"))
150
249
  fileMode(value);
151
250
  else {
152
251
  validateInteger(value, "uid", -1, 0xffffffff);
153
252
  validateInteger(gid, "gid", -1, 0xffffffff);
154
253
  }
155
- if (name.startsWith("f")) {
254
+ if (typeof path === "number" || name.startsWith("f"))
156
255
  validateInteger(path, "fd", 0, 2147483647);
157
- temporary.fstatSync(path);
158
- }
159
- else if (name.startsWith("l") && temporaryPath(path))
160
- temporary.lstatSync(path);
161
256
  else
162
- api.statSync(path);
163
- }, !name.startsWith("f"));
257
+ pathOf(path);
258
+ return path;
259
+ };
260
+ const operation = (path) => {
261
+ try {
262
+ if (typeof path === "number")
263
+ temporary.fstatSync(path);
264
+ else
265
+ api[name.startsWith("l") ? "lstatSync" : "statSync"](path);
266
+ }
267
+ catch (error) {
268
+ if (error.code === "ENOENT")
269
+ error.syscall = name;
270
+ throw error;
271
+ }
272
+ };
273
+ api[name + "Sync"] = (...args) => operation(prepare(args));
274
+ api[name] = (...args) => {
275
+ const path = prepare(args), callback = args[count];
276
+ validateFunction(callback, "callback");
277
+ let error = null;
278
+ try {
279
+ operation(path);
280
+ }
281
+ catch (failure) {
282
+ error = failure;
283
+ }
284
+ queueMicrotask(() => callback(error));
285
+ };
286
+ if (!name.startsWith("f"))
287
+ promiseImpl[name] = async (...args) => operation(prepare(args));
164
288
  }
165
289
  installOperation("statfs", (path, options = {}) => {
166
290
  pathOf(path);
@@ -178,23 +302,40 @@ installOperation("statfs", (path, options = {}) => {
178
302
  ffree: value,
179
303
  };
180
304
  });
181
- const openPromise = promises.open;
182
- promises.open = async (...args) => {
183
- fileMode(args[2], 0o666);
184
- args[2] = 0o666;
185
- const handle = await openPromise(...args);
186
- const stat = handle.stat.bind(handle);
187
- handle.stat = async (...options) => temporaryStats(await stat(...options));
188
- handle.chmod = async (mode) => {
189
- fileMode(mode);
190
- await stat();
191
- };
192
- handle.chown = async (uid, gid) => {
193
- validateInteger(uid, "uid", -1, 0xffffffff);
194
- validateInteger(gid, "gid", -1, 0xffffffff);
195
- await stat();
196
- };
197
- return handle;
305
+ // Workers interprets numeric timestamps as milliseconds and does not change
306
+ // metadata belonging to embedded files. Convert before the memfs boundary.
307
+ function fileTime(value) {
308
+ let date;
309
+ if (value instanceof Date)
310
+ date = value;
311
+ else if (typeof value === "number" || typeof value === "string")
312
+ date = new Date(value);
313
+ else if (typeof value === "bigint")
314
+ date = new Date(Number(value));
315
+ else
316
+ throw new ERR_INVALID_ARG_TYPE("time", ["string", "number", "bigint", "Date"], value);
317
+ if (!Number.isFinite(date.getTime()))
318
+ throw new TypeError("The value cannot be converted because it is not an integer.");
319
+ return date;
320
+ }
321
+ for (const name of ["utimes", "lutimes", "futimes"]) {
322
+ installOperation(name, (path, atime, mtime) => {
323
+ const access = fileTime(atime), modified = fileTime(mtime);
324
+ if (name === "futimes") {
325
+ validateInteger(path, "fd", 0, 2147483647);
326
+ api.fstatSync(path);
327
+ }
328
+ else
329
+ api[name === "lutimes" ? "lstatSync" : "statSync"](path);
330
+ if (!readonlyFile(path, name !== "lutimes"))
331
+ temporary[name + "Sync"](path, access, modified);
332
+ }, name !== "futimes");
333
+ }
334
+ promiseImpl.FileHandle = FileHandle;
335
+ promiseImpl.open = async (path, flags, mode) => {
336
+ const run = retainTemporaryFiles();
337
+ const fd = api.openSync(path, flags, mode);
338
+ return createFileHandle({ fd, run, api });
198
339
  };
199
340
  // Copy an embedded bundle file into request-local /tmp without granting any
200
341
  // write access to its source volume.
@@ -215,7 +356,412 @@ installOperation("copyFile", (source, destination, mode = 0) => {
215
356
  throw Object.assign(new Error("File already exists"), { code: "EEXIST" });
216
357
  temporary.writeFileSync(destination, embedded.readFileSync(pathOf(source)));
217
358
  });
218
- api.promises = promises;
359
+ const copyTree = (source, destination, options) => {
360
+ const fail = (code) => {
361
+ throw Object.assign(new Error(code), { code, syscall: "cp" });
362
+ };
363
+ source = pathOf(source);
364
+ destination = pathOf(destination);
365
+ if (source === destination)
366
+ throw new Error("Source and destination paths must not be the same");
367
+ if (destination.startsWith(source + "/"))
368
+ fail("ERR_FS_CP_EINVAL");
369
+ const lookup = (path, follow) => {
370
+ try {
371
+ return api[follow ? "statSync" : "lstatSync"](path);
372
+ }
373
+ catch (error) {
374
+ if (error.code !== "ENOENT")
375
+ throw error;
376
+ }
377
+ };
378
+ const visit = (src, dst, nested = false) => {
379
+ const stat = lookup(src, nested ? false : options.dereference);
380
+ if (!stat)
381
+ fail("ENOENT");
382
+ const target = lookup(dst, options.dereference);
383
+ if (stat.isDirectory()) {
384
+ if (!options.recursive)
385
+ fail("ERR_FS_EISDIR");
386
+ if (target && !target.isDirectory())
387
+ fail(target.isSymbolicLink()
388
+ ? nested
389
+ ? "EISDIR"
390
+ : "ENOTDIR"
391
+ : nested
392
+ ? "ENOTDIR"
393
+ : "ERR_FS_CP_DIR_TO_NON_DIR");
394
+ const entries = api.readdirSync(src);
395
+ api.mkdirSync(dst, { recursive: true });
396
+ for (const name of entries)
397
+ visit(src + "/" + name, dst + "/" + name, true);
398
+ return;
399
+ }
400
+ if (target?.isDirectory())
401
+ fail(nested
402
+ ? "EISDIR"
403
+ : stat.isSymbolicLink()
404
+ ? "ENOTDIR"
405
+ : "ERR_FS_CP_NON_DIR_TO_DIR");
406
+ if (target && !options.force) {
407
+ if (options.errorOnExist)
408
+ fail(nested ? "EEXIST" : "ERR_FS_CP_EEXIST");
409
+ return;
410
+ }
411
+ const data = stat.isSymbolicLink()
412
+ ? api.readlinkSync(src)
413
+ : api.readFileSync(src);
414
+ api.mkdirSync(dst.slice(0, dst.lastIndexOf("/")) || "/", {
415
+ recursive: true,
416
+ });
417
+ if (lookup(dst, false))
418
+ api.unlinkSync(dst);
419
+ if (stat.isSymbolicLink())
420
+ api.symlinkSync(data, dst);
421
+ else
422
+ api.writeFileSync(dst, data);
423
+ };
424
+ visit(source, destination);
425
+ };
426
+ installOperation("cp", (source, destination, options = {}) => {
427
+ validateObject(options, "options");
428
+ const { dereference = false, errorOnExist = false, force = true, preserveTimestamps = false, recursive = false, verbatimSymlinks = false, mode = 0, } = options;
429
+ for (const [key, value] of Object.entries({
430
+ dereference,
431
+ errorOnExist,
432
+ force,
433
+ preserveTimestamps,
434
+ recursive,
435
+ verbatimSymlinks,
436
+ }))
437
+ validateBoolean(value, "options." + key);
438
+ validateUint32(mode, "options.mode");
439
+ if (mode & 4)
440
+ throw new ERR_INVALID_ARG_VALUE("options.mode", "COPYFILE_FICLONE_FORCE is not supported");
441
+ if (options.filter !== undefined) {
442
+ if (typeof options.filter !== "function")
443
+ throw new ERR_INVALID_ARG_TYPE("options.filter", "function", options.filter);
444
+ throw Object.assign(new Error("The requested operation is unsupported"), {
445
+ code: "ERR_UNSUPPORTED_OPERATION",
446
+ });
447
+ }
448
+ return copyTree(source, destination, {
449
+ dereference,
450
+ errorOnExist,
451
+ force,
452
+ recursive,
453
+ verbatimSymlinks: false,
454
+ preserveTimestamps: false,
455
+ mode: 0,
456
+ });
457
+ });
458
+ api.cp = (source, destination, options, callback) => {
459
+ if (typeof options === "function") {
460
+ callback = options;
461
+ options = {};
462
+ }
463
+ validateObject(options ?? {}, "options");
464
+ for (const key of [
465
+ "dereference",
466
+ "errorOnExist",
467
+ "force",
468
+ "preserveTimestamps",
469
+ "recursive",
470
+ "verbatimSymlinks",
471
+ ])
472
+ if (options?.[key] !== undefined)
473
+ validateBoolean(options[key], "options." + key);
474
+ if (options?.mode !== undefined)
475
+ validateUint32(options.mode, "options.mode");
476
+ if (options?.filter !== undefined && typeof options.filter !== "function")
477
+ throw new ERR_INVALID_ARG_TYPE("options.filter", "function", options.filter);
478
+ if (options?.filter !== undefined)
479
+ throw Object.assign(new Error("The requested operation is unsupported"), {
480
+ code: "ERR_UNSUPPORTED_OPERATION",
481
+ });
482
+ if (options?.mode & 4)
483
+ throw new ERR_INVALID_ARG_VALUE("options.mode", "COPYFILE_FICLONE_FORCE is not supported");
484
+ pathOf(source);
485
+ pathOf(destination);
486
+ validateFunction(callback, "callback");
487
+ let error;
488
+ try {
489
+ api.cpSync(source, destination, options);
490
+ }
491
+ catch (cause) {
492
+ error = cause;
493
+ }
494
+ queueMicrotask(() => callback(error ?? null));
495
+ };
496
+ api.promises = promiseImpl;
497
+ const promises = promiseImpl;
219
498
  export { promises };
499
+ // Validate public directory arguments before scheduling their callbacks.
500
+ function directoryOperation(name, prepare, operation) {
501
+ api[name + "Sync"] = (path, options = {}) => operation(prepare(path, options));
502
+ api[name] = (path, options, callback) => {
503
+ if (typeof options === "function") {
504
+ callback = options;
505
+ options = {};
506
+ }
507
+ const args = prepare(path, options === undefined ? {} : options);
508
+ validateFunction(callback, "callback");
509
+ let value, error = null;
510
+ try {
511
+ value = operation(args);
512
+ }
513
+ catch (failure) {
514
+ error = failure;
515
+ }
516
+ queueMicrotask(() => callback(error, value));
517
+ };
518
+ promiseImpl[name] = async (path, options = {}) => operation(prepare(path, options));
519
+ }
520
+ directoryOperation("mkdir", (path, options) => {
521
+ if (typeof options === "number")
522
+ options = { mode: options };
523
+ validateObject(options, "options");
524
+ const { recursive = false, mode = 0o777 } = options;
525
+ validateBoolean(recursive, "options.recursive");
526
+ fileMode(mode);
527
+ return { path: pathOf(path), recursive };
528
+ }, ({ path, recursive }) => {
529
+ writablePath(path, "mkdir");
530
+ if (temporary.existsSync(path) && temporary.statSync(path).isDirectory())
531
+ return;
532
+ let created = path;
533
+ if (recursive) {
534
+ let parent = created.slice(0, created.lastIndexOf("/")) || "/";
535
+ while (!temporary.existsSync(parent)) {
536
+ created = parent;
537
+ parent = created.slice(0, created.lastIndexOf("/")) || "/";
538
+ }
539
+ }
540
+ temporary.mkdirSync(path, { recursive, mode: 0o777 });
541
+ return recursive ? created : undefined;
542
+ });
543
+ directoryOperation("mkdtemp", (path, options) => {
544
+ if (typeof options === "string" || options == null)
545
+ options = { encoding: options };
546
+ validateObject(options, "options");
547
+ const { encoding = "utf8" } = options;
548
+ if (encoding !== "buffer" && !Buffer.isEncoding(encoding))
549
+ throw new ERR_INVALID_ARG_VALUE("options.encoding", encoding);
550
+ return { path: pathOf(path) };
551
+ }, ({ path }) => {
552
+ writablePath(path, "mkdtemp");
553
+ for (;;) {
554
+ const name = path + globalThis.crypto.getRandomValues(new Uint32Array(1))[0];
555
+ try {
556
+ temporary.mkdirSync(name);
557
+ return name;
558
+ }
559
+ catch (error) {
560
+ if (error.code !== "EEXIST")
561
+ throw error;
562
+ }
563
+ }
564
+ });
565
+ for (const name of ["rm", "rmdir"])
566
+ directoryOperation(name, (path, options) => {
567
+ validateObject(options, "options");
568
+ const { recursive = false, force = false, maxRetries = 0, retryDelay = 0, } = options;
569
+ if (name === "rm")
570
+ validateBoolean(force, "options.force");
571
+ validateUint32(maxRetries, "options.maxRetries");
572
+ validateBoolean(recursive, "options.recursive");
573
+ validateUint32(retryDelay, "options.retryDelay");
574
+ return { path: pathOf(path), recursive, force };
575
+ }, ({ path, recursive, force }) => {
576
+ if (name === "rm" &&
577
+ !recursive &&
578
+ temporary.existsSync(path) &&
579
+ temporary.lstatSync(path).isDirectory())
580
+ return temporary.rmdirSync(path);
581
+ return temporary[name + "Sync"](path, { recursive, force });
582
+ });
583
+ const statFilesystem = api.statfsSync;
584
+ directoryOperation("statfs", (path, options) => {
585
+ pathOf(path);
586
+ validateObject(options, "options");
587
+ validateBoolean(options.bigint ?? false, "options.bigint");
588
+ return { path, options };
589
+ }, ({ path, options }) => statFilesystem(path, options));
590
+ api.exists = (path, callback) => {
591
+ validateFunction(callback, "callback");
592
+ let exists = false;
593
+ try {
594
+ exists = api.existsSync(path);
595
+ }
596
+ catch { }
597
+ queueMicrotask(() => callback(exists));
598
+ };
599
+ for (const name of ["link", "symlink"]) {
600
+ const prepare = (source, destination, type = null) => {
601
+ if (name === "symlink" && !["dir", "file", "junction", null].includes(type))
602
+ throw new ERR_INVALID_ARG_VALUE("type", type);
603
+ const src = pathOf(source), dest = pathOf(destination);
604
+ const raw = destination instanceof URL
605
+ ? destination.pathname
606
+ : Buffer.isBuffer(destination)
607
+ ? destination.toString()
608
+ : destination;
609
+ return { src, dest, type, trailing: raw.endsWith("/") };
610
+ };
611
+ const operation = ({ src, dest, type, trailing }) => {
612
+ if (trailing)
613
+ throw Object.assign(new Error("Invalid path"), { code: "EINVAL" });
614
+ if (name === "link") {
615
+ let stat;
616
+ try {
617
+ stat = api.statSync(src);
618
+ }
619
+ catch (error) {
620
+ if (error.code === "ENOTDIR")
621
+ error.code = "ENOENT";
622
+ throw error;
623
+ }
624
+ if (stat.isDirectory())
625
+ throw Object.assign(new Error("operation not permitted"), {
626
+ code: "EPERM",
627
+ });
628
+ }
629
+ const parent = dest.slice(0, dest.lastIndexOf("/")) || "/";
630
+ try {
631
+ const parentStat = api.statSync(parent);
632
+ if (!parentStat.isDirectory())
633
+ throw Object.assign(new Error("Invalid path"), { code: "EINVAL" });
634
+ }
635
+ catch (error) {
636
+ if (error.code === "ENOTDIR")
637
+ error.code = "EINVAL";
638
+ throw error;
639
+ }
640
+ try {
641
+ return temporary[name + "Sync"](src, dest, type ?? undefined);
642
+ }
643
+ catch (error) {
644
+ if (error.code === "ENOTDIR")
645
+ error.code = api.existsSync(parent) ? "EINVAL" : "ENOENT";
646
+ throw error;
647
+ }
648
+ };
649
+ api[name + "Sync"] = (source, destination, type) => operation(prepare(source, destination, type));
650
+ api[name] = (source, destination, type, callback) => {
651
+ if (typeof type === "function") {
652
+ callback = type;
653
+ type = null;
654
+ }
655
+ const args = prepare(source, destination, type);
656
+ validateFunction(callback, "callback");
657
+ let error = null;
658
+ try {
659
+ operation(args);
660
+ }
661
+ catch (failure) {
662
+ error = failure;
663
+ }
664
+ queueMicrotask(() => callback(error));
665
+ };
666
+ promiseImpl[name] = async (source, destination, type) => operation(prepare(source, destination, type));
667
+ }
668
+ for (const name of ["readlink", "realpath"])
669
+ directoryOperation(name, (path, options) => {
670
+ if (typeof options === "string" || options == null)
671
+ options = { encoding: options };
672
+ validateObject(options, "options");
673
+ const { encoding = "utf8" } = options;
674
+ if (encoding !== "buffer" && !Buffer.isEncoding(encoding))
675
+ throw new ERR_INVALID_ARG_VALUE("options.encoding", encoding);
676
+ return { path: pathOf(path), encoding };
677
+ }, ({ path, encoding }) => {
678
+ const stat = api.lstatSync(path);
679
+ let target = path;
680
+ if (stat.isSymbolicLink())
681
+ target = temporary.readlinkSync(path);
682
+ else if (name === "readlink")
683
+ throw Object.assign(new Error("invalid argument"), { code: "EINVAL" });
684
+ return Buffer.from(target).toString(encoding);
685
+ });
686
+ api.realpathSync.native = api.realpathSync;
687
+ api.realpath.native = api.realpath;
688
+ const unlinkFile = (path) => temporary.unlinkSync(path);
689
+ api.unlinkSync = (path) => {
690
+ path = pathOf(path);
691
+ if (api.lstatSync(path).isDirectory())
692
+ throw Object.assign(new Error("illegal operation on a directory"), {
693
+ code: "EISDIR",
694
+ });
695
+ return unlinkFile(path);
696
+ };
697
+ api.unlink = (path, callback) => {
698
+ path = pathOf(path);
699
+ validateFunction(callback, "callback");
700
+ let error = null;
701
+ try {
702
+ api.unlinkSync(path);
703
+ }
704
+ catch (failure) {
705
+ error = failure;
706
+ }
707
+ queueMicrotask(() => callback(error));
708
+ };
709
+ promiseImpl.unlink = async (path) => api.unlinkSync(path);
710
+ api.ReadStream = api.FileReadStream = fileStreams.ReadStream;
711
+ api.WriteStream = api.FileWriteStream = fileStreams.WriteStream;
712
+ api.createReadStream = fileStreams.createReadStream;
713
+ api.createWriteStream = fileStreams.createWriteStream;
714
+ api.openAsBlob = (path, options = {}) => {
715
+ const normalized = pathOf(path);
716
+ validateObject(options, "options");
717
+ const { type = "" } = options;
718
+ if (typeof type !== "string")
719
+ throw new ERR_INVALID_ARG_TYPE("options.type", "string", type);
720
+ if (api.statSync(normalized).isDirectory())
721
+ throw Object.assign(new Error("illegal operation on a directory"), {
722
+ code: "EISDIR",
723
+ });
724
+ const data = api.readFileSync(normalized);
725
+ return new Blob([data], { type });
726
+ };
727
+ api.Dir = WorkersDir;
728
+ api.Dirent = WorkersDirent;
729
+ installOperation("glob", workersGlob, false);
730
+ promiseImpl.glob = async function* (pattern, options) {
731
+ yield* workersGlob(pattern, options);
732
+ };
733
+ function directoryOptions(options, open) {
734
+ if (!open && (typeof options === "string" || options == null))
735
+ options = { encoding: options };
736
+ validateObject(options, "options");
737
+ const { encoding = "utf8", recursive = false, withFileTypes = false, bufferSize = 32, } = options;
738
+ if (encoding !== "buffer" && !Buffer.isEncoding(encoding))
739
+ throw new ERR_INVALID_ARG_VALUE("options.encoding", encoding);
740
+ validateBoolean(recursive, "options.recursive");
741
+ if (open)
742
+ validateUint32(bufferSize, "options.bufferSize");
743
+ else
744
+ validateBoolean(withFileTypes, "options.withFileTypes");
745
+ return { encoding, recursive, withFileTypes };
746
+ }
747
+ directoryOperation("readdir", (path, options) => ({
748
+ ...directoryOptions(options, false),
749
+ path: pathOf(path),
750
+ }), ({ path, encoding, recursive, withFileTypes }) => {
751
+ const entries = readDirectory(path, recursive);
752
+ return entries.map((entry) => withFileTypes
753
+ ? new WorkersDirent(encoding === "buffer" ? Buffer.from(entry.name) : entry.name, entry.type, entry.parentPath)
754
+ : encoding === "buffer"
755
+ ? Buffer.from(entry.name)
756
+ : Buffer.from(entry.name).toString(encoding));
757
+ });
758
+ directoryOperation("opendir", (path, options) => {
759
+ const opts = directoryOptions(options, true);
760
+ pathOf(path);
761
+ return { ...opts, path };
762
+ }, ({ path, encoding, recursive }) => {
763
+ return new WorkersDir(readDirectory(path, recursive), path, { encoding });
764
+ });
765
+ installIo(api, promiseImpl);
220
766
  export const { Dir, Dirent, F_OK, FileReadStream, FileWriteStream, R_OK, ReadStream, Stats, W_OK, WriteStream, X_OK, access, accessSync, appendFile, appendFileSync, chmod, chmodSync, chown, chownSync, close, closeSync, constants, copyFile, copyFileSync, cp, cpSync, createReadStream, createWriteStream, exists, existsSync, fchmod, fchmodSync, fchown, fchownSync, fdatasync, fdatasyncSync, fstat, fstatSync, fsync, fsyncSync, ftruncate, ftruncateSync, futimes, futimesSync, glob, globSync, lchmod, lchmodSync, lchown, lchownSync, link, linkSync, lstat, lstatSync, lutimes, lutimesSync, mkdir, mkdirSync, mkdtemp, mkdtempSync, open, openAsBlob, openSync, opendir, opendirSync, read, readFile, readFileSync, readSync, readdir, readdirSync, readlink, readlinkSync, readv, readvSync, realpath, realpathSync, rename, renameSync, rm, rmSync, rmdir, rmdirSync, stat, statSync, statfs, statfsSync, symlink, symlinkSync, truncate, truncateSync, unlink, unlinkSync, unwatchFile, utimes, utimesSync, watch, watchFile, write, writeFile, writeFileSync, writeSync, writev, writevSync, } = api;
221
767
  export default api;