cf-workers-native 0.1.5 → 0.1.6

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 +125 -56
  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 +118 -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 +226 -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 +582 -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 +282 -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,6 +1,14 @@
1
+ export { currentDirectory, changeDirectory } from "../process/directory.js";
2
+ import { Buffer } from "node:buffer";
1
3
  export declare function pathOf(value: any): string;
2
4
  export declare function temporaryPath(value: any): boolean;
3
5
  export declare function writablePath(value: any, syscall: string): string | number;
4
6
  export declare const temporary: any;
5
7
  export declare function clearTemporaryFiles(): void;
6
8
  export declare function runWithTemporaryFiles<T>(callback: () => T): T;
9
+ /** Retain the originating virtual volume for descriptor operations. */
10
+ export declare function retainTemporaryFiles(): <T>(operation: () => T) => T;
11
+ export declare function readonlyFile(value: any, follow?: boolean): boolean;
12
+ export declare function embeddedStat(path: any, options?: any): any;
13
+ export declare function readDescriptor(fd: number): Buffer;
14
+ export declare function descriptorFlags(fd: number): number;
@@ -1,3 +1,6 @@
1
+ import { currentDirectory, runWithDirectory, registerDirectoryValidator, } from "../process/directory.js";
2
+ export { currentDirectory, changeDirectory } from "../process/directory.js";
3
+ import * as embedded from "./embedded.js";
1
4
  import { fileMode } from "./mode.js";
2
5
  import { registerRequestScope } from "../../shared/request-scope.js";
3
6
  // Writable, memory-only /tmp. Embedded bundle files remain read-only.
@@ -5,35 +8,251 @@ import { registerRequestScope } from "../../shared/request-scope.js";
5
8
  import { Volume, createFsFromVolume } from "memfs";
6
9
  import { Buffer } from "node:buffer";
7
10
  import { posix } from "node:path";
8
- import { ERR_INVALID_ARG_TYPE } from "../net/errors.js";
11
+ import { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE } from "../net/errors.js";
9
12
  import { AsyncLocalStorage } from "../async-hooks/index.js";
