@trpc/server 11.0.0-rc.348 → 11.0.0-rc.354

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 (160) hide show
  1. package/dist/@trpc/server/http.d.ts +1 -0
  2. package/dist/@trpc/server/http.d.ts.map +1 -1
  3. package/dist/@trpc/server/index.d.ts +1 -2
  4. package/dist/@trpc/server/index.d.ts.map +1 -1
  5. package/dist/adapters/aws-lambda/index.d.ts.map +1 -1
  6. package/dist/adapters/aws-lambda/index.js +9 -19
  7. package/dist/adapters/aws-lambda/index.mjs +9 -19
  8. package/dist/adapters/aws-lambda/utils.d.ts +12 -3
  9. package/dist/adapters/aws-lambda/utils.d.ts.map +1 -1
  10. package/dist/adapters/aws-lambda/utils.js +1 -12
  11. package/dist/adapters/aws-lambda/utils.mjs +2 -12
  12. package/dist/adapters/express.d.ts.map +1 -1
  13. package/dist/adapters/express.js +1 -0
  14. package/dist/adapters/express.mjs +1 -0
  15. package/dist/adapters/fastify/fastifyRequestHandler.d.ts +9 -1
  16. package/dist/adapters/fastify/fastifyRequestHandler.d.ts.map +1 -1
  17. package/dist/adapters/fastify/fastifyRequestHandler.js +2 -10
  18. package/dist/adapters/fastify/fastifyRequestHandler.mjs +2 -10
  19. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts +1 -1
  20. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts.map +1 -1
  21. package/dist/adapters/fetch/fetchRequestHandler.d.ts +5 -1
  22. package/dist/adapters/fetch/fetchRequestHandler.d.ts.map +1 -1
  23. package/dist/adapters/fetch/fetchRequestHandler.js +2 -16
  24. package/dist/adapters/fetch/fetchRequestHandler.mjs +2 -16
  25. package/dist/adapters/fetch/types.d.ts +12 -9
  26. package/dist/adapters/fetch/types.d.ts.map +1 -1
  27. package/dist/adapters/next-app-dir/nextAppDirCaller.d.ts +7 -2
  28. package/dist/adapters/next-app-dir/nextAppDirCaller.d.ts.map +1 -1
  29. package/dist/adapters/next.d.ts.map +1 -1
  30. package/dist/adapters/next.js +1 -0
  31. package/dist/adapters/next.mjs +1 -0
  32. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts +73 -0
  33. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.d.ts.map +1 -0
  34. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.js +161 -0
  35. package/dist/adapters/node-http/content-type/form-data/fileUploadHandler.mjs +157 -0
  36. package/dist/adapters/node-http/content-type/form-data/index.d.ts +25 -4
  37. package/dist/adapters/node-http/content-type/form-data/index.d.ts.map +1 -1
  38. package/dist/adapters/node-http/content-type/form-data/index.js +128 -25
  39. package/dist/adapters/node-http/content-type/form-data/index.mjs +103 -25
  40. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts +31 -0
  41. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.d.ts.map +1 -0
  42. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.js +29 -0
  43. package/dist/adapters/node-http/content-type/form-data/memoryUploadHandler.mjs +27 -0
  44. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts +16 -0
  45. package/dist/adapters/node-http/content-type/form-data/streamSlice.d.ts.map +1 -0
  46. package/dist/adapters/node-http/content-type/form-data/streamSlice.js +46 -0
  47. package/dist/adapters/node-http/content-type/form-data/streamSlice.mjs +44 -0
  48. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts +45 -0
  49. package/dist/adapters/node-http/content-type/form-data/uploadHandler.d.ts.map +1 -0
  50. package/dist/adapters/node-http/content-type/form-data/uploadHandler.js +30 -0
  51. package/dist/adapters/node-http/content-type/form-data/uploadHandler.mjs +26 -0
  52. package/dist/adapters/node-http/content-type/json/getPostBody.d.ts.map +1 -1
  53. package/dist/adapters/node-http/content-type/json/getPostBody.js +12 -4
  54. package/dist/adapters/node-http/content-type/json/getPostBody.mjs +12 -4
  55. package/dist/adapters/node-http/content-type/json/index.d.ts +1 -4
  56. package/dist/adapters/node-http/content-type/json/index.d.ts.map +1 -1
  57. package/dist/adapters/node-http/content-type/json/index.js +10 -59
  58. package/dist/adapters/node-http/content-type/json/index.mjs +10 -59
  59. package/dist/adapters/node-http/internals/contentType.d.ts +9 -0
  60. package/dist/adapters/node-http/internals/contentType.d.ts.map +1 -0
  61. package/dist/adapters/node-http/internals/contentType.js +8 -0
  62. package/dist/adapters/node-http/internals/contentType.mjs +6 -0
  63. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
  64. package/dist/adapters/node-http/nodeHTTPRequestHandler.js +21 -19
  65. package/dist/adapters/node-http/nodeHTTPRequestHandler.mjs +22 -20
  66. package/dist/adapters/node-http/types.d.ts +19 -8
  67. package/dist/adapters/node-http/types.d.ts.map +1 -1
  68. package/dist/adapters/standalone.d.ts.map +1 -1
  69. package/dist/adapters/standalone.js +1 -0
  70. package/dist/adapters/standalone.mjs +1 -0
  71. package/dist/adapters/ws.d.ts +12 -2
  72. package/dist/adapters/ws.d.ts.map +1 -1
  73. package/dist/bundle-analysis.json +225 -219
  74. package/dist/http.js +2 -0
  75. package/dist/http.mjs +1 -0
  76. package/dist/index.js +0 -2
  77. package/dist/index.mjs +0 -1
  78. package/dist/unstable-core-do-not-import/http/contentType.d.ts +15 -7
  79. package/dist/unstable-core-do-not-import/http/contentType.d.ts.map +1 -1
  80. package/dist/unstable-core-do-not-import/http/contentType.js +54 -0
  81. package/dist/unstable-core-do-not-import/http/contentType.mjs +52 -0
  82. package/dist/unstable-core-do-not-import/http/index.d.ts +1 -0
  83. package/dist/unstable-core-do-not-import/http/index.d.ts.map +1 -1
  84. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.d.ts +5 -5
  85. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.d.ts.map +1 -1
  86. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.js +22 -25
  87. package/dist/unstable-core-do-not-import/http/resolveHTTPResponse.mjs +22 -25
  88. package/dist/unstable-core-do-not-import/http/types.d.ts +2 -0
  89. package/dist/unstable-core-do-not-import/http/types.d.ts.map +1 -1
  90. package/dist/unstable-core-do-not-import/initTRPC.d.ts +1 -1
  91. package/dist/unstable-core-do-not-import/initTRPC.d.ts.map +1 -1
  92. package/dist/unstable-core-do-not-import/rootConfig.d.ts +0 -21
  93. package/dist/unstable-core-do-not-import/rootConfig.d.ts.map +1 -1
  94. package/dist/unstable-core-do-not-import.js +2 -0
  95. package/dist/unstable-core-do-not-import.mjs +1 -0
  96. package/package.json +3 -2
  97. package/src/@trpc/server/http.ts +1 -0
  98. package/src/@trpc/server/index.ts +1 -4
  99. package/src/adapters/aws-lambda/index.ts +9 -24
  100. package/src/adapters/aws-lambda/utils.ts +15 -21
  101. package/src/adapters/express.ts +6 -1
  102. package/src/adapters/fastify/fastifyRequestHandler.ts +21 -15
  103. package/src/adapters/fastify/fastifyTRPCPlugin.ts +1 -1
  104. package/src/adapters/fetch/fetchRequestHandler.ts +10 -22
  105. package/src/adapters/fetch/types.ts +15 -22
  106. package/src/adapters/next-app-dir/nextAppDirCaller.ts +9 -2
  107. package/src/adapters/next.ts +6 -1
  108. package/src/adapters/node-http/content-type/form-data/fileUploadHandler.ts +277 -0
  109. package/src/adapters/node-http/content-type/form-data/index.ts +159 -33
  110. package/src/adapters/node-http/content-type/form-data/memoryUploadHandler.ts +56 -0
  111. package/src/adapters/node-http/content-type/form-data/streamSlice.ts +56 -0
  112. package/src/adapters/node-http/content-type/form-data/uploadHandler.ts +89 -0
  113. package/src/adapters/node-http/content-type/json/getPostBody.ts +18 -9
  114. package/src/adapters/node-http/content-type/json/index.ts +7 -87
  115. package/src/adapters/node-http/{content-type/types.ts → internals/contentType.ts} +14 -2
  116. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +35 -22
  117. package/src/adapters/node-http/types.ts +46 -46
  118. package/src/adapters/standalone.ts +2 -1
  119. package/src/adapters/ws.ts +14 -9
  120. package/src/unstable-core-do-not-import/http/contentType.ts +85 -10
  121. package/src/unstable-core-do-not-import/http/index.ts +1 -0
  122. package/src/unstable-core-do-not-import/http/resolveHTTPResponse.ts +28 -29
  123. package/src/unstable-core-do-not-import/http/types.ts +2 -0
  124. package/src/unstable-core-do-not-import/initTRPC.ts +1 -0
  125. package/src/unstable-core-do-not-import/rootConfig.ts +0 -31
  126. package/dist/adapters/aws-lambda/content-type/json/index.d.ts +0 -10
  127. package/dist/adapters/aws-lambda/content-type/json/index.d.ts.map +0 -1
  128. package/dist/adapters/aws-lambda/content-type/json/index.js +0 -59
  129. package/dist/adapters/aws-lambda/content-type/json/index.mjs +0 -57
  130. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.d.ts +0 -10
  131. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.d.ts.map +0 -1
  132. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.js +0 -33
  133. package/dist/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.mjs +0 -31
  134. package/dist/adapters/fastify/content-type/json/index.d.ts +0 -8
  135. package/dist/adapters/fastify/content-type/json/index.d.ts.map +0 -1
  136. package/dist/adapters/fastify/content-type/json/index.js +0 -59
  137. package/dist/adapters/fastify/content-type/json/index.mjs +0 -57
  138. package/dist/adapters/fastify/types.d.ts +0 -11
  139. package/dist/adapters/fastify/types.d.ts.map +0 -1
  140. package/dist/adapters/fetch/content-type/json/index.d.ts +0 -9
  141. package/dist/adapters/fetch/content-type/json/index.d.ts.map +0 -1
  142. package/dist/adapters/fetch/content-type/json/index.js +0 -58
  143. package/dist/adapters/fetch/content-type/json/index.mjs +0 -56
  144. package/dist/adapters/node-http/content-type/octet/index.d.ts +0 -5
  145. package/dist/adapters/node-http/content-type/octet/index.d.ts.map +0 -1
  146. package/dist/adapters/node-http/content-type/octet/index.js +0 -19
  147. package/dist/adapters/node-http/content-type/octet/index.mjs +0 -17
  148. package/dist/adapters/node-http/content-type/types.d.ts +0 -8
  149. package/dist/adapters/node-http/content-type/types.d.ts.map +0 -1
  150. package/dist/unstable-core-do-not-import/contentTypeParsers.d.ts +0 -16
  151. package/dist/unstable-core-do-not-import/contentTypeParsers.d.ts.map +0 -1
  152. package/dist/unstable-core-do-not-import/contentTypeParsers.js +0 -23
  153. package/dist/unstable-core-do-not-import/contentTypeParsers.mjs +0 -21
  154. package/src/adapters/aws-lambda/content-type/json/index.ts +0 -99
  155. package/src/adapters/content-handlers/selectContentHandlerOrUnsupportedMediaType.ts +0 -45
  156. package/src/adapters/fastify/content-type/json/index.ts +0 -97
  157. package/src/adapters/fastify/types.ts +0 -22
  158. package/src/adapters/fetch/content-type/json/index.ts +0 -94
  159. package/src/adapters/node-http/content-type/octet/index.ts +0 -27
  160. package/src/unstable-core-do-not-import/contentTypeParsers.ts +0 -37
@@ -0,0 +1,73 @@
1
+ /// <reference types="node" />
2
+ import type { UploadHandler } from './uploadHandler';
3
+ export declare function readableStreamToString(stream: ReadableStream<Uint8Array>, encoding?: BufferEncoding): Promise<string>;
4
+ export type FileUploadHandlerFilterArgs = {
5
+ filename: string;
6
+ contentType: string;
7
+ name: string;
8
+ };
9
+ export type FileUploadHandlerPathResolverArgs = {
10
+ filename: string;
11
+ contentType: string;
12
+ name: string;
13
+ };
14
+ /**
15
+ * Chooses the path of the file to be uploaded. If a string is not
16
+ * returned the file will not be written.
17
+ */
18
+ export type FileUploadHandlerPathResolver = (args: FileUploadHandlerPathResolverArgs) => string | undefined;
19
+ export type FileUploadHandlerOptions = {
20
+ /**
21
+ * Avoid file conflicts by appending a count on the end of the filename
22
+ * if it already exists on disk. Defaults to `true`.
23
+ */
24
+ avoidFileConflicts?: boolean;
25
+ /**
26
+ * The directory to write the upload.
27
+ */
28
+ directory?: FileUploadHandlerPathResolver | string;
29
+ /**
30
+ * The name of the file in the directory. Can be a relative path, the directory
31
+ * structure will be created if it does not exist.
32
+ */
33
+ file?: FileUploadHandlerPathResolver;
34
+ /**
35
+ * The maximum upload size allowed. If the size is exceeded an error will be thrown.
36
+ * Defaults to 3000000B (3MB).
37
+ */
38
+ maxPartSize?: number;
39
+ /**
40
+ *
41
+ * @param filename
42
+ * @param contentType
43
+ * @param name
44
+ */
45
+ filter?(args: FileUploadHandlerFilterArgs): Promise<boolean> | boolean;
46
+ };
47
+ export declare function createFileUploadHandler({ directory, avoidFileConflicts, file, filter, maxPartSize, }?: FileUploadHandlerOptions): UploadHandler;
48
+ type NodeJSReadableStreamEsque = {
49
+ on(eventName: string | symbol, listener: (...args: any[]) => void): NodeJSReadableStreamEsque;
50
+ };
51
+ export declare class NodeOnDiskFile {
52
+ private filepath;
53
+ type: string;
54
+ private slicer?;
55
+ name: string;
56
+ lastModified: number;
57
+ webkitRelativePath: string;
58
+ constructor(filepath: string, type: string, slicer?: {
59
+ start: number;
60
+ end: number;
61
+ } | undefined);
62
+ get size(): number;
63
+ slice(start?: number, end?: number, type?: string): NodeOnDiskFile;
64
+ arrayBuffer(): Promise<ArrayBuffer>;
65
+ stream(): ReadableStream<any>;
66
+ stream(): NodeJSReadableStreamEsque;
67
+ text(): Promise<string>;
68
+ readonly [Symbol.toStringTag] = "File";
69
+ remove(): Promise<void>;
70
+ getFilePath(): string;
71
+ }
72
+ export {};
73
+ //# sourceMappingURL=fileUploadHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fileUploadHandler.d.ts","sourceRoot":"","sources":["../../../../../src/adapters/node-http/content-type/form-data/fileUploadHandler.ts"],"names":[],"mappings":";AAoBA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGrD,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,EAClC,QAAQ,CAAC,EAAE,cAAc,mBAoB1B;AAED,MAAM,MAAM,2BAA2B,GAAG;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,iCAAiC,GAAG;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,6BAA6B,GAAG,CAC1C,IAAI,EAAE,iCAAiC,KACpC,MAAM,GAAG,SAAS,CAAC;AAExB,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B;;OAEG;IACH,SAAS,CAAC,EAAE,6BAA6B,GAAG,MAAM,CAAC;IACnD;;;OAGG;IACH,IAAI,CAAC,EAAE,6BAA6B,CAAC;IACrC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,MAAM,CAAC,CAAC,IAAI,EAAE,2BAA2B,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;CACxE,CAAC;AA4BF,wBAAgB,uBAAuB,CAAC,EACtC,SAAoB,EACpB,kBAAyB,EACzB,IAA8B,EAC9B,MAAM,EACN,WAAqB,GACtB,GAAE,wBAA6B,GAAG,aAAa,CAyD/C;AACD,KAAK,yBAAyB,GAAG;IAC/B,EAAE,CACA,SAAS,EAAE,MAAM,GAAG,MAAM,EAC1B,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,GACjC,yBAAyB,CAAC;CAC9B,CAAC;AAEF,qBAAa,cAAc;IAMvB,OAAO,CAAC,QAAQ;IACT,IAAI,EAAE,MAAM;IACnB,OAAO,CAAC,MAAM,CAAC;IAPjB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,SAAK;IACjB,kBAAkB,SAAM;gBAGd,QAAQ,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACX,MAAM,CAAC;eAAW,MAAM;aAAO,MAAM;iBAAE;IAKjD,IAAI,IAAI,IAAI,MAAM,CASjB;IAED,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,cAAc;IAkB5D,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC;IAkBzC,MAAM,IAAI,cAAc,CAAC,GAAG,CAAC;IAC7B,MAAM,IAAI,yBAAyB;IAU7B,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC;IAI7B,SAAgB,CAAC,MAAM,CAAC,WAAW,CAAC,UAAU;IAE9C,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAGvB,WAAW,IAAI,MAAM;CAGtB"}
@@ -0,0 +1,161 @@
1
+ 'use strict';
2
+
3
+ var node_crypto = require('node:crypto');
4
+ var node_fs = require('node:fs');
5
+ var fs = require('node:fs/promises');
6
+ var node_os = require('node:os');
7
+ var node_path = require('node:path');
8
+ var node_stream = require('node:stream');
9
+ var node_util = require('node:util');
10
+ var streamSlice = require('./streamSlice.js');
11
+ var uploadHandler = require('./uploadHandler.js');
12
+
13
+ async function readableStreamToString(stream, encoding) {
14
+ const reader = stream.getReader();
15
+ const chunks = [];
16
+ async function read() {
17
+ const { done , value } = await reader.read();
18
+ if (done) {
19
+ return;
20
+ } else if (value) {
21
+ chunks.push(value);
22
+ }
23
+ await read();
24
+ }
25
+ await read();
26
+ return Buffer.concat(chunks).toString(encoding);
27
+ }
28
+ const defaultFilePathResolver = ({ filename , })=>{
29
+ const ext = filename ? node_path.extname(filename) : '';
30
+ return 'upload_' + node_crypto.randomBytes(4).readUInt32LE(0) + ext;
31
+ };
32
+ async function uniqueFile(filepath) {
33
+ const ext = node_path.extname(filepath);
34
+ let uniqueFilepath = filepath;
35
+ for(let i = 1; await fs.stat(uniqueFilepath).then(()=>true).catch(()=>false); i++){
36
+ uniqueFilepath = (ext ? filepath.slice(0, -ext.length) : filepath) + `-${new Date().getTime()}${ext}`;
37
+ }
38
+ return uniqueFilepath;
39
+ }
40
+ function createFileUploadHandler({ directory =node_os.tmpdir() , avoidFileConflicts =true , file =defaultFilePathResolver , filter , maxPartSize =3000000 } = {}) {
41
+ return async ({ name , filename , contentType , data })=>{
42
+ if (!filename || filter && !await filter({
43
+ name,
44
+ filename,
45
+ contentType
46
+ })) {
47
+ return undefined;
48
+ }
49
+ const dir = typeof directory === 'string' ? directory : directory({
50
+ name,
51
+ filename,
52
+ contentType
53
+ });
54
+ if (!dir) {
55
+ return undefined;
56
+ }
57
+ const filedir = node_path.resolve(dir);
58
+ const path = typeof file === 'string' ? file : file({
59
+ name,
60
+ filename,
61
+ contentType
62
+ });
63
+ if (!path) {
64
+ return undefined;
65
+ }
66
+ let filepath = node_path.resolve(filedir, path);
67
+ if (avoidFileConflicts) {
68
+ filepath = await uniqueFile(filepath);
69
+ }
70
+ await fs.mkdir(node_path.dirname(filepath), {
71
+ recursive: true
72
+ }).catch(()=>{});
73
+ const writeFileStream = node_fs.createWriteStream(filepath);
74
+ let size = 0;
75
+ let deleteFile = false;
76
+ try {
77
+ for await (const chunk of data){
78
+ size += chunk.byteLength;
79
+ if (size > maxPartSize) {
80
+ deleteFile = true;
81
+ throw new uploadHandler.MaxPartSizeExceededError(name, maxPartSize);
82
+ }
83
+ writeFileStream.write(chunk);
84
+ }
85
+ } finally{
86
+ writeFileStream.end();
87
+ await node_util.promisify(node_stream.finished)(writeFileStream);
88
+ if (deleteFile) {
89
+ await fs.rm(filepath).catch(()=>{});
90
+ }
91
+ }
92
+ return new NodeOnDiskFile(filepath, contentType);
93
+ };
94
+ }
95
+ let _toStringTag = Symbol.toStringTag;
96
+ class NodeOnDiskFile {
97
+ get size() {
98
+ const stats = node_fs.statSync(this.filepath);
99
+ if (this.slicer) {
100
+ const slice = this.slicer.end - this.slicer.start;
101
+ return slice < 0 ? 0 : slice > stats.size ? stats.size : slice;
102
+ }
103
+ return stats.size;
104
+ }
105
+ slice(start, end, type) {
106
+ if (typeof start === 'number' && start < 0) start = this.size + start;
107
+ if (typeof end === 'number' && end < 0) end = this.size + end;
108
+ const startOffset = this.slicer?.start ?? 0;
109
+ start = startOffset + (start ?? 0);
110
+ end = startOffset + (end ?? this.size);
111
+ return new NodeOnDiskFile(this.filepath, typeof type === 'string' ? type : this.type, {
112
+ start,
113
+ end
114
+ });
115
+ }
116
+ async arrayBuffer() {
117
+ let stream = node_fs.createReadStream(this.filepath);
118
+ if (this.slicer) {
119
+ stream = stream.pipe(streamSlice.streamSlice(this.slicer.start, this.slicer.end));
120
+ }
121
+ return new Promise((resolve, reject)=>{
122
+ const buf = [];
123
+ stream.on('data', (chunk)=>buf.push(chunk));
124
+ stream.on('end', ()=>{
125
+ resolve(Buffer.concat(buf));
126
+ });
127
+ stream.on('error', (err)=>{
128
+ reject(err);
129
+ });
130
+ });
131
+ }
132
+ stream() {
133
+ let stream = node_fs.createReadStream(this.filepath);
134
+ if (this.slicer) {
135
+ stream = stream.pipe(streamSlice.streamSlice(this.slicer.start, this.slicer.end));
136
+ }
137
+ return node_stream.Readable.toWeb(stream);
138
+ }
139
+ async text() {
140
+ return readableStreamToString(this.stream());
141
+ }
142
+ remove() {
143
+ return fs.unlink(this.filepath);
144
+ }
145
+ getFilePath() {
146
+ return this.filepath;
147
+ }
148
+ constructor(filepath, type, slicer){
149
+ this.filepath = filepath;
150
+ this.type = type;
151
+ this.slicer = slicer;
152
+ this.lastModified = 0;
153
+ this.webkitRelativePath = '';
154
+ this[_toStringTag] = 'File';
155
+ this.name = node_path.basename(filepath);
156
+ }
157
+ }
158
+
159
+ exports.NodeOnDiskFile = NodeOnDiskFile;
160
+ exports.createFileUploadHandler = createFileUploadHandler;
161
+ exports.readableStreamToString = readableStreamToString;
@@ -0,0 +1,157 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { createWriteStream, statSync, createReadStream } from 'node:fs';
3
+ import { mkdir, rm, unlink, stat } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { resolve, dirname, basename, extname } from 'node:path';
6
+ import { finished, Readable } from 'node:stream';
7
+ import { promisify } from 'node:util';
8
+ import { streamSlice } from './streamSlice.mjs';
9
+ import { MaxPartSizeExceededError } from './uploadHandler.mjs';
10
+
11
+ async function readableStreamToString(stream, encoding) {
12
+ const reader = stream.getReader();
13
+ const chunks = [];
14
+ async function read() {
15
+ const { done , value } = await reader.read();
16
+ if (done) {
17
+ return;
18
+ } else if (value) {
19
+ chunks.push(value);
20
+ }
21
+ await read();
22
+ }
23
+ await read();
24
+ return Buffer.concat(chunks).toString(encoding);
25
+ }
26
+ const defaultFilePathResolver = ({ filename , })=>{
27
+ const ext = filename ? extname(filename) : '';
28
+ return 'upload_' + randomBytes(4).readUInt32LE(0) + ext;
29
+ };
30
+ async function uniqueFile(filepath) {
31
+ const ext = extname(filepath);
32
+ let uniqueFilepath = filepath;
33
+ for(let i = 1; await stat(uniqueFilepath).then(()=>true).catch(()=>false); i++){
34
+ uniqueFilepath = (ext ? filepath.slice(0, -ext.length) : filepath) + `-${new Date().getTime()}${ext}`;
35
+ }
36
+ return uniqueFilepath;
37
+ }
38
+ function createFileUploadHandler({ directory =tmpdir() , avoidFileConflicts =true , file =defaultFilePathResolver , filter , maxPartSize =3000000 } = {}) {
39
+ return async ({ name , filename , contentType , data })=>{
40
+ if (!filename || filter && !await filter({
41
+ name,
42
+ filename,
43
+ contentType
44
+ })) {
45
+ return undefined;
46
+ }
47
+ const dir = typeof directory === 'string' ? directory : directory({
48
+ name,
49
+ filename,
50
+ contentType
51
+ });
52
+ if (!dir) {
53
+ return undefined;
54
+ }
55
+ const filedir = resolve(dir);
56
+ const path = typeof file === 'string' ? file : file({
57
+ name,
58
+ filename,
59
+ contentType
60
+ });
61
+ if (!path) {
62
+ return undefined;
63
+ }
64
+ let filepath = resolve(filedir, path);
65
+ if (avoidFileConflicts) {
66
+ filepath = await uniqueFile(filepath);
67
+ }
68
+ await mkdir(dirname(filepath), {
69
+ recursive: true
70
+ }).catch(()=>{});
71
+ const writeFileStream = createWriteStream(filepath);
72
+ let size = 0;
73
+ let deleteFile = false;
74
+ try {
75
+ for await (const chunk of data){
76
+ size += chunk.byteLength;
77
+ if (size > maxPartSize) {
78
+ deleteFile = true;
79
+ throw new MaxPartSizeExceededError(name, maxPartSize);
80
+ }
81
+ writeFileStream.write(chunk);
82
+ }
83
+ } finally{
84
+ writeFileStream.end();
85
+ await promisify(finished)(writeFileStream);
86
+ if (deleteFile) {
87
+ await rm(filepath).catch(()=>{});
88
+ }
89
+ }
90
+ return new NodeOnDiskFile(filepath, contentType);
91
+ };
92
+ }
93
+ let _toStringTag = Symbol.toStringTag;
94
+ class NodeOnDiskFile {
95
+ get size() {
96
+ const stats = statSync(this.filepath);
97
+ if (this.slicer) {
98
+ const slice = this.slicer.end - this.slicer.start;
99
+ return slice < 0 ? 0 : slice > stats.size ? stats.size : slice;
100
+ }
101
+ return stats.size;
102
+ }
103
+ slice(start, end, type) {
104
+ if (typeof start === 'number' && start < 0) start = this.size + start;
105
+ if (typeof end === 'number' && end < 0) end = this.size + end;
106
+ const startOffset = this.slicer?.start ?? 0;
107
+ start = startOffset + (start ?? 0);
108
+ end = startOffset + (end ?? this.size);
109
+ return new NodeOnDiskFile(this.filepath, typeof type === 'string' ? type : this.type, {
110
+ start,
111
+ end
112
+ });
113
+ }
114
+ async arrayBuffer() {
115
+ let stream = createReadStream(this.filepath);
116
+ if (this.slicer) {
117
+ stream = stream.pipe(streamSlice(this.slicer.start, this.slicer.end));
118
+ }
119
+ return new Promise((resolve, reject)=>{
120
+ const buf = [];
121
+ stream.on('data', (chunk)=>buf.push(chunk));
122
+ stream.on('end', ()=>{
123
+ resolve(Buffer.concat(buf));
124
+ });
125
+ stream.on('error', (err)=>{
126
+ reject(err);
127
+ });
128
+ });
129
+ }
130
+ stream() {
131
+ let stream = createReadStream(this.filepath);
132
+ if (this.slicer) {
133
+ stream = stream.pipe(streamSlice(this.slicer.start, this.slicer.end));
134
+ }
135
+ return Readable.toWeb(stream);
136
+ }
137
+ async text() {
138
+ return readableStreamToString(this.stream());
139
+ }
140
+ remove() {
141
+ return unlink(this.filepath);
142
+ }
143
+ getFilePath() {
144
+ return this.filepath;
145
+ }
146
+ constructor(filepath, type, slicer){
147
+ this.filepath = filepath;
148
+ this.type = type;
149
+ this.slicer = slicer;
150
+ this.lastModified = 0;
151
+ this.webkitRelativePath = '';
152
+ this[_toStringTag] = 'File';
153
+ this.name = basename(filepath);
154
+ }
155
+ }
156
+
157
+ export { NodeOnDiskFile, createFileUploadHandler, readableStreamToString };
@@ -1,5 +1,26 @@
1
- import type { AnyRouter } from '../../../../@trpc/server';
2
- import type { NodeHTTPRequest, NodeHTTPResponse } from '../../types';
3
- import type { NodeHTTPContentTypeHandler } from '../types';
4
- export declare const getFormDataContentTypeHandler: <TRouter extends AnyRouter, TRequest extends NodeHTTPRequest, TResponse extends NodeHTTPResponse>() => NodeHTTPContentTypeHandler<TRouter, TRequest, TResponse>;
1
+ /**
2
+ * Copyright 2021 Remix Software Inc.
3
+ * 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:
4
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ * 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.
6
+ */
7
+ import type { NodeHTTPRequest } from '../../types';
8
+ import type { UploadHandler } from './uploadHandler';
9
+ /**
10
+ * Allows you to handle multipart forms (file uploads) for your app.
11
+ * Request body parts with a 'filename' property will be treated as files.
12
+ * The rest will be treated as text.
13
+ * @param request The incoming Node HTTP request
14
+ * @param uploadHandler A function that handles file uploads and returns a value to be used in the request body. If uploaded to disk, the returned value is a NodeOnDiskFile. If uploaded to memory, the returned value is a File.
15
+ * @param maxBodySize The maximum size of the request body in bytes. Defaults to Infinity.
16
+ *
17
+ * @link https://remix.run/utils/parse-multipart-form-data
18
+ */
19
+ declare function parseMultipartFormData(request: NodeHTTPRequest, uploadHandler: UploadHandler, maxBodySize?: number): Promise<FormData>;
20
+ declare function isMultipartFormDataRequest(req: NodeHTTPRequest): boolean;
21
+ export declare const nodeHTTPFormDataContentTypeHandler: <TRequest extends NodeHTTPRequest, TResponse extends import("../../types").NodeHTTPResponse>() => import("../../internals/contentType").NodeHTTPContentTypeHandler<TRequest, TResponse>;
22
+ export { NodeOnDiskFile as experimental_NodeOnDiskFile, createFileUploadHandler as experimental_createFileUploadHandler, } from './fileUploadHandler';
23
+ export { createMemoryUploadHandler as experimental_createMemoryUploadHandler } from './memoryUploadHandler';
24
+ export { MaxBodySizeExceededError, MaxPartSizeExceededError, composeUploadHandlers as experimental_composeUploadHandlers, type UploadHandler, } from './uploadHandler';
25
+ export { isMultipartFormDataRequest as experimental_isMultipartFormDataRequest, parseMultipartFormData as experimental_parseMultipartFormData, };
5
26
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/adapters/node-http/content-type/form-data/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,UAAU,CAAC;AAE3D,eAAO,MAAM,6BAA6B,EAAE,CAC1C,OAAO,SAAS,SAAS,EACzB,QAAQ,SAAS,eAAe,EAChC,SAAS,SAAS,gBAAgB,OAC7B,0BAA0B,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CA0B5D,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/adapters/node-http/content-type/form-data/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAYH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,KAAK,EAAE,aAAa,EAAqB,MAAM,iBAAiB,CAAC;AAKxE;;;;;;;;;GASG;AACH,iBAAe,sBAAsB,CACnC,OAAO,EAAE,eAAe,EACxB,aAAa,EAAE,aAAa,EAC5B,WAAW,SAAW,qBAoEvB;AAED,iBAAS,0BAA0B,CAAC,GAAG,EAAE,eAAe,WAMvD;AAED,eAAO,MAAM,kCAAkC,yLA+B3C,CAAC;AAEL,OAAO,EACL,cAAc,IAAI,2BAA2B,EAC7C,uBAAuB,IAAI,oCAAoC,GAChE,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,IAAI,sCAAsC,EAAE,MAAM,uBAAuB,CAAC;AAC5G,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,qBAAqB,IAAI,kCAAkC,EAC3D,KAAK,aAAa,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,0BAA0B,IAAI,uCAAuC,EACrE,sBAAsB,IAAI,mCAAmC,GAC9D,CAAC"}
@@ -1,32 +1,135 @@
1
1
  'use strict';
2
2
 
3
+ var fs = require('node:fs/promises');
3
4
  var node_stream = require('node:stream');
5
+ var multipartParser = require('@web3-storage/multipart-parser');
6
+ var contentType = require('../../internals/contentType.js');
7
+ var fileUploadHandler = require('./fileUploadHandler.js');
8
+ var uploadHandler = require('./uploadHandler.js');
9
+ var memoryUploadHandler = require('./memoryUploadHandler.js');
4
10
 
5
- const getFormDataContentTypeHandler = ()=>({
6
- name: 'node-http-formdata',
7
- isMatch: (headers)=>{
8
- return !!headers.get('content-type')?.startsWith('multipart/form-data');
9
- },
10
- async getInputs (opts, inputOpts) {
11
- if (inputOpts.isBatchCall) {
12
- throw new Error('Batch calls not supported for form-data');
13
- }
14
- const contentType = opts.req.headers['content-type'];
15
- if (!contentType) {
16
- // Should be unreachable given the isMatch check
17
- throw new Error('No content-type header found');
11
+ function _interopNamespaceDefault(e) {
12
+ var n = Object.create(null);
13
+ if (e) {
14
+ Object.keys(e).forEach(function (k) {
15
+ if (k !== 'default') {
16
+ var d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: function () { return e[k]; }
20
+ });
21
+ }
22
+ });
23
+ }
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
29
+
30
+ const utfTextDecoder = new TextDecoder('utf-8');
31
+ /**
32
+ * Allows you to handle multipart forms (file uploads) for your app.
33
+ * Request body parts with a 'filename' property will be treated as files.
34
+ * The rest will be treated as text.
35
+ * @param request The incoming Node HTTP request
36
+ * @param uploadHandler A function that handles file uploads and returns a value to be used in the request body. If uploaded to disk, the returned value is a NodeOnDiskFile. If uploaded to memory, the returned value is a File.
37
+ * @param maxBodySize The maximum size of the request body in bytes. Defaults to Infinity.
38
+ *
39
+ * @link https://remix.run/utils/parse-multipart-form-data
40
+ */ async function parseMultipartFormData(request, uploadHandler$1, maxBodySize = Infinity) {
41
+ const contentType = request.headers['content-type'] ?? '';
42
+ const [type, boundary] = contentType.split(/\s*;\s*boundary=/);
43
+ if (!boundary || type !== 'multipart/form-data') {
44
+ throw new TypeError('Could not parse content as FormData.');
45
+ }
46
+ const formData = new FormData();
47
+ const parts = multipartParser.streamMultipart(node_stream.Readable.toWeb(request), boundary);
48
+ let currentBodySize = 0;
49
+ const nodeOnDiskFiles = [];
50
+ try {
51
+ for await (const part of parts){
52
+ if (part.done) break;
53
+ if (typeof part.filename === 'string') {
54
+ // This is a file, so the uploadHandler function will be called
55
+ // only pass basename as the multipart/form-data spec recommends
56
+ // https://datatracker.ietf.org/doc/html/rfc7578#section-4.2
57
+ part.filename = part.filename.split(/[/\\]/).pop();
58
+ const value = await uploadHandler$1(part);
59
+ if (typeof value === 'undefined' || value === null) {
60
+ continue;
61
+ }
62
+ // add to cleanup array in case of error
63
+ if (value instanceof fileUploadHandler.NodeOnDiskFile) {
64
+ nodeOnDiskFiles.push(value);
65
+ }
66
+ // if the combined size of the body exceeds the max size, throw an error
67
+ currentBodySize += value.size;
68
+ if (currentBodySize > maxBodySize) {
69
+ throw new uploadHandler.MaxBodySizeExceededError(maxBodySize);
70
+ }
71
+ // add the file to the form data
72
+ formData.append(part.name, value);
73
+ } else {
74
+ // This is text, so we'll decode it and add it to the form data
75
+ let textualPart = '';
76
+ for await (const chunk of part.data){
77
+ // if the combined size of the body exceeds the max size, throw an error
78
+ currentBodySize += chunk.length;
79
+ if (currentBodySize > maxBodySize) {
80
+ throw new uploadHandler.MaxBodySizeExceededError(maxBodySize);
81
+ }
82
+ textualPart += utfTextDecoder.decode(chunk);
83
+ }
84
+ // add the text to the form data
85
+ formData.append(part.name, textualPart);
18
86
  }
19
- const form = await new Request('https://unused.com', {
20
- method: 'POST',
21
- headers: {
22
- 'content-type': contentType
23
- },
24
- body: node_stream.Readable.toWeb(opts.req),
25
- // @ts-expect-error - outdated types? this exists
26
- duplex: 'half'
27
- }).formData();
28
- return form;
29
87
  }
30
- });
88
+ return formData;
89
+ } catch (e) {
90
+ // clean up any files that were uploaded to disk if an error occurs
91
+ await Promise.all(nodeOnDiskFiles.map((file)=>fs__namespace.unlink(file.getFilePath())));
92
+ throw e;
93
+ }
94
+ }
95
+ function isMultipartFormDataRequest(req) {
96
+ const contentTypeHeader = req.headers['content-type'];
97
+ return contentTypeHeader?.startsWith('multipart/form-data') ?? contentTypeHeader === 'application/x-www-form-urlencoded';
98
+ }
99
+ const nodeHTTPFormDataContentTypeHandler = contentType.createNodeHTTPContentTypeHandler({
100
+ isMatch (opts) {
101
+ return isMultipartFormDataRequest(opts.req);
102
+ },
103
+ async getBody (opts) {
104
+ const fields = Object.fromEntries(opts.query);
105
+ return {
106
+ ok: true,
107
+ data: fields,
108
+ preprocessed: false
109
+ };
110
+ },
111
+ getInputs (opts) {
112
+ const req = opts.req;
113
+ const unparsedInput = req.query.get('input');
114
+ if (!unparsedInput) {
115
+ return {
116
+ 0: undefined
117
+ };
118
+ }
119
+ const transformer = opts.router._def._config.transformer;
120
+ const deserializedInput = transformer.input.deserialize(JSON.parse(unparsedInput));
121
+ return {
122
+ 0: deserializedInput
123
+ };
124
+ }
125
+ });
31
126
 
32
- exports.getFormDataContentTypeHandler = getFormDataContentTypeHandler;
127
+ exports.experimental_NodeOnDiskFile = fileUploadHandler.NodeOnDiskFile;
128
+ exports.experimental_createFileUploadHandler = fileUploadHandler.createFileUploadHandler;
129
+ exports.MaxBodySizeExceededError = uploadHandler.MaxBodySizeExceededError;
130
+ exports.MaxPartSizeExceededError = uploadHandler.MaxPartSizeExceededError;
131
+ exports.experimental_composeUploadHandlers = uploadHandler.composeUploadHandlers;
132
+ exports.experimental_createMemoryUploadHandler = memoryUploadHandler.createMemoryUploadHandler;
133
+ exports.experimental_isMultipartFormDataRequest = isMultipartFormDataRequest;
134
+ exports.experimental_parseMultipartFormData = parseMultipartFormData;
135
+ exports.nodeHTTPFormDataContentTypeHandler = nodeHTTPFormDataContentTypeHandler;