@univerjs-pro/collaboration-file-endpoint 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -2
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@univerjs-pro/collaboration-file-service"),t=require("node:stream"),n=require("node:stream/promises"),r=require("content-disposition"),i=require("@univerjs-pro/collaboration-transport-node"),a=require("@univerjs/protocol"),o=require("node:zlib"),s=require("@fastify/busboy");function c(e,t){return{"content-type":e.contentType,"content-length":String(e.size),"content-disposition":(0,r.create)(e.name),"x-content-type-options":`nosniff`,"cache-control":`private, max-age=${t}, immutable`,etag:`"${e.fileID}"`}}async function l(e,r,i,a){e.statusCode=200;for(let[t,n]of Object.entries(c(r,a)))e.setHeader(t,n);await(0,n.pipeline)(t.Readable.from(i),e)}var u={code:a.ErrorCode.OK,message:``};function d(t){if(t instanceof i.NodeTransportError){let e=t.code===`REQUEST_BODY_TOO_LARGE`?413:t.code===`INVALID_JSON`||t.code===`REQUEST_ABORTED`||t.code===`INVALID_URL`?400:503;return{status:e,error:{code:e===503?a.ErrorCode.INTERNAL_ERROR:a.ErrorCode.INVALID_ARGUMENT,message:t.message}}}if(!(t instanceof e.FileError))return{status:500,error:{code:a.ErrorCode.INTERNAL_ERROR,message:`Internal error`}};let[n,r]=(()=>{switch(t.code){case`INVALID_REQUEST`:return[400,a.ErrorCode.INVALID_ARGUMENT];case`UNAUTHENTICATED`:return[401,a.ErrorCode.UNAUTHENTICATED];case`PERMISSION_DENIED`:return[403,a.ErrorCode.PERMISSION_DENIED];case`FILE_NOT_FOUND`:return[404,a.ErrorCode.NOT_FOUND];case`UPLOAD_TIMEOUT`:return[408,a.ErrorCode.INTERNAL_ERROR];case`PAYLOAD_TOO_LARGE`:return[413,a.ErrorCode.INVALID_ARGUMENT];case`STORAGE_FAILURE`:case`SERVICE_DISPOSED`:return[503,a.ErrorCode.INTERNAL_ERROR];default:return[500,a.ErrorCode.INTERNAL_ERROR]}})();return{status:n,error:{code:r,message:t.message}}}function f(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`content-type`,`application/json; charset=utf-8`),e.end(JSON.stringify(n)))}function p(e,t,n={}){let r=d(t);f(e,r.status,{error:r.error,...n})}function m(e,t){if(e.writableEnded)return;if(e.headersSent){e.destroy();return}let n=d(t);e.statusCode=n.status,e.setHeader(`content-type`,`text/plain; charset=utf-8`),e.end(n.error.message)}function h(e){let t=e.searchParams.get(`size`),n=t===null?void 0:Number(t),r=e.searchParams.getAll(`source`),i=r.length===1&&r[0]!==``?Number(r[0]):NaN,a=Number.isInteger(i)&&i>=-2147483648&&i<=2147483647?i:0;return{...n!==void 0&&Number.isFinite(n)?{size:n}:{},source:a,assign:e.searchParams.get(`assign`)??``,flate:e.searchParams.get(`flate`)===`true`}}function g(n,r,i){return new Promise((a,c)=>{let l=n.headers[`content-type`]??``;if(!/^multipart\/form-data\b/i.test(l)){c(new e.FileError(`INVALID_REQUEST`,`Upload must be multipart/form-data`));return}let u;try{u=new s.Busboy({headers:n.headers,isPartAFile:(e,t,n)=>e===`file`||n!==void 0})}catch(t){c(new e.FileError(`INVALID_REQUEST`,`Malformed multipart request`,{cause:t}));return}let d=!1,f=!1,p,m=setTimeout(()=>g(new e.FileError(`UPLOAD_TIMEOUT`,`Upload timed out`)),i.timeoutMs);m.unref?.();let h=()=>{clearTimeout(m),n.off(`close`,_)},g=e=>{f||(f=!0,h(),n.unpipe(u),p&&p.destroy(e),d||c(e))},_=()=>{n.complete||g(new e.FileError(`INVALID_REQUEST`,`Client disconnected during upload`))};n.on(`close`,_),u.on(`file`,(s,c,l,m,_)=>{if(s!==`file`||d||f){c.resume();return}let v=0,y=new t.Transform({transform(t,n,r){
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@univerjs-pro/collaboration-file-service"),t=require("node:stream"),n=require("node:stream/promises"),r=require("content-disposition"),i=require("@univerjs-pro/collaboration-transport-node"),a=require("@univerjs/protocol"),o=require("node:zlib"),s=require("@fastify/busboy");function c(e,t){return{"content-type":e.contentType,"content-length":String(e.size),"content-disposition":(0,r.create)(e.name),"x-content-type-options":`nosniff`,"cache-control":`private, max-age=${t}, immutable`,etag:`"${e.fileID}"`}}async function l(e,r,i,a){e.statusCode=200;for(let[t,n]of Object.entries(c(r,a)))e.setHeader(t,n);await(0,n.pipeline)(t.Readable.from(i),e)}var u={code:a.ErrorCode.OK,message:``};function d(t){if(t instanceof i.NodeTransportError){let e=t.code===`REQUEST_BODY_TOO_LARGE`?413:t.code===`INVALID_JSON`||t.code===`REQUEST_ABORTED`||t.code===`INVALID_URL`?400:503;return{status:e,error:{code:e===503?a.ErrorCode.INTERNAL_ERROR:a.ErrorCode.INVALID_ARGUMENT,message:t.message}}}if(!(t instanceof e.FileError))return{status:500,error:{code:a.ErrorCode.INTERNAL_ERROR,message:`Internal error`}};let[n,r]=(()=>{switch(t.code){case`INVALID_REQUEST`:return[400,a.ErrorCode.INVALID_ARGUMENT];case`UNAUTHENTICATED`:return[401,a.ErrorCode.UNAUTHENTICATED];case`PERMISSION_DENIED`:return[403,a.ErrorCode.PERMISSION_DENIED];case`FILE_NOT_FOUND`:return[404,a.ErrorCode.NOT_FOUND];case`UPLOAD_TIMEOUT`:return[408,a.ErrorCode.INTERNAL_ERROR];case`PAYLOAD_TOO_LARGE`:return[413,a.ErrorCode.INVALID_ARGUMENT];case`STORAGE_FAILURE`:case`SERVICE_DISPOSED`:return[503,a.ErrorCode.INTERNAL_ERROR];default:return[500,a.ErrorCode.INTERNAL_ERROR]}})();return{status:n,error:{code:r,message:t.message}}}function f(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`content-type`,`application/json; charset=utf-8`),e.end(JSON.stringify(n)))}function p(e,t,n={}){let r=d(t);f(e,r.status,{error:r.error,...n})}function m(e,t){if(e.writableEnded)return;if(e.headersSent){e.destroy();return}let n=d(t);e.statusCode=n.status,e.setHeader(`content-type`,`text/plain; charset=utf-8`),e.end(n.error.message)}function h(e){let t=e.searchParams.get(`size`),n=t===null?void 0:Number(t),r=e.searchParams.getAll(`source`),i=r.length===1&&r[0]!==``?Number(r[0]):NaN,a=Number.isInteger(i)&&i>=-2147483648&&i<=2147483647?i:0;return{...n!==void 0&&Number.isFinite(n)?{size:n}:{},source:a,assign:e.searchParams.get(`assign`)??``,flate:e.searchParams.get(`flate`)===`true`}}function g(n,r,i){return new Promise((a,c)=>{let l=n.headers[`content-type`]??``;if(!/^multipart\/form-data\b/i.test(l)){c(new e.FileError(`INVALID_REQUEST`,`Upload must be multipart/form-data`));return}let u;try{u=new s.Busboy({headers:n.headers,isPartAFile:(e,t,n)=>e===`file`||n!==void 0})}catch(t){c(new e.FileError(`INVALID_REQUEST`,`Malformed multipart request`,{cause:t}));return}let d=!1,f=!1,p,m=setTimeout(()=>g(new e.FileError(`UPLOAD_TIMEOUT`,`Upload timed out`)),i.timeoutMs);m.unref?.();let h=()=>{clearTimeout(m),n.off(`close`,_)},g=e=>{f||(f=!0,h(),n.unpipe(u),p&&p.destroy(e),d||c(e))},_=()=>{n.complete||g(new e.FileError(`INVALID_REQUEST`,`Client disconnected during upload`))};n.on(`close`,_),u.on(`file`,(s,c,l,m,_)=>{if(s!==`file`||d||f){c.resume();return}let v=0,y=new t.Transform({transform(t,n,r){v+=t.byteLength,i.maxBytes!==void 0&&v>i.maxBytes?r(new e.FileError(`PAYLOAD_TOO_LARGE`,`Upload exceeds ${i.maxBytes} bytes`)):r(null,t)}});p=y;let b=r.flate?[c,(0,o.createInflateRaw)(),y]:[c,y],x=t=>t instanceof e.FileError?t:new e.FileError(`INVALID_REQUEST`,r.flate?`Upload is not valid raw DEFLATE data`:`Upload stream failed`,{cause:t});(0,t.pipeline)(b,e=>{e?g(x(e)):(f=!0,h())});let S=(async function*(){try{yield*y}catch(e){throw x(e)}})();d=!0,a({name:l??``,contentType:_||`application/octet-stream`,content:S,release:()=>{f||(f=!0,h(),n.unpipe(u),y.destroy())}})}),u.on(`error`,t=>g(new e.FileError(`INVALID_REQUEST`,`Malformed multipart request`,{cause:t}))),u.on(`finish`,()=>{d||g(new e.FileError(`INVALID_REQUEST`,`Multipart request has no file part`))}),n.pipe(u)})}var _=6e5,v=3600,y=class{_service;_routePrefix;_maxUploadBytes;_uploadTimeoutMs;_downloadCacheMaxAgeSeconds;_calls=new Set;_disposed=!1;_disposePromise;constructor(e,t={}){if(!e)throw TypeError(`UniverFileEndpoint requires a service`);this._service=e,this._routePrefix=C(t.routePrefix??`/universer-api`),this._maxUploadBytes=w(t.maxUploadBytes,`maxUploadBytes`),this._uploadTimeoutMs=w(t.uploadTimeoutMs,`uploadTimeoutMs`)??_,this._downloadCacheMaxAgeSeconds=T(t.downloadCacheMaxAgeSeconds,`downloadCacheMaxAgeSeconds`,v)}register(t){if(this._disposed)throw new e.FileError(`SERVICE_DISPOSED`,`File Endpoint is disposed`);t.post(`${this._routePrefix}/stream/file/upload`,e=>this._track(this._handleUpload(e))),t.get(`${this._routePrefix}/file/:fileID/sign-url`,e=>this._track(this._handleSignUrl(e))),t.get(`${this._routePrefix}/file/:fileID/download`,e=>this._track(this._handleDownload(e)))}dispose(){return this._disposePromise||=(this._disposed=!0,Promise.allSettled([...this._calls]).then(()=>void 0)),this._disposePromise}async _handleUpload(e){let t;try{let n=this._requireUser(e),r=h(S(e));t=await g(e.incomingMessage,r,{maxBytes:this._maxUploadBytes,timeoutMs:this._uploadTimeoutMs});let i=await this._service.upload({name:t.name,contentType:t.contentType,...r.size===void 0?{}:{size:r.size},source:r.source,assign:r.assign,flate:r.flate,content:t.content},{userID:n,customData:e.customData});f(e.response,200,{error:u,FileId:i.fileID})}catch(n){t?.release(),b(e),p(e.response,n,{FileId:``})}finally{t?.release()}}async _handleSignUrl(e){try{let t=this._requireUser(e),n=x(e),r=(await this._service.signUrl({fileID:n},{userID:t,customData:e.customData})).direct?.url??`${this._routePrefix}/file/${encodeURIComponent(n)}/download`;f(e.response,200,{error:u,url:r})}catch(t){p(e.response,t,{url:``})}}async _handleDownload(e){try{let t=this._requireUser(e),n=x(e),{record:r,content:i}=await this._service.openDownload({fileID:n},{userID:t,customData:e.customData});await l(e.response,r,i,this._downloadCacheMaxAgeSeconds)}catch(t){m(e.response,t)}}_requireUser(t){if(this._disposed)throw new e.FileError(`SERVICE_DISPOSED`,`File Endpoint is disposed`);if(!t.userID)throw new e.FileError(`UNAUTHENTICATED`,`HTTP user is not authenticated`);return t.userID}_track(e){return this._calls.add(e),e.finally(()=>this._calls.delete(e)).catch(()=>void 0),e}};function b(e){e.incomingMessage.complete||e.response.headersSent||(e.response.setHeader(`connection`,`close`),e.response.once(`finish`,()=>e.incomingMessage.destroy()))}function x(t){let n=t.params.fileID;if(!n||n.includes(`/`))throw new e.FileError(`INVALID_REQUEST`,`Invalid route fileID`);return n}function S(e){return new URL(e.incomingMessage.url??`/`,`http://localhost`)}function C(e){if(!e.startsWith(`/`)||e===`/`||e.endsWith(`/`)||e.includes(`//`))throw TypeError(`routePrefix must be an absolute path without a trailing slash`);return e}function w(e,t){if(e!==void 0){if(!Number.isFinite(e)||e<=0)throw TypeError(`${t} must be a positive number`);return e}}function T(e,t,n){if(e===void 0)return n;if(!Number.isSafeInteger(e)||e<0)throw TypeError(`${t} must be a non-negative integer`);return e}exports.UniverFileEndpoint=y;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { IUniverFileService } from "@univerjs-pro/collaboration-file-service";
|
|
2
2
|
import { NodeRouter, NodeTransportEndpoint } from "@univerjs-pro/collaboration-transport-node";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// src/endpoint.d.ts
|
|
5
5
|
/** @public */
|
|
6
6
|
interface UniverFileEndpointOptions {
|
|
7
7
|
/** Defaults to `/universer-api`; absolute, no trailing slash. */
|
|
@@ -38,5 +38,4 @@ declare class UniverFileEndpoint implements NodeTransportEndpoint {
|
|
|
38
38
|
private _requireUser;
|
|
39
39
|
private _track;
|
|
40
40
|
}
|
|
41
|
-
//#endregion
|
|
42
41
|
export { UniverFileEndpoint, type UniverFileEndpointOptions };
|
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"engines": {
|
|
12
12
|
"node": ">=22"
|
|
13
13
|
},
|
|
14
|
-
"version": "1.
|
|
14
|
+
"version": "1.6.0",
|
|
15
15
|
"main": "./dist/index.cjs",
|
|
16
16
|
"module": "./dist/index.mjs",
|
|
17
17
|
"types": "./dist/index.d.ts",
|
|
@@ -30,8 +30,8 @@
|
|
|
30
30
|
"content-disposition": "^3.0.0"
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|
|
33
|
-
"@univerjs-pro/collaboration-file-service": "1.
|
|
34
|
-
"@univerjs-pro/collaboration-transport-node": "1.
|
|
35
|
-
"@univerjs/protocol": "1.
|
|
33
|
+
"@univerjs-pro/collaboration-file-service": "1.6.0",
|
|
34
|
+
"@univerjs-pro/collaboration-transport-node": "1.6.0",
|
|
35
|
+
"@univerjs/protocol": "1.6.0"
|
|
36
36
|
}
|
|
37
37
|
}
|