10
13
  export function pathOf(value) {
14
+ let url;
11
15
  if (value instanceof URL)
12
- value = decodeURIComponent(value.pathname);
13
- if (Buffer.isBuffer(value))
14
- value = value.toString();
15
- if (typeof value !== "string")
16
- throw new ERR_INVALID_ARG_TYPE("path", ["string", "Buffer", "URL"], value);
17
- return posix.resolve("/bundle", value);
16
+ url = value;
17
+ else {
18
+ if (Buffer.isBuffer(value))
19
+ value = value.toString();
20
+ if (typeof value !== "string")
21
+ throw new ERR_INVALID_ARG_TYPE("path", ["string", "Buffer", "URL"], value);
22
+ if (value.includes("\0"))
23
+ throw new ERR_INVALID_ARG_VALUE("path", value, "must not contain null bytes");
24
+ url = new URL(value.replace(/[#?]/g, encodeURIComponent).replace(/\/\//g, "/"), "file://" + currentDirectory() + "/");
25
+ }
26
+ if (url.protocol !== "file:")
27
+ throw new TypeError("File path must be a file: URL");
28
+ if (url.host)
29
+ throw new Error("File path must not have a host");
30
+ const normalized = posix.normalize(url.pathname.replace(/%([0-9a-f]{2})/gi, (_match, hex) => {
31
+ const char = String.fromCharCode(parseInt(hex, 16));
32
+ return /[A-Za-z0-9._~-]/.test(char) ? char : "%" + hex.toUpperCase();
33
+ }));
34
+ if (Buffer.byteLength(normalized) > 4096)
35
+ throw new Error("File path is too long");
36
+ if ((normalized.match(/\//g) || []).length > 48)
37
+ throw new Error("File path has too many segments");
38
+ return normalized.length > 1 ? normalized.replace(/\/$/, "") : normalized;
18
39
  }
40
+ const devices = new Set(["/dev/null", "/dev/zero", "/dev/full", "/dev/random"]);
19
41
  export function temporaryPath(value) {
20
42
  if (typeof value === "number")
21
43
  return true;
22
44
  const path = pathOf(value);
23
- return path === "/tmp" || path.startsWith("/tmp/");
45
+ return (path === "/tmp" ||
46
+ path.startsWith("/tmp/") ||
47
+ path === "/dev" ||
48
+ devices.has(path));
24
49
  }
25
50
  export function writablePath(value, syscall) {
26
51
  if (typeof value === "number")
27
52
  return value;
28
53
  const path = pathOf(value);
29
- if (!(path === "/tmp" || path.startsWith("/tmp/")))
30
- throw Object.assign(new Error(`EROFS: read-only file system, ${syscall} '${path}'`), { code: "EROFS", errno: -30, syscall, path });
54
+ if (!(path === "/tmp" ||
55
+ path.startsWith("/tmp/") ||
56
+ (devices.has(path) &&
57
+ [
58
+ "writeFile",
59
+ "appendFile",
60
+ "truncate",
61
+ "utimes",
62
+ "lutimes",
63
+ "createWriteStream",
64
+ "WriteStream",
65
+ ].includes(syscall))))
66
+ throw Object.assign(new Error(`operation not permitted, ${syscall} '${path}'`), { code: "EPERM", errno: -1, syscall, path });
31
67
  return path;
32
68
  }
33
69
  function createTemporary() {
34
70
  const volume = new Volume();
71
+ // memfs supplies storage, while Workers keeps timestamps unchanged on writes
72
+ // and caps every file at 128 MiB. Configure nodes at this owned boundary so
73
+ // descriptors, FileHandles and streams cannot bypass these rules.
74
+ const core = volume._core;
75
+ let nextFd = 3;
76
+ // Workers allocates monotonically within a volume. Reusing a closed number
77
+ // would let a stale FileHandle access or close an unrelated descriptor.
78
+ core.releasedFds.push = () => 0;
79
+ core.newFdNumber = () => {
80
+ if (nextFd === 2147483647)
81
+ throw Object.assign(new Error("Too many open files"), { code: "EMFILE" });
82
+ return nextFd++;
83
+ };
84
+ const createNode = core.createNode.bind(core);
85
+ core.createNode = (...args) => {
86
+ const node = createNode(...args);
87
+ node.mtime = node.btime = new Date(0);
88
+ node.touch = () => { };
89
+ const write = node.write.bind(node), truncate = node.truncate.bind(node), set = node._setBuf.bind(node);
90
+ const limit = (size) => {
91
+ if (size > 134217728)
92
+ throw Object.assign(new Error("File size limit exceeded"), {
93
+ code: "EPERM",
94
+ });
95
+ };
96
+ node.write = (buffer, offset = 0, length = buffer.length, position = 0) => {
97
+ limit(position + length);
98
+ return write(buffer, offset, length, position);
99
+ };
100
+ node.truncate = (length = 0) => {
101
+ limit(length);
102
+ return truncate(length);
103
+ };
104
+ node._setBuf = (buffer) => {
105
+ limit(buffer.byteLength);
106
+ return set(buffer);
107
+ };
108
+ return node;
109
+ };
110
+ core.root.getNode().mtime = core.root.getNode().btime = new Date(0);
35
111
  volume.mkdirSync("/tmp");
36
112
  const fs = createFsFromVolume(volume);
113
+ function installDevices() {
114
+ fs.mkdirSync("/dev");
115
+ for (const path of devices) {
116
+ fs.writeFileSync(path, "");
117
+ const node = core.getResolvedLinkOrThrow(path, "open").getNode();
118
+ node.mode = 0o20666;
119
+ const rejected = () => {
120
+ throw Object.assign(new Error("operation not permitted"), {
121
+ code: "EPERM",
122
+ });
123
+ };
124
+ node.write =
125
+ path === "/dev/full" || path === "/dev/random"
126
+ ? rejected
127
+ : (_buffer, _offset, length) => length;
128
+ node.truncate =
129
+ path === "/dev/full" || path === "/dev/random" ? rejected : () => { };
130
+ node._setBuf =
131
+ path === "/dev/full" || path === "/dev/random" ? rejected : () => { };
132
+ node.read = (buffer, offset = 0, length = buffer.byteLength) => {
133
+ if (path === "/dev/null")
134
+ return 0;
135
+ const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset + offset, length);
136
+ if (path === "/dev/random")
137
+ for (let n = 0; n < bytes.length; n += 65536)
138
+ bytes.set(globalThis.crypto.getRandomValues(new Uint8Array(Math.min(65536, bytes.length - n))), n);
139
+ else
140
+ bytes.fill(0);
141
+ return length;
142
+ };
143
+ }
144
+ }
145
+ installDevices();
146
+ for (let fd = 0; fd < 3; fd++) {
147
+ const path = "/tmp/.stdio-" + fd, allocated = fs.openSync(path, "w+");
148
+ const file = core.getFileByFdOrThrow(allocated, "stdio");
149
+ delete core.fds[String(allocated)];
150
+ file.fd = fd;
151
+ core.fds[String(fd)] = file;
152
+ fs.unlinkSync(path);
153
+ let pending = "";
154
+ file.node.read = () => 0;
155
+ file.node.write = (buffer, offset = 0, length = buffer.byteLength) => {
156
+ pending += Buffer.from(buffer.buffer, buffer.byteOffset + offset, length).toString();
157
+ const lines = pending.split("\n");
158
+ pending = lines.pop();
159
+ for (const line of lines)
160
+ (fd === 2 ? console.error : console.log)(line);
161
+ return length;
162
+ };
163
+ }
164
+ nextFd = 3;
165
+ const closeSync = fs.closeSync.bind(fs), close = fs.close.bind(fs);
166
+ fs.closeSync = (fd) => {
167
+ if (typeof fd === "number" && fd >= 0 && fd <= 2 && Number.isInteger(fd))
168
+ return;
169
+ return closeSync(fd);
170
+ };
171
+ fs.close = (fd, callback) => {
172
+ if (typeof fd === "number" && fd >= 0 && fd <= 2 && Number.isInteger(fd)) {
173
+ if (typeof callback !== "function")
174
+ throw new ERR_INVALID_ARG_TYPE("callback", "function", callback);
175
+ queueMicrotask(() => callback(null));
176
+ return;
177
+ }
178
+ return close(fd, callback);
179
+ };
180
+ const readonlyDescriptors = new Set();
181
+ const readonlyInodes = new Set();
182
+ const denied = (syscall, path) => Object.assign(new Error("operation not permitted"), {
183
+ code: "EPERM",
184
+ errno: -1,
185
+ syscall,
186
+ ...(path ? { path } : {}),
187
+ });
188
+ function mount(path) {
189
+ if (temporaryPath(path) ||
190
+ (fs.existsSync(path) && fs.statSync(path).isFile()))
191
+ return;
192
+ let stat;
193
+ try {
194
+ stat = embedded.statSync(path);
195
+ }
196
+ catch (error) {
197
+ if (error.code === "ENOENT")
198
+ return;
199
+ throw error;
200
+ }
201
+ if (stat.isDirectory()) {
202
+ fs.mkdirSync(path, { recursive: true });
203
+ for (const name of embedded.readdirSync(path))
204
+ mount(posix.join(path, name));
205
+ }
206
+ else {
207
+ fs.mkdirSync(posix.dirname(path), { recursive: true });
208
+ fs.writeFileSync(path, embedded.readFileSync(path));
209
+ readonlyInodes.add(fs.statSync(path).ino);
210
+ }
211
+ }
212
+ function resolved(path) {
213
+ let parent = path;
214
+ const missing = [];
215
+ while (!fs.existsSync(parent) && parent !== "/") {
216
+ missing.unshift(posix.basename(parent));
217
+ parent = posix.dirname(parent);
218
+ }
219
+ return posix.join(fs.realpathSync(parent), ...missing);
220
+ }
221
+ function mutable(value, syscall, follow = true) {
222
+ if (typeof value === "number") {
223
+ if (readonlyDescriptors.has(value))
224
+ throw denied(syscall);
225
+ return value;
226
+ }
227
+ const path = writablePath(value, syscall);
228
+ const target = follow
229
+ ? resolved(path)
230
+ : posix.join(resolved(posix.dirname(path)), posix.basename(path));
231
+ if (!temporaryPath(target) ||
232
+ (follow &&
233
+ fs.existsSync(target) &&
234
+ readonlyInodes.has(fs.statSync(target).ino)))
235
+ throw denied(syscall, path);
236
+ return path;
237
+ }
238
+ function openPath(value, flags = "r") {
239
+ const path = pathOf(value);
240
+ mount(path);
241
+ const target = resolved(path);
242
+ const writes = typeof flags === "number"
243
+ ? !!(flags &
244
+ (fs.constants.O_WRONLY |
245
+ fs.constants.O_RDWR |
246
+ fs.constants.O_CREAT |
247
+ fs.constants.O_TRUNC |
248
+ fs.constants.O_APPEND))
249
+ : typeof flags === "string" && !["r", "rs", "sr"].includes(flags);
250
+ const readonly = !temporaryPath(target) ||
251
+ (fs.existsSync(target) && readonlyInodes.has(fs.statSync(target).ino));
252
+ if (readonly && writes)
253
+ throw denied("open", path);
254
+ return { path, readonly };
255
+ }
37
256
  const mutating = new Set([
38
257
  "appendFile",
39
258
  "writeFile",
@@ -79,22 +298,27 @@ function createTemporary() {
79
298
  };
80
299
  }
81
300
  if (base === "symlink") {
82
- args[1] = writablePath(args[1], base);
301
+ args[1] = mutable(args[1], base, false);
83
302
  const target = Buffer.isBuffer(args[0])
84
303
  ? args[0].toString()
85
304
  : args[0];
86
305
  if (typeof target !== "string")
87
306
  throw new ERR_INVALID_ARG_TYPE("target", ["string", "Buffer"], target);
88
- writablePath(posix.resolve(posix.dirname(args[1]), target), base);
307
+ const absolute = pathOf(target);
308
+ mount(absolute);
309
+ args[0] = absolute;
89
310
  }
90
- else if (["rename", "copyFile", "cp", "link"].includes(base)) {
91
- args[0] = writablePath(args[0], base);
92
- args[1] = writablePath(args[1], base);
311
+ else if (["copyFile", "cp", "link"].includes(base)) {
312
+ args[0] = pathOf(args[0]);
313
+ mount(args[0]);
314
+ args[1] = mutable(args[1], base, base !== "link");
315
+ }
316
+ else if (base === "rename") {
317
+ args[0] = mutable(args[0], base, false);
318
+ args[1] = mutable(args[1], base, false);
93
319
  }
94
- else if (mutating.has(base) ||
95
- base === "open" ||
96
- base === "createWriteStream")
97
- args[0] = writablePath(args[0], base);
320
+ else if (mutating.has(base) || base === "createWriteStream")
321
+ args[0] = mutable(args[0], base, !["unlink", "rm", "rmdir", "mkdir"].includes(base));
98
322
  else if (typeof args[0] === "string" ||
99
323
  args[0] instanceof URL ||
100
324
  Buffer.isBuffer(args[0]))
@@ -108,14 +332,152 @@ function createTemporary() {
108
332
  }
109
333
  throw error;
110
334
  }
335
+ if (["write", "writev", "ftruncate"].includes(base) &&
336
+ readonlyDescriptors.has(args[0])) {
337
+ const error = denied(base);
338
+ const callback = args[args.length - 1];
339
+ if (!name.endsWith("Sync") && typeof callback === "function") {
340
+ queueMicrotask(() => callback(error));
341
+ return;
342
+ }
343
+ throw error;
344
+ }
345
+ if (base === "read" &&
346
+ typeof args[2] === "number" &&
347
+ args[3] === undefined &&
348
+ args[1]?.byteLength !== undefined)
349
+ args[3] = args[1].byteLength - args[2];
350
+ if (base === "close")
351
+ readonlyDescriptors.delete(args[0]);
111
352
  return fs[name](...args);
112
353
  };
113
354
  }
355
+ api.openSync = (path, flags = "r", mode) => {
356
+ if (typeof flags === "number" && !(flags & 3))
357
+ flags &= ~512;
358
+ const entry = openPath(path, flags);
359
+ const fd = fs.openSync(entry.path, flags, mode);
360
+ if (entry.readonly)
361
+ readonlyDescriptors.add(fd);
362
+ return fd;
363
+ };
364
+ api.open = (path, flags, mode, callback) => {
365
+ if (typeof mode === "function") {
366
+ callback = mode;
367
+ mode = undefined;
368
+ }
369
+ let fd, error = null;
370
+ try {
371
+ fd = api.openSync(path, flags, mode);
372
+ }
373
+ catch (failure) {
374
+ error = failure;
375
+ }
376
+ queueMicrotask(() => callback(error, fd));
377
+ };
378
+ api.createReadStream = (path, options) => {
379
+ if (typeof options?.fd === "number")
380
+ return fs.createReadStream(path, options);
381
+ const entry = openPath(path, options?.flags);
382
+ const stream = fs.createReadStream(entry.path, options);
383
+ if (entry.readonly) {
384
+ stream.prependListener("open", (fd) => readonlyDescriptors.add(fd));
385
+ let fd;
386
+ stream.on("open", (value) => {
387
+ fd = value;
388
+ });
389
+ stream.on("close", () => {
390
+ if (fd !== undefined)
391
+ readonlyDescriptors.delete(fd);
392
+ });
393
+ }
394
+ return stream;
395
+ };
396
+ api.promises = {
397
+ ...fs.promises,
398
+ open: async (path, flags = "r", mode) => {
399
+ if (typeof flags === "number" && !(flags & 3))
400
+ flags &= ~512;
401
+ const entry = openPath(path, flags);
402
+ const handle = await fs.promises.open(entry.path, flags, mode);
403
+ handle.readFile = async (options = {}) => {
404
+ const encoding = typeof options === "string" ? options : options?.encoding;
405
+ const size = (await handle.stat()).size;
406
+ const buffer = Buffer.alloc(size);
407
+ const { bytesRead } = await handle.read(buffer, 0, size, 0);
408
+ core.getFileByFdOrThrow(handle.fd, "readFile").position = size;
409
+ return encoding
410
+ ? buffer.subarray(0, bytesRead).toString(encoding)
411
+ : buffer.subarray(0, bytesRead);
412
+ };
413
+ for (const name of [
414
+ "write",
415
+ "writev",
416
+ "writeFile",
417
+ "appendFile",
418
+ "truncate",
419
+ ]) {
420
+ const operation = handle[name].bind(handle);
421
+ handle[name] = async (...args) => {
422
+ await handle.stat();
423
+ if (entry.readonly)
424
+ throw denied(name);
425
+ return operation(...args);
426
+ };
427
+ }
428
+ if (entry.readonly) {
429
+ readonlyDescriptors.add(handle.fd);
430
+ const close = handle.close.bind(handle);
431
+ handle.close = async () => {
432
+ readonlyDescriptors.delete(handle.fd);
433
+ return close();
434
+ };
435
+ }
436
+ return handle;
437
+ },
438
+ };
439
+ for (const name of [
440
+ ...mutating,
441
+ "rename",
442
+ "copyFile",
443
+ "cp",
444
+ "link",
445
+ "symlink",
446
+ ])
447
+ api.promises[name] = (...args) => new Promise((resolve, reject) => api[name](...args, (error, value) => error ? reject(error) : resolve(value)));
114
448
  return {
449
+ descriptorFlags(fd) {
450
+ return core.getFileByFdOrThrow(fd, "write").flags;
451
+ },
452
+ readDescriptor(fd) {
453
+ const file = core.getFileByFdOrThrow(fd, "read");
454
+ const data = Buffer.from(file.node.getBuffer());
455
+ file.position = data.length;
456
+ return data;
457
+ },
115
458
  api,
459
+ statEmbedded(path, options) {
460
+ const normalized = pathOf(path);
461
+ mount(normalized);
462
+ return fs.statSync(normalized, options);
463
+ },
464
+ readonly(value, follow = true) {
465
+ if (typeof value === "number")
466
+ return readonlyDescriptors.has(value);
467
+ const path = pathOf(value);
468
+ const target = follow ? resolved(path) : path;
469
+ return (target === "/dev" ||
470
+ !temporaryPath(target) ||
471
+ (fs.existsSync(target) &&
472
+ readonlyInodes.has((follow ? fs.statSync : fs.lstatSync)(target).ino)));
473
+ },
116
474
  clear() {
117
- for (const name of fs.readdirSync("/tmp"))
118
- fs.rmSync(`/tmp/${name}`, { recursive: true, force: true });
475
+ for (const name of fs.readdirSync("/"))
476
+ fs.rmSync(`/${name}`, { recursive: true, force: true });
477
+ fs.mkdirSync("/tmp");
478
+ installDevices();
479
+ readonlyDescriptors.clear();
480
+ readonlyInodes.clear();
119
481
  },
120
482
  };
121
483
  }
@@ -137,6 +499,34 @@ export function clearTemporaryFiles() {
137
499
  active().clear();
138
500
  }
139
501
  export function runWithTemporaryFiles(callback) {
140
- return contexts.run(createTemporary(), callback);
502
+ return runWithDirectory(() => contexts.run(createTemporary(), callback));
141
503
  }
142
504
  registerRequestScope(runWithTemporaryFiles);
505
+ /** Retain the originating virtual volume for descriptor operations. */
506
+ export function retainTemporaryFiles() {
507
+ const volume = active();
508
+ return (operation) => contexts.run(volume, operation);
509
+ }
510
+ export function readonlyFile(value, follow = true) {
511
+ return active().readonly(value, follow);
512
+ }
513
+ export function embeddedStat(path, options) {
514
+ return active().statEmbedded(path, options);
515
+ }
516
+ registerDirectoryValidator((path) => {
517
+ const normalized = pathOf(path);
518
+ const stat = active().statEmbedded(normalized);
519
+ if (!stat.isDirectory())
520
+ throw Object.assign(new Error("not a directory"), {
521
+ code: "ENOTDIR",
522
+ syscall: "chdir",
523
+ path: normalized,
524
+ });
525
+ return normalized;
526
+ });
527
+ export function readDescriptor(fd) {
528
+ return active().readDescriptor(fd);
529
+ }
530
+ export function descriptorFlags(fd) {
531
+ return active().descriptorFlags(fd);
532
+ }
@@ -1,9 +1,12 @@
1
+ import { WebSocket } from "../../browser/websocket/endpoint.js";
2
+ import { CloseEvent } from "../../browser/websocket/close-event.js";
1
3
  import { asyncDispose } from "../../shared/globals/symbols.js";
2
4
  import { Readable, Writable } from "node:stream";
3
5
  import { EventEmitter } from "node:events";
4
6
  import { Buffer } from "node:buffer";
5
7
  import { kSetIncomingBody, kSetIncomingFetchResponse, kSetIncomingSocket } from "./registry.js";
6
8
  import type { AgentOptions, IncomingHttpHeaders, OutgoingHttpHeader, OutgoingHttpHeaders, RequestOptions, ServerOptions } from "node:http";
9
+ import { kIncomingMessage, kServerResponse, kUniqueHeaders } from "./symbols.js";
7
10
  export declare const METHODS: string[];
8
11
  export declare const STATUS_CODES: Record<number, string>;
9
12
  export declare const maxHeaderSize = 16384;
@@ -41,6 +44,7 @@ export declare class OutgoingMessage extends Writable {
41
44
  _onPendingData: (delta: number) => void;
42
45
  constructor(_req?: IncomingMessage, options?: {
43
46
  highWaterMark?: number;
47
+ rejectNonStandardBodyWrites?: boolean;
44
48
  });
45
49
  get headersSent(): boolean;
46
50
  setHeader(name: string, value: number | string | readonly string[]): this;
@@ -172,8 +176,9 @@ export declare class Server extends EventEmitter {
172
176
  keepAliveTimeoutBuffer: number;
173
177
  highWaterMark: number;
174
178
  private port?;
175
- private IncomingMessageClass;
176
- private ServerResponseClass;
179
+ [kIncomingMessage]: typeof IncomingMessage;
180
+ [kServerResponse]: typeof ServerResponse;
181
+ [kUniqueHeaders]: Set<string> | null;
177
182
  constructor(options?: ServerOptions | RequestListener, listener?: RequestListener);
178
183
  [captureRejection](error: unknown, event: string | symbol, ...args: unknown[]): void;
179
184
  get listening(): boolean;
@@ -242,8 +247,7 @@ export declare class ClientRequest extends OutgoingMessage {
242
247
  timeout?: number;
243
248
  _ended: boolean;
244
249
  private abortController;
245
- private upload?;
246
- private uploadWriter?;
250
+ private upload;
247
251
  private response?;
248
252
  private timer?;
249
253
  private sent;
@@ -268,18 +272,7 @@ export declare function get(url: string | URL | RequestOptions, options?: Reques
268
272
  export declare function createServer(options?: ServerOptions | RequestListener, listener?: RequestListener): Server;
269
273
  export declare function setMaxIdleHTTPParsers(max: unknown): never;
270
274
  export declare function _connectionListener(): never;
271
- export declare const WebSocket: {
272
- new (url: string | URL, protocols?: string | string[]): WebSocket;
273
- prototype: WebSocket;
274
- readonly CONNECTING: 0;
275
- readonly OPEN: 1;
276
- readonly CLOSING: 2;
277
- readonly CLOSED: 3;
278
- };
279
- export declare const CloseEvent: {
280
- new (type: string, eventInitDict?: CloseEventInit): CloseEvent;
281
- prototype: CloseEvent;
282
- };
275
+ export { WebSocket, CloseEvent };
283
276
  export declare const MessageEvent: {
284
277
  new <T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>;
285
278
  prototype: MessageEvent;
@@ -302,18 +295,8 @@ declare const _default: {
302
295
  maxHeaderSize: number;
303
296
  setMaxIdleHTTPParsers: typeof setMaxIdleHTTPParsers;
304
297
  _connectionListener: typeof _connectionListener;
305
- WebSocket: {
306
- new (url: string | URL, protocols?: string | string[]): WebSocket;
307
- prototype: WebSocket;
308
- readonly CONNECTING: 0;
309
- readonly OPEN: 1;
310
- readonly CLOSING: 2;
311
- readonly CLOSED: 3;
312
- };
313
- CloseEvent: {
314
- new (type: string, eventInitDict?: CloseEventInit): CloseEvent;
315
- prototype: CloseEvent;
316
- };
298
+ WebSocket: typeof WebSocket;
299
+ CloseEvent: typeof CloseEvent;
317
300
  MessageEvent: {
318
301
  new <T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>;
319
302
  prototype: MessageEvent;