@trpc/server
Advanced tools
Comparing version 1.4.0-alpha.1 to 1.4.0
@@ -47,10 +47,3 @@ /// <reference types="node" /> | ||
subscriptions?: { | ||
/** | ||
* Time in milliseconds before `408` is sent | ||
*/ | ||
requestTimeoutMs?: number; | ||
/** | ||
* Allow for some backpressure and batch send events every X ms | ||
*/ | ||
backpressureMs?: number; | ||
timeout?: number; | ||
}; | ||
@@ -64,8 +57,8 @@ teardown?: () => Promise<void>; | ||
} | ||
export declare function requestHandler<TContext, TRouter extends Router<TContext, any, any, any>, TCreateContextFn extends CreateContextFn<TContext, TRequest, TResponse>, TRequest extends BaseRequest, TResponse extends BaseResponse>({ req, res, router, path, subscriptions, createContext, teardown, transformer, maxBodySize, }: { | ||
export declare function requestHandler<TContext, TRouter extends Router<TContext, any, any, any>, TCreateContextFn extends CreateContextFn<TContext, TRequest, TResponse>, TRequest extends BaseRequest, TResponse extends BaseResponse>({ req, res, router, endpoint, subscriptions, createContext, teardown, transformer, maxBodySize, }: { | ||
req: TRequest; | ||
res: TResponse; | ||
path: string; | ||
endpoint: string; | ||
router: TRouter; | ||
createContext: TCreateContextFn; | ||
} & BaseOptions): Promise<void>; |
@@ -28,3 +28,3 @@ import { Subscription } from './subscription'; | ||
export declare type inferRouteOutput<TRoute extends Route> = inferAsyncReturnType<TRoute['resolve']>; | ||
export declare type inferSubscriptionOutput<TRouter extends AnyRouter, TPath extends keyof TRouter['_def']['subscriptions']> = TRouter[TPath] extends Subscription<infer TData> ? TData : never; | ||
export declare type inferSubscriptionOutput<TRouter extends AnyRouter, TPath extends keyof TRouter['_def']['subscriptions']> = inferAsyncReturnType<inferAsyncReturnType<TRouter['_def']['subscriptions'][TPath]['resolve']>['onceOutputAndStop']>; | ||
export declare type inferHandlerFn<TRoutes extends RouteRecord<any, any, any>> = <TPath extends keyof TRoutes & string, TRoute extends TRoutes[TPath]>(path: TPath, ...args: TRoute extends RouteWithInput<any, any, any> ? [inferRouteInput<TRoute>] : [undefined?]) => Promise<inferRouteOutput<TRoutes[TPath]>>; | ||
@@ -31,0 +31,0 @@ export declare type AnyRouter<TContext = any> = Router<TContext, any, any, any>; |
@@ -7,4 +7,4 @@ 'use strict'; | ||
var events = require('events'); | ||
var url = _interopDefault(require('url')); | ||
var events = require('events'); | ||
var http = _interopDefault(require('http')); | ||
@@ -926,2 +926,269 @@ | ||
var SubscriptionDestroyError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(SubscriptionDestroyError, _Error); | ||
function SubscriptionDestroyError(reason) { | ||
var _this; | ||
_this = _Error.call(this, reason) || this; | ||
_this.reason = reason; | ||
Object.setPrototypeOf(_assertThisInitialized(_this), SubscriptionDestroyError.prototype); | ||
return _this; | ||
} | ||
return SubscriptionDestroyError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
var SubscriptionEventEmitter = /*#__PURE__*/function (_EventEmitter) { | ||
_inheritsLoose(SubscriptionEventEmitter, _EventEmitter); | ||
function SubscriptionEventEmitter() { | ||
return _EventEmitter.apply(this, arguments) || this; | ||
} | ||
return SubscriptionEventEmitter; | ||
}(events.EventEmitter); | ||
var Subscription = /*#__PURE__*/function () { | ||
function Subscription(opts) { | ||
this.isDestroyed = false; | ||
this.events = new SubscriptionEventEmitter(); | ||
this.opts = _extends({ | ||
getInitialOutput: function getInitialOutput() {// no-op | ||
} | ||
}, opts); | ||
} | ||
var _proto = Subscription.prototype; | ||
_proto.destroy = function destroy(reason) { | ||
if (this.isDestroyed) { | ||
return; | ||
} // debug('Subscription.destroy()', reason); | ||
this.isDestroyed = true; | ||
this.events.emit('destroy', reason); | ||
this.events.removeAllListeners(); | ||
}; | ||
_proto.start = /*#__PURE__*/function () { | ||
var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() { | ||
var _this2 = this; | ||
var emit, cancel; | ||
return runtime_1.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
if (!this.isDestroyed) { | ||
_context.next = 2; | ||
break; | ||
} | ||
throw new Error('Called start() on a destroyed subscription'); | ||
case 2: | ||
_context.prev = 2; | ||
emit = { | ||
error: function error(err) { | ||
return _this2.emitError(err); | ||
}, | ||
data: function data(_data) { | ||
return _this2.emitOutput(_data); | ||
} | ||
}; | ||
_context.next = 6; | ||
return this.opts.getInitialOutput(emit); | ||
case 6: | ||
cancel = this.opts.start(emit); | ||
this.events.on('destroy', function () { | ||
cancel(); | ||
}); | ||
_context.next = 13; | ||
break; | ||
case 10: | ||
_context.prev = 10; | ||
_context.t0 = _context["catch"](2); | ||
this.emitError(_context.t0); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this, [[2, 10]]); | ||
})); | ||
function start() { | ||
return _start.apply(this, arguments); | ||
} | ||
return start; | ||
}(); | ||
_proto.onceOutputAndStop = /*#__PURE__*/function () { | ||
var _onceOutputAndStop = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3() { | ||
var _this3 = this; | ||
return runtime_1.wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
return _context3.abrupt("return", new Promise( /*#__PURE__*/function () { | ||
var _ref = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(resolve, reject) { | ||
var onDestroy, onOutput, onError, cleanup; | ||
return runtime_1.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
onDestroy = function onDestroy(reason) { | ||
reject(new SubscriptionDestroyError(reason)); | ||
cleanup(); | ||
}; | ||
onOutput = function onOutput(data) { | ||
resolve(data); | ||
cleanup(); | ||
_this3.destroy('stopped'); | ||
}; | ||
onError = function onError(err) { | ||
reject(err); | ||
cleanup(); | ||
_this3.destroy('stopped'); | ||
}; | ||
cleanup = function cleanup() { | ||
_this3.events.off('data', onOutput); | ||
_this3.events.off('destroy', onDestroy); | ||
_this3.events.off('error', onError); | ||
}; | ||
_this3.events.once('data', onOutput); | ||
_this3.events.once('destroy', onDestroy); | ||
_this3.events.once('error', onError); | ||
_this3.start()["catch"](function () {// is handled through event | ||
}); | ||
case 8: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2); | ||
})); | ||
return function (_x, _x2) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}())); | ||
case 1: | ||
case "end": | ||
return _context3.stop(); | ||
} | ||
} | ||
}, _callee3); | ||
})); | ||
function onceOutputAndStop() { | ||
return _onceOutputAndStop.apply(this, arguments); | ||
} | ||
return onceOutputAndStop; | ||
}() | ||
/** | ||
* Emit data | ||
*/ | ||
; | ||
_proto.emitOutput = function emitOutput(data) { | ||
this.events.emit('data', data); | ||
} | ||
/** | ||
* Emit error | ||
*/ | ||
; | ||
_proto.emitError = function emitError(err) { | ||
this.events.emit('error', err); | ||
}; | ||
return Subscription; | ||
}(); | ||
function subscriptionPullFatory(opts) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
var timer; | ||
var stopped = false; | ||
function _pull(_x3) { | ||
return _pull2.apply(this, arguments); | ||
} | ||
function _pull2() { | ||
_pull2 = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee4(emit) { | ||
return runtime_1.wrap(function _callee4$(_context4) { | ||
while (1) { | ||
switch (_context4.prev = _context4.next) { | ||
case 0: | ||
if (!stopped) { | ||
_context4.next = 2; | ||
break; | ||
} | ||
return _context4.abrupt("return"); | ||
case 2: | ||
_context4.prev = 2; | ||
_context4.next = 5; | ||
return opts.pull(emit); | ||
case 5: | ||
_context4.next = 10; | ||
break; | ||
case 7: | ||
_context4.prev = 7; | ||
_context4.t0 = _context4["catch"](2); | ||
emit.error(_context4.t0); | ||
case 10: | ||
if (!stopped) { | ||
timer = setTimeout(function () { | ||
return _pull(emit); | ||
}, opts.interval); | ||
} | ||
case 11: | ||
case "end": | ||
return _context4.stop(); | ||
} | ||
} | ||
}, _callee4, null, [[2, 7]]); | ||
})); | ||
return _pull2.apply(this, arguments); | ||
} | ||
return new Subscription({ | ||
start: function start(emit) { | ||
_pull(emit); | ||
return function () { | ||
clearTimeout(timer); | ||
stopped = true; | ||
}; | ||
} | ||
}); | ||
} | ||
assertNotBrowser(); | ||
@@ -1058,3 +1325,3 @@ var HTTPError = /*#__PURE__*/function (_Error) { | ||
_requestHandler = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(_ref2) { | ||
var req, res, router, path, subscriptions, createContext, teardown, _ref2$transformer, transformer, maxBodySize, _req$method, _res$statusCode, output, ctx, method, deserializeInput, body, input, query, _input, _body, _input2, sub, json, _json; | ||
var req, res, router, endpoint, subscriptions, createContext, teardown, _ref2$transformer, transformer, maxBodySize, _req$method, _res$statusCode, output, ctx, method, deserializeInput, body, input, query, _input, _subscriptions$timeou, _body, _input2, sub, onClose, timeout, timer, json, _json; | ||
@@ -1065,3 +1332,3 @@ return runtime_1.wrap(function _callee2$(_context2) { | ||
case 0: | ||
req = _ref2.req, res = _ref2.res, router = _ref2.router, path = _ref2.path, subscriptions = _ref2.subscriptions, createContext = _ref2.createContext, teardown = _ref2.teardown, _ref2$transformer = _ref2.transformer, transformer = _ref2$transformer === void 0 ? { | ||
req = _ref2.req, res = _ref2.res, router = _ref2.router, endpoint = _ref2.endpoint, subscriptions = _ref2.subscriptions, createContext = _ref2.createContext, teardown = _ref2.teardown, _ref2$transformer = _ref2.transformer, transformer = _ref2$transformer === void 0 ? { | ||
serialize: function serialize(data) { | ||
@@ -1118,3 +1385,3 @@ return data; | ||
ctx: ctx, | ||
path: path | ||
path: endpoint | ||
}); | ||
@@ -1124,3 +1391,3 @@ | ||
output = _context2.sent; | ||
_context2.next = 42; | ||
_context2.next = 57; | ||
break; | ||
@@ -1142,3 +1409,3 @@ | ||
ctx: ctx, | ||
path: path | ||
path: endpoint | ||
}); | ||
@@ -1148,3 +1415,3 @@ | ||
output = _context2.sent; | ||
_context2.next = 42; | ||
_context2.next = 57; | ||
break; | ||
@@ -1154,3 +1421,3 @@ | ||
if (!(method === 'PATCH')) { | ||
_context2.next = 41; | ||
_context2.next = 56; | ||
break; | ||
@@ -1173,3 +1440,3 @@ } | ||
ctx: ctx, | ||
path: path | ||
path: endpoint | ||
}); | ||
@@ -1179,84 +1446,54 @@ | ||
sub = _context2.sent; | ||
_context2.next = 38; | ||
return new Promise(function (resolve, reject) { | ||
var _subscriptions$reques, _subscriptions$backpr; | ||
var startTime = Date.now(); | ||
var buffer = []; | ||
var requestTimeoutMs = (_subscriptions$reques = subscriptions == null ? void 0 : subscriptions.requestTimeoutMs) != null ? _subscriptions$reques : 9000; // 10s is vercel's api timeout | ||
onClose = function onClose() { | ||
sub.destroy('closed'); | ||
}; // FIXME - refactor | ||
// this is a bit complex | ||
// needs to handle a few cases: | ||
// - ok subscription | ||
// - error subscription | ||
// - request got prematurely closed | ||
// - request timed out | ||
var backpressureMs = (_subscriptions$backpr = subscriptions == null ? void 0 : subscriptions.backpressureMs) != null ? _subscriptions$backpr : 0; // timers | ||
var backpressureTimer = null; | ||
var requestTimeoutTimer = null; | ||
res.once('close', onClose); | ||
timeout = (_subscriptions$timeou = subscriptions == null ? void 0 : subscriptions.timeout) != null ? _subscriptions$timeou : 9000; // 10s is vercel's api timeout | ||
function cleanup() { | ||
sub.off('data', onData); | ||
sub.off('error', onError); | ||
sub.off('destroy', onDestroy); | ||
req.off('close', onClose); | ||
clearTimeout(requestTimeoutTimer); | ||
clearTimeout(backpressureTimer); | ||
sub.destroy(); | ||
} | ||
timer = setTimeout(function () { | ||
sub.destroy('timeout'); | ||
}, timeout); | ||
_context2.prev = 40; | ||
_context2.next = 43; | ||
return sub.onceOutputAndStop(); | ||
function onData(data) { | ||
buffer.push(data); | ||
var requestTimeLeft = requestTimeoutMs - (Date.now() - startTime); | ||
case 43: | ||
output = _context2.sent; | ||
res.off('close', onClose); | ||
_context2.next = 54; | ||
break; | ||
var success = function success() { | ||
cleanup(); | ||
resolve(buffer); | ||
}; | ||
case 47: | ||
_context2.prev = 47; | ||
_context2.t1 = _context2["catch"](40); | ||
res.off('close', onClose); | ||
clearTimeout(timer); | ||
if (requestTimeLeft >= backpressureMs) { | ||
// will timeout before next backpressure tick | ||
success(); | ||
return; | ||
} | ||
if (!(_context2.t1 instanceof SubscriptionDestroyError && _context2.t1.reason === 'timeout')) { | ||
_context2.next = 53; | ||
break; | ||
} | ||
if (!backpressureTimer) { | ||
backpressureTimer = setTimeout(success, backpressureMs); | ||
return; | ||
} | ||
} | ||
throw new HTTPError(408, "Subscription exceeded " + timeout + "ms - please reconnect."); | ||
function onError(err) { | ||
cleanup(); // maybe if `buffer` has length here we should just return instead? | ||
case 53: | ||
throw _context2.t1; | ||
reject(err); | ||
} | ||
function onClose() { | ||
cleanup(); | ||
reject(new HTTPError(499, "Client Closed Request")); | ||
} | ||
function onRequestTimeout() { | ||
cleanup(); | ||
reject(new HTTPError(408, "Subscription exceeded " + requestTimeoutMs + "ms - please reconnect.")); | ||
} | ||
function onDestroy() { | ||
reject(new HTTPError(500, "Subscription was destroyed prematurely")); | ||
cleanup(); | ||
} | ||
sub.on('data', onData); | ||
sub.on('error', onError); | ||
sub.on('destroy', onDestroy); | ||
req.once('close', onClose); | ||
requestTimeoutTimer = setTimeout(onRequestTimeout, requestTimeoutMs); | ||
sub.start(); | ||
}); | ||
case 38: | ||
output = _context2.sent; | ||
_context2.next = 42; | ||
case 54: | ||
_context2.next = 57; | ||
break; | ||
case 41: | ||
case 56: | ||
throw httpError.badRequest("Unexpected request method " + method); | ||
case 42: | ||
case 57: | ||
json = { | ||
@@ -1270,9 +1507,9 @@ ok: true, | ||
res.end(JSON.stringify(transformer.serialize(json))); | ||
_context2.next = 54; | ||
_context2.next = 69; | ||
break; | ||
case 48: | ||
_context2.prev = 48; | ||
_context2.t1 = _context2["catch"](1); | ||
_json = getErrorResponseEnvelope(_context2.t1); | ||
case 63: | ||
_context2.prev = 63; | ||
_context2.t2 = _context2["catch"](1); | ||
_json = getErrorResponseEnvelope(_context2.t2); | ||
res.statusCode = _json.statusCode; | ||
@@ -1282,24 +1519,24 @@ res.setHeader('Content-Type', 'application/json'); | ||
case 54: | ||
_context2.prev = 54; | ||
_context2.t2 = teardown; | ||
case 69: | ||
_context2.prev = 69; | ||
_context2.t3 = teardown; | ||
if (!_context2.t2) { | ||
_context2.next = 59; | ||
if (!_context2.t3) { | ||
_context2.next = 74; | ||
break; | ||
} | ||
_context2.next = 59; | ||
_context2.next = 74; | ||
return teardown(); | ||
case 59: | ||
_context2.next = 64; | ||
case 74: | ||
_context2.next = 79; | ||
break; | ||
case 61: | ||
_context2.prev = 61; | ||
_context2.t3 = _context2["catch"](54); | ||
console.error('Teardown failed', _context2.t3); | ||
case 76: | ||
_context2.prev = 76; | ||
_context2.t4 = _context2["catch"](69); | ||
console.error('Teardown failed', _context2.t4); | ||
case 64: | ||
case 79: | ||
case "end": | ||
@@ -1309,3 +1546,3 @@ return _context2.stop(); | ||
} | ||
}, _callee2, null, [[1, 48], [54, 61]]); | ||
}, _callee2, null, [[1, 63], [40, 47], [69, 76]]); | ||
})); | ||
@@ -1494,211 +1731,2 @@ return _requestHandler.apply(this, arguments); | ||
var SubscriptionEventEmitter = /*#__PURE__*/function (_EventEmitter) { | ||
_inheritsLoose(SubscriptionEventEmitter, _EventEmitter); | ||
function SubscriptionEventEmitter() { | ||
return _EventEmitter.apply(this, arguments) || this; | ||
} | ||
return SubscriptionEventEmitter; | ||
}(events.EventEmitter); | ||
var Subscription = /*#__PURE__*/function () { | ||
function Subscription(opts) { | ||
this.isDestroyed = false; | ||
this.events = new SubscriptionEventEmitter(); | ||
this.opts = _extends({}, opts); | ||
} | ||
var _proto = Subscription.prototype; | ||
_proto.destroy = function destroy() { | ||
if (this.isDestroyed) { | ||
return; | ||
} // debug('Subscription.destroy()', reason); | ||
this.isDestroyed = true; | ||
this.events.emit('destroy'); | ||
this.events.removeAllListeners(); | ||
}; | ||
_proto.start = /*#__PURE__*/function () { | ||
var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() { | ||
var _this = this; | ||
var emit, cancel; | ||
return runtime_1.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
if (!this.isDestroyed) { | ||
_context.next = 2; | ||
break; | ||
} | ||
throw new Error('Called start() on a destroyed subscription'); | ||
case 2: | ||
_context.prev = 2; | ||
emit = { | ||
error: function error(err) { | ||
return _this.emitError(err); | ||
}, | ||
data: function data(_data) { | ||
return _this.emitOutput(_data); | ||
} | ||
}; | ||
_context.next = 6; | ||
return this.opts.start(emit); | ||
case 6: | ||
cancel = _context.sent; | ||
if (this.isDestroyed) { | ||
cancel(); | ||
} else { | ||
this.events.on('destroy', cancel); | ||
} | ||
_context.next = 13; | ||
break; | ||
case 10: | ||
_context.prev = 10; | ||
_context.t0 = _context["catch"](2); | ||
this.emitError(_context.t0); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this, [[2, 10]]); | ||
})); | ||
function start() { | ||
return _start.apply(this, arguments); | ||
} | ||
return start; | ||
}(); | ||
_proto.onceOutputAndStop = /*#__PURE__*/function () { | ||
var _onceOutputAndStop = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2() { | ||
return runtime_1.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
throw new Error('Legacy'); | ||
case 1: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2); | ||
})); | ||
function onceOutputAndStop() { | ||
return _onceOutputAndStop.apply(this, arguments); | ||
} | ||
return onceOutputAndStop; | ||
}() | ||
/** | ||
* Emit data | ||
*/ | ||
; | ||
_proto.emitOutput = function emitOutput(data) { | ||
this.events.emit('data', data); | ||
} | ||
/** | ||
* Emit error | ||
*/ | ||
; | ||
_proto.emitError = function emitError(err) { | ||
this.events.emit('error', err); | ||
}; | ||
_proto.on = function on() { | ||
var _this$events; | ||
return (_this$events = this.events).on.apply(_this$events, arguments); | ||
}; | ||
_proto.off = function off() { | ||
var _this$events2; | ||
return (_this$events2 = this.events).off.apply(_this$events2, arguments); | ||
}; | ||
return Subscription; | ||
}(); | ||
function subscriptionPullFactory(opts) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
var timer; | ||
var stopped = false; | ||
function _pull(_x) { | ||
return _pull2.apply(this, arguments); | ||
} | ||
function _pull2() { | ||
_pull2 = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3(emit) { | ||
return runtime_1.wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
if (!stopped) { | ||
_context3.next = 2; | ||
break; | ||
} | ||
return _context3.abrupt("return"); | ||
case 2: | ||
_context3.prev = 2; | ||
_context3.next = 5; | ||
return opts.pull(emit); | ||
case 5: | ||
_context3.next = 10; | ||
break; | ||
case 7: | ||
_context3.prev = 7; | ||
_context3.t0 = _context3["catch"](2); | ||
emit.error(_context3.t0); | ||
case 10: | ||
if (!stopped) { | ||
timer = setTimeout(function () { | ||
return _pull(emit); | ||
}, opts.intervalMs); | ||
} | ||
case 11: | ||
case "end": | ||
return _context3.stop(); | ||
} | ||
} | ||
}, _callee3, null, [[2, 7]]); | ||
})); | ||
return _pull2.apply(this, arguments); | ||
} | ||
return new Subscription({ | ||
start: function start(emit) { | ||
_pull(emit); | ||
return function () { | ||
clearTimeout(timer); | ||
stopped = true; | ||
}; | ||
} | ||
}); | ||
} | ||
function createExpressMiddleware(opts) { | ||
@@ -1710,3 +1738,3 @@ return function (req, res) { | ||
res: res, | ||
path: endpoint | ||
endpoint: endpoint | ||
})); | ||
@@ -1740,3 +1768,3 @@ }; | ||
res: res, | ||
path: endpoint | ||
endpoint: endpoint | ||
})); | ||
@@ -1771,3 +1799,3 @@ | ||
res: res, | ||
path: endpoint | ||
endpoint: endpoint | ||
})); | ||
@@ -1808,2 +1836,3 @@ | ||
exports.Subscription = Subscription; | ||
exports.SubscriptionDestroyError = SubscriptionDestroyError; | ||
exports.assertNotBrowser = assertNotBrowser; | ||
@@ -1819,3 +1848,3 @@ exports.createExpressMiddleware = createExpressMiddleware; | ||
exports.router = router; | ||
exports.subscriptionPullFactory = subscriptionPullFactory; | ||
exports.subscriptionPullFatory = subscriptionPullFatory; | ||
//# sourceMappingURL=server.cjs.development.js.map |
@@ -1,2 +0,2 @@ | ||
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("url")),r=require("events"),n=t(require("http"));function o(){if("undefined"!=typeof window&&void 0===process.env.JEST_WORKER_ID)throw new Error("Imported server-only code in the broowser")}function i(t,e,r,n,o,i,u){try{var a=t[i](u),s=a.value}catch(t){return void r(t)}a.done?e(s):Promise.resolve(s).then(n,o)}function u(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var u=t.apply(e,r);function a(t){i(u,n,o,a,s,"next",t)}function s(t){i(u,n,o,a,s,"throw",t)}a(void 0)}))}}function a(){return(a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function s(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}function c(t){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function f(t,e){return(f=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function p(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}function l(t,e,r){return(l=p()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&f(o,r.prototype),o}).apply(null,arguments)}function h(t){var e="function"==typeof Map?new Map:void 0;return(h=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return l(t,arguments,c(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),f(r,t)})(t)}function d(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function v(t,e){return t(e={exports:{}},e.exports),e.exports}var y=v((function(t){var e=function(t){var e=Object.prototype,r=e.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",i=n.asyncIterator||"@@asyncIterator",u=n.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var o=Object.create((e&&e.prototype instanceof p?e:p).prototype),i=new O(n||[]);return o._invoke=function(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var u=r.delegate;if(u){var a=g(u,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var s=c(t,e,r);if("normal"===s.type){if(n=r.done?"completed":"suspendedYield",s.arg===f)continue;return{value:s.arg,done:r.done}}"throw"===s.type&&(n="completed",r.method="throw",r.arg=s.arg)}}}(t,r,i),o}function c(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var f={};function p(){}function l(){}function h(){}var d={};d[o]=function(){return this};var v=Object.getPrototypeOf,y=v&&v(v(k([])));y&&y!==e&&r.call(y,o)&&(d=y);var m=h.prototype=p.prototype=Object.create(d);function w(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){var n;this._invoke=function(o,i){function u(){return new e((function(n,u){!function n(o,i,u,a){var s=c(t[o],t,i);if("throw"!==s.type){var f=s.arg,p=f.value;return p&&"object"==typeof p&&r.call(p,"__await")?e.resolve(p.__await).then((function(t){n("next",t,u,a)}),(function(t){n("throw",t,u,a)})):e.resolve(p).then((function(t){f.value=t,u(f)}),(function(t){return n("throw",t,u,a)}))}a(s.arg)}(o,i,n,u)}))}return n=n?n.then(u,u):u()}}function g(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,g(t,e),"throw"===e.method))return f;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return f}var n=c(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,f;var o=n.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,f):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,f)}function b(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function E(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(b,this),this.reset(!0)}function k(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,i=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return i.next=i}}return{next:_}}function _(){return{value:void 0,done:!0}}return l.prototype=m.constructor=h,h.constructor=l,l.displayName=a(h,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===l||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,h):(t.__proto__=h,a(t,u,"GeneratorFunction")),t.prototype=Object.create(m),t},t.awrap=function(t){return{__await:t}},w(x.prototype),x.prototype[i]=function(){return this},t.AsyncIterator=x,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var u=new x(s(e,r,n,o),i);return t.isGeneratorFunction(r)?u:u.next().then((function(t){return t.done?t.value:u.next()}))},w(m),a(m,u,"Generator"),m[o]=function(){return this},m.toString=function(){return"[object Generator]"},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=k,O.prototype={constructor:O,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return u.type="throw",u.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],u=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),s=r.call(i,"finallyLoc");if(a&&s){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var u=i?i.completion:{};return u.type=t,u.arg=e,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(u)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),f},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),E(r),f}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;E(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:k(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},t}(t.exports);try{regeneratorRuntime=e}catch(t){Function("r","regeneratorRuntime = r")(e)}})),m=function(t){function e(r){var n;return(n=t.call(this,r.message)||this).originalError=r,Object.setPrototypeOf(d(n),e.prototype),n}return s(e,t),e}(h(Error)),w=function(t){function e(r){var n;return n=t.call(this,r)||this,Object.setPrototypeOf(d(n),e.prototype),n}return s(e,t),e}(h(Error));o();var x=function(t){function e(r,n){var o;return(o=t.call(this,n)||this).statusCode=r,Object.setPrototypeOf(d(o),e.prototype),o}return s(e,t),e}(h(Error)),g={forbidden:function(t){return new x(403,null!=t?t:"Forbidden")},unauthorized:function(t){return new x(401,null!=t?t:"Unauthorized")},badRequest:function(t){return new x(400,null!=t?t:"Bad Request")},notFound:function(t){return new x(404,null!=t?t:"Not found")},payloadTooLarge:function(t){return new x(413,null!=t?t:"Payload Too Large")}};function b(t){var e,r,n=t;return n instanceof m?n=g.badRequest(n.message):n instanceof w&&(n=g.notFound(n.message)),{ok:!1,statusCode:"number"==typeof(null==(e=n)?void 0:e.statusCode)?n.statusCode:500,error:{message:"string"==typeof(null==(r=n)?void 0:r.message)?n.message:"Internal Server Error",stack:void 0}}}function E(t){var e=void 0,r=t.input;if(!r)return e;if("string"!=typeof r)throw g.badRequest("Expected query.input to be a JSON string");try{e=JSON.parse(r)}catch(t){throw g.badRequest("Expected query.input to be a JSON string")}return e}function O(t){return k.apply(this,arguments)}function k(){return(k=u(y.mark((function t(e){var r,n;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.req,n=e.maxBodySize,t.abrupt("return",new Promise((function(t,e){if(r.body)t(r.body);else{var o="";r.on("data",(function(t){o+=t,"number"==typeof n&&o.length>n&&(e(g.payloadTooLarge()),r.connection.destroy())})),r.on("end",(function(){try{var r=JSON.parse(o);t(r)}catch(t){e(g.badRequest("Body couldn't be parsed as json"))}}))}})));case 2:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function _(t){return q.apply(this,arguments)}function q(){return(q=u(y.mark((function t(r){var n,o,i,u,a,s,c,f,p,l,h,d,v,m,w,k,_,q,j,L,S,T,P;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=r.req,o=r.res,i=r.router,u=r.path,a=r.subscriptions,s=r.createContext,c=r.teardown,p=void 0===(f=r.transformer)?{serialize:function(t){return t},deserialize:function(t){return t}}:f,l=r.maxBodySize,t.prev=1,t.t0=s,!t.t0){t.next=7;break}return t.next=6,s({req:n,res:o});case 6:t.t0=t.sent;case 7:if(m=t.t0,w=null!=(h=n.method)?h:"GET",k=function(t){return t?p.deserialize(t):t},"POST"!==w){t.next=20;break}return t.next=13,O({req:n,maxBodySize:l});case 13:return _=k(t.sent.input),t.next=17,i.invoke({target:"mutations",input:_,ctx:m,path:u});case 17:v=t.sent,t.next=42;break;case 20:if("GET"!==w){t.next=28;break}return q=n.query?n.query:e.parse(n.url,!0).query,j=k(E(q)),t.next=25,i.invoke({target:"queries",input:j,ctx:m,path:u});case 25:v=t.sent,t.next=42;break;case 28:if("PATCH"!==w){t.next=41;break}return t.next=31,O({req:n,maxBodySize:l});case 31:return L=k(t.sent.input),t.next=35,i.invoke({target:"subscriptions",input:L,ctx:m,path:u});case 35:return S=t.sent,t.next=38,new Promise((function(t,e){var r,o,i=Date.now(),u=[],s=null!=(r=null==a?void 0:a.requestTimeoutMs)?r:9e3,c=null!=(o=null==a?void 0:a.backpressureMs)?o:0,f=null,p=null;function l(){S.off("data",h),S.off("error",d),S.off("destroy",y),n.off("close",v),clearTimeout(p),clearTimeout(f),S.destroy()}function h(e){u.push(e);var r=function(){l(),t(u)};s-(Date.now()-i)>=c?r():f||(f=setTimeout(r,c))}function d(t){l(),e(t)}function v(){l(),e(new x(499,"Client Closed Request"))}function y(){e(new x(500,"Subscription was destroyed prematurely")),l()}S.on("data",h),S.on("error",d),S.on("destroy",y),n.once("close",v),p=setTimeout((function(){l(),e(new x(408,"Subscription exceeded "+s+"ms - please reconnect."))}),s),S.start()}));case 38:v=t.sent,t.next=42;break;case 41:throw g.badRequest("Unexpected request method "+w);case 42:T={ok:!0,statusCode:null!=(d=o.statusCode)?d:200,data:v},o.statusCode=T.statusCode,o.setHeader("Content-Type","application/json"),o.end(JSON.stringify(p.serialize(T))),t.next=54;break;case 48:t.prev=48,t.t1=t.catch(1),P=b(t.t1),o.statusCode=P.statusCode,o.setHeader("Content-Type","application/json"),o.end(JSON.stringify(p.serialize(P)));case 54:if(t.prev=54,t.t2=c,!t.t2){t.next=59;break}return t.next=59,c();case 59:t.next=64;break;case 61:t.prev=61,t.t3=t.catch(54),console.error("Teardown failed",t.t3);case 64:case"end":return t.stop()}}),t,null,[[1,48],[54,61]])})))).apply(this,arguments)}o();var j=function(){function t(t){this._def=null!=t?t:{queries:{},mutations:{},subscriptions:{}}}t.prefixRoutes=function(t,e){var r={};for(var n in t)r[e+n]=t[n];return r};var e=t.prototype;return e.query=function(e,r){var n,o=new t({queries:(n={},n[e]=r,n),mutations:{},subscriptions:{}});return this.merge(o)},e.mutation=function(e,r){var n,o=new t({queries:{},mutations:(n={},n[e]=r,n),subscriptions:{}});return this.merge(o)},e.subscription=function(e,r){var n,o=new t({queries:{},mutations:{},subscriptions:(n={},n[e]=r,n)});return this.merge(o)},e.merge=function(e,r){var n,o=this,i="";if("string"==typeof e&&r instanceof t)i=e,n=r;else{if(!(e instanceof t))throw new Error("Invalid args");n=e}var u=Object.keys(n._def.queries).filter((function(t){return o.has("queries",t)})),s=Object.keys(n._def.mutations).filter((function(t){return o.has("mutations",t)})),c=Object.keys(n._def.subscriptions).filter((function(t){return o.has("subscriptions",t)})),f=[].concat(u,s,c);if(f.length)throw new Error("Duplicate endpoint(s): "+f.join(", "));return new t({queries:a({},this._def.queries,t.prefixRoutes(n._def.queries,i)),mutations:a({},this._def.mutations,t.prefixRoutes(n._def.mutations,i)),subscriptions:a({},this._def.subscriptions,t.prefixRoutes(n._def.subscriptions,i))})},t.getInput=function(t,e){if(t.input)try{var r=t.input;if("function"==typeof r.parse)return r.parse(e);if("function"==typeof r)return r(e);if("function"==typeof r.validateSync)return r.validateSync(e);throw new Error("Could not find a validator fn")}catch(t){throw new m(t)}},e.invoke=function(){var e=u(y.mark((function e(r){var n,o;return y.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.has(r.target,r.path)){e.next=2;break}throw new w('No such route "'+r.path+'"');case 2:return o=t.getInput(n=this._def[r.target][r.path],r.input),e.abrupt("return",n.resolve({ctx:r.ctx,input:o}));case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.has=function(t,e){return!!this._def[t][e]},t}(),L=function(t){function e(){return t.apply(this,arguments)||this}return s(e,t),e}(r.EventEmitter),S=function(){function t(t){this.isDestroyed=!1,this.events=new L,this.opts=a({},t)}var e=t.prototype;return e.destroy=function(){this.isDestroyed||(this.isDestroyed=!0,this.events.emit("destroy"),this.events.removeAllListeners())},e.start=function(){var t=u(y.mark((function t(){var e,r,n=this;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.isDestroyed){t.next=2;break}throw new Error("Called start() on a destroyed subscription");case 2:return t.prev=2,e={error:function(t){return n.emitError(t)},data:function(t){return n.emitOutput(t)}},t.next=6,this.opts.start(e);case 6:r=t.sent,this.isDestroyed?r():this.events.on("destroy",r),t.next=13;break;case 10:t.prev=10,t.t0=t.catch(2),this.emitError(t.t0);case 13:case"end":return t.stop()}}),t,this,[[2,10]])})));return function(){return t.apply(this,arguments)}}(),e.onceOutputAndStop=function(){var t=u(y.mark((function t(){return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw new Error("Legacy");case 1:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),e.emitOutput=function(t){this.events.emit("data",t)},e.emitError=function(t){this.events.emit("error",t)},e.on=function(){var t;return(t=this.events).on.apply(t,arguments)},e.off=function(){var t;return(t=this.events).off.apply(t,arguments)},t}();function T(t){return function(){var r=u(y.mark((function r(n,o){var i;return y.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return i=e.parse(n.url).pathname.substr(1),r.next=3,_(a({},t,{req:n,res:o,path:i}));case 3:case"end":return r.stop()}}),r)})));return function(t,e){return r.apply(this,arguments)}}()}exports.HTTPError=x,exports.Router=j,exports.Subscription=S,exports.assertNotBrowser=o,exports.createExpressMiddleware=function(t){return function(e,r){var n=e.path.substr(1);_(a({},t,{req:e,res:r,path:n}))}},exports.createHttpHandler=T,exports.createHttpServer=function(t){var e=T(t),r=n.createServer((function(t,r){return e(t,r)}));return{server:r,listen:function(t){return r.listen(t),{port:0===t?r.address().port:t}}}},exports.createNextApiHandler=function(t){return function(){var e=u(y.mark((function e(r,n){var o,i;return y.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!==(o=Array.isArray(r.query.trpc)?r.query.trpc.join("/"):null)){e.next=5;break}return i=b(new Error('Query "trpc" not found - is the file named [...trpc].ts?')),n.status(i.statusCode).json(i),e.abrupt("return");case 5:return e.next=7,_(a({},t,{req:r,res:n,path:o}));case 7:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}()},exports.getErrorResponseEnvelope=b,exports.getQueryInput=E,exports.httpError=g,exports.requestHandler=_,exports.router=function(){return new j},exports.subscriptionPullFactory=function(t){var e,r=!1;function n(t){return o.apply(this,arguments)}function o(){return(o=u(y.mark((function o(i){return y.wrap((function(o){for(;;)switch(o.prev=o.next){case 0:if(!r){o.next=2;break}return o.abrupt("return");case 2:return o.prev=2,o.next=5,t.pull(i);case 5:o.next=10;break;case 7:o.prev=7,o.t0=o.catch(2),i.error(o.t0);case 10:r||(e=setTimeout((function(){return n(i)}),t.intervalMs));case 11:case"end":return o.stop()}}),o,null,[[2,7]])})))).apply(this,arguments)}return new S({start:function(t){return n(t),function(){clearTimeout(e),r=!0}}})}; | ||
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=require("events"),r=t(require("url")),n=t(require("http"));function o(){if("undefined"!=typeof window&&void 0===process.env.JEST_WORKER_ID)throw new Error("Imported server-only code in the broowser")}function i(t,e,r,n,o,i,u){try{var a=t[i](u),s=a.value}catch(t){return void r(t)}a.done?e(s):Promise.resolve(s).then(n,o)}function u(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var u=t.apply(e,r);function a(t){i(u,n,o,a,s,"next",t)}function s(t){i(u,n,o,a,s,"throw",t)}a(void 0)}))}}function a(){return(a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function s(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}function c(t){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function f(t,e){return(f=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function p(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}function l(t,e,r){return(l=p()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&f(o,r.prototype),o}).apply(null,arguments)}function h(t){var e="function"==typeof Map?new Map:void 0;return(h=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return l(t,arguments,c(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),f(r,t)})(t)}function d(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function v(t,e){return t(e={exports:{}},e.exports),e.exports}var y=v((function(t){var e=function(t){var e=Object.prototype,r=e.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",i=n.asyncIterator||"@@asyncIterator",u=n.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var o=Object.create((e&&e.prototype instanceof p?e:p).prototype),i=new O(n||[]);return o._invoke=function(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var u=r.delegate;if(u){var a=g(u,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var s=c(t,e,r);if("normal"===s.type){if(n=r.done?"completed":"suspendedYield",s.arg===f)continue;return{value:s.arg,done:r.done}}"throw"===s.type&&(n="completed",r.method="throw",r.arg=s.arg)}}}(t,r,i),o}function c(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var f={};function p(){}function l(){}function h(){}var d={};d[o]=function(){return this};var v=Object.getPrototypeOf,y=v&&v(v(k([])));y&&y!==e&&r.call(y,o)&&(d=y);var m=h.prototype=p.prototype=Object.create(d);function w(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){var n;this._invoke=function(o,i){function u(){return new e((function(n,u){!function n(o,i,u,a){var s=c(t[o],t,i);if("throw"!==s.type){var f=s.arg,p=f.value;return p&&"object"==typeof p&&r.call(p,"__await")?e.resolve(p.__await).then((function(t){n("next",t,u,a)}),(function(t){n("throw",t,u,a)})):e.resolve(p).then((function(t){f.value=t,u(f)}),(function(t){return n("throw",t,u,a)}))}a(s.arg)}(o,i,n,u)}))}return n=n?n.then(u,u):u()}}function g(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,g(t,e),"throw"===e.method))return f;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return f}var n=c(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,f;var o=n.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,f):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,f)}function b(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function E(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(b,this),this.reset(!0)}function k(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,i=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return i.next=i}}return{next:_}}function _(){return{value:void 0,done:!0}}return l.prototype=m.constructor=h,h.constructor=l,l.displayName=a(h,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===l||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,h):(t.__proto__=h,a(t,u,"GeneratorFunction")),t.prototype=Object.create(m),t},t.awrap=function(t){return{__await:t}},w(x.prototype),x.prototype[i]=function(){return this},t.AsyncIterator=x,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var u=new x(s(e,r,n,o),i);return t.isGeneratorFunction(r)?u:u.next().then((function(t){return t.done?t.value:u.next()}))},w(m),a(m,u,"Generator"),m[o]=function(){return this},m.toString=function(){return"[object Generator]"},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=k,O.prototype={constructor:O,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return u.type="throw",u.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],u=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),s=r.call(i,"finallyLoc");if(a&&s){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var u=i?i.completion:{};return u.type=t,u.arg=e,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(u)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),f},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),E(r),f}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;E(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:k(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},t}(t.exports);try{regeneratorRuntime=e}catch(t){Function("r","regeneratorRuntime = r")(e)}})),m=function(t){function e(r){var n;return(n=t.call(this,r.message)||this).originalError=r,Object.setPrototypeOf(d(n),e.prototype),n}return s(e,t),e}(h(Error)),w=function(t){function e(r){var n;return n=t.call(this,r)||this,Object.setPrototypeOf(d(n),e.prototype),n}return s(e,t),e}(h(Error)),x=function(t){function e(r){var n;return(n=t.call(this,r)||this).reason=r,Object.setPrototypeOf(d(n),e.prototype),n}return s(e,t),e}(h(Error)),g=function(t){function e(){return t.apply(this,arguments)||this}return s(e,t),e}(e.EventEmitter),b=function(){function t(t){this.isDestroyed=!1,this.events=new g,this.opts=a({getInitialOutput:function(){}},t)}var e=t.prototype;return e.destroy=function(t){this.isDestroyed||(this.isDestroyed=!0,this.events.emit("destroy",t),this.events.removeAllListeners())},e.start=function(){var t=u(y.mark((function t(){var e,r,n=this;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.isDestroyed){t.next=2;break}throw new Error("Called start() on a destroyed subscription");case 2:return t.prev=2,e={error:function(t){return n.emitError(t)},data:function(t){return n.emitOutput(t)}},t.next=6,this.opts.getInitialOutput(e);case 6:r=this.opts.start(e),this.events.on("destroy",(function(){r()})),t.next=13;break;case 10:t.prev=10,t.t0=t.catch(2),this.emitError(t.t0);case 13:case"end":return t.stop()}}),t,this,[[2,10]])})));return function(){return t.apply(this,arguments)}}(),e.onceOutputAndStop=function(){var t=u(y.mark((function t(){var e=this;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",new Promise(function(){var t=u(y.mark((function t(r,n){var o,i,u,a;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:o=function(t){n(new x(t)),a()},i=function(t){r(t),a(),e.destroy("stopped")},u=function(t){n(t),a(),e.destroy("stopped")},a=function(){e.events.off("data",i),e.events.off("destroy",o),e.events.off("error",u)},e.events.once("data",i),e.events.once("destroy",o),e.events.once("error",u),e.start().catch((function(){}));case 8:case"end":return t.stop()}}),t)})));return function(e,r){return t.apply(this,arguments)}}()));case 1:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),e.emitOutput=function(t){this.events.emit("data",t)},e.emitError=function(t){this.events.emit("error",t)},t}();o();var E=function(t){function e(r,n){var o;return(o=t.call(this,n)||this).statusCode=r,Object.setPrototypeOf(d(o),e.prototype),o}return s(e,t),e}(h(Error)),O={forbidden:function(t){return new E(403,null!=t?t:"Forbidden")},unauthorized:function(t){return new E(401,null!=t?t:"Unauthorized")},badRequest:function(t){return new E(400,null!=t?t:"Bad Request")},notFound:function(t){return new E(404,null!=t?t:"Not found")},payloadTooLarge:function(t){return new E(413,null!=t?t:"Payload Too Large")}};function k(t){var e,r,n=t;return n instanceof m?n=O.badRequest(n.message):n instanceof w&&(n=O.notFound(n.message)),{ok:!1,statusCode:"number"==typeof(null==(e=n)?void 0:e.statusCode)?n.statusCode:500,error:{message:"string"==typeof(null==(r=n)?void 0:r.message)?n.message:"Internal Server Error",stack:void 0}}}function _(t){var e=void 0,r=t.input;if(!r)return e;if("string"!=typeof r)throw O.badRequest("Expected query.input to be a JSON string");try{e=JSON.parse(r)}catch(t){throw O.badRequest("Expected query.input to be a JSON string")}return e}function q(t){return j.apply(this,arguments)}function j(){return(j=u(y.mark((function t(e){var r,n;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.req,n=e.maxBodySize,t.abrupt("return",new Promise((function(t,e){if(r.body)t(r.body);else{var o="";r.on("data",(function(t){o+=t,"number"==typeof n&&o.length>n&&(e(O.payloadTooLarge()),r.connection.destroy())})),r.on("end",(function(){try{var r=JSON.parse(o);t(r)}catch(t){e(O.badRequest("Body couldn't be parsed as json"))}}))}})));case 2:case"end":return t.stop()}}),t)})))).apply(this,arguments)}function L(t){return S.apply(this,arguments)}function S(){return(S=u(y.mark((function t(e){var n,o,i,u,a,s,c,f,p,l,h,d,v,m,w,g,b,j,L,S,P,R,T,N,C,F,I;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.req,o=e.res,i=e.router,u=e.endpoint,a=e.subscriptions,s=e.createContext,c=e.teardown,p=void 0===(f=e.transformer)?{serialize:function(t){return t},deserialize:function(t){return t}}:f,l=e.maxBodySize,t.prev=1,t.t0=s,!t.t0){t.next=7;break}return t.next=6,s({req:n,res:o});case 6:t.t0=t.sent;case 7:if(m=t.t0,w=null!=(h=n.method)?h:"GET",g=function(t){return t?p.deserialize(t):t},"POST"!==w){t.next=20;break}return t.next=13,q({req:n,maxBodySize:l});case 13:return b=g(t.sent.input),t.next=17,i.invoke({target:"mutations",input:b,ctx:m,path:u});case 17:v=t.sent,t.next=57;break;case 20:if("GET"!==w){t.next=28;break}return j=n.query?n.query:r.parse(n.url,!0).query,L=g(_(j)),t.next=25,i.invoke({target:"queries",input:L,ctx:m,path:u});case 25:v=t.sent,t.next=57;break;case 28:if("PATCH"!==w){t.next=56;break}return t.next=31,q({req:n,maxBodySize:l});case 31:return P=g(t.sent.input),t.next=35,i.invoke({target:"subscriptions",input:P,ctx:m,path:u});case 35:return R=t.sent,o.once("close",T=function(){R.destroy("closed")}),N=null!=(S=null==a?void 0:a.timeout)?S:9e3,C=setTimeout((function(){R.destroy("timeout")}),N),t.prev=40,t.next=43,R.onceOutputAndStop();case 43:v=t.sent,o.off("close",T),t.next=54;break;case 47:if(t.prev=47,t.t1=t.catch(40),o.off("close",T),clearTimeout(C),!(t.t1 instanceof x&&"timeout"===t.t1.reason)){t.next=53;break}throw new E(408,"Subscription exceeded "+N+"ms - please reconnect.");case 53:throw t.t1;case 54:t.next=57;break;case 56:throw O.badRequest("Unexpected request method "+w);case 57:F={ok:!0,statusCode:null!=(d=o.statusCode)?d:200,data:v},o.statusCode=F.statusCode,o.setHeader("Content-Type","application/json"),o.end(JSON.stringify(p.serialize(F))),t.next=69;break;case 63:t.prev=63,t.t2=t.catch(1),I=k(t.t2),o.statusCode=I.statusCode,o.setHeader("Content-Type","application/json"),o.end(JSON.stringify(p.serialize(I)));case 69:if(t.prev=69,t.t3=c,!t.t3){t.next=74;break}return t.next=74,c();case 74:t.next=79;break;case 76:t.prev=76,t.t4=t.catch(69),console.error("Teardown failed",t.t4);case 79:case"end":return t.stop()}}),t,null,[[1,63],[40,47],[69,76]])})))).apply(this,arguments)}o();var P=function(){function t(t){this._def=null!=t?t:{queries:{},mutations:{},subscriptions:{}}}t.prefixRoutes=function(t,e){var r={};for(var n in t)r[e+n]=t[n];return r};var e=t.prototype;return e.query=function(e,r){var n,o=new t({queries:(n={},n[e]=r,n),mutations:{},subscriptions:{}});return this.merge(o)},e.mutation=function(e,r){var n,o=new t({queries:{},mutations:(n={},n[e]=r,n),subscriptions:{}});return this.merge(o)},e.subscription=function(e,r){var n,o=new t({queries:{},mutations:{},subscriptions:(n={},n[e]=r,n)});return this.merge(o)},e.merge=function(e,r){var n,o=this,i="";if("string"==typeof e&&r instanceof t)i=e,n=r;else{if(!(e instanceof t))throw new Error("Invalid args");n=e}var u=Object.keys(n._def.queries).filter((function(t){return o.has("queries",t)})),s=Object.keys(n._def.mutations).filter((function(t){return o.has("mutations",t)})),c=Object.keys(n._def.subscriptions).filter((function(t){return o.has("subscriptions",t)})),f=[].concat(u,s,c);if(f.length)throw new Error("Duplicate endpoint(s): "+f.join(", "));return new t({queries:a({},this._def.queries,t.prefixRoutes(n._def.queries,i)),mutations:a({},this._def.mutations,t.prefixRoutes(n._def.mutations,i)),subscriptions:a({},this._def.subscriptions,t.prefixRoutes(n._def.subscriptions,i))})},t.getInput=function(t,e){if(t.input)try{var r=t.input;if("function"==typeof r.parse)return r.parse(e);if("function"==typeof r)return r(e);if("function"==typeof r.validateSync)return r.validateSync(e);throw new Error("Could not find a validator fn")}catch(t){throw new m(t)}},e.invoke=function(){var e=u(y.mark((function e(r){var n,o;return y.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.has(r.target,r.path)){e.next=2;break}throw new w('No such route "'+r.path+'"');case 2:return o=t.getInput(n=this._def[r.target][r.path],r.input),e.abrupt("return",n.resolve({ctx:r.ctx,input:o}));case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e.has=function(t,e){return!!this._def[t][e]},t}();function R(t){return function(){var e=u(y.mark((function e(n,o){var i;return y.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.parse(n.url).pathname.substr(1),e.next=3,L(a({},t,{req:n,res:o,endpoint:i}));case 3:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}()}exports.HTTPError=E,exports.Router=P,exports.Subscription=b,exports.SubscriptionDestroyError=x,exports.assertNotBrowser=o,exports.createExpressMiddleware=function(t){return function(e,r){var n=e.path.substr(1);L(a({},t,{req:e,res:r,endpoint:n}))}},exports.createHttpHandler=R,exports.createHttpServer=function(t){var e=R(t),r=n.createServer((function(t,r){return e(t,r)}));return{server:r,listen:function(t){return r.listen(t),{port:0===t?r.address().port:t}}}},exports.createNextApiHandler=function(t){return function(){var e=u(y.mark((function e(r,n){var o,i;return y.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!==(o=Array.isArray(r.query.trpc)?r.query.trpc.join("/"):null)){e.next=5;break}return i=k(new Error('Query "trpc" not found - is the file named [...trpc].ts?')),n.status(i.statusCode).json(i),e.abrupt("return");case 5:return e.next=7,L(a({},t,{req:r,res:n,endpoint:o}));case 7:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}()},exports.getErrorResponseEnvelope=k,exports.getQueryInput=_,exports.httpError=O,exports.requestHandler=L,exports.router=function(){return new P},exports.subscriptionPullFatory=function(t){var e,r=!1;function n(t){return o.apply(this,arguments)}function o(){return(o=u(y.mark((function o(i){return y.wrap((function(o){for(;;)switch(o.prev=o.next){case 0:if(!r){o.next=2;break}return o.abrupt("return");case 2:return o.prev=2,o.next=5,t.pull(i);case 5:o.next=10;break;case 7:o.prev=7,o.t0=o.catch(2),i.error(o.t0);case 10:r||(e=setTimeout((function(){return n(i)}),t.interval));case 11:case"end":return o.stop()}}),o,null,[[2,7]])})))).apply(this,arguments)}return new b({start:function(t){return n(t),function(){clearTimeout(e),r=!0}}})}; | ||
//# sourceMappingURL=server.cjs.production.min.js.map |
@@ -0,3 +1,3 @@ | ||
import { EventEmitter } from 'events'; | ||
import url from 'url'; | ||
import { EventEmitter } from 'events'; | ||
import http from 'http'; | ||
@@ -919,2 +919,269 @@ | ||
var SubscriptionDestroyError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(SubscriptionDestroyError, _Error); | ||
function SubscriptionDestroyError(reason) { | ||
var _this; | ||
_this = _Error.call(this, reason) || this; | ||
_this.reason = reason; | ||
Object.setPrototypeOf(_assertThisInitialized(_this), SubscriptionDestroyError.prototype); | ||
return _this; | ||
} | ||
return SubscriptionDestroyError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
var SubscriptionEventEmitter = /*#__PURE__*/function (_EventEmitter) { | ||
_inheritsLoose(SubscriptionEventEmitter, _EventEmitter); | ||
function SubscriptionEventEmitter() { | ||
return _EventEmitter.apply(this, arguments) || this; | ||
} | ||
return SubscriptionEventEmitter; | ||
}(EventEmitter); | ||
var Subscription = /*#__PURE__*/function () { | ||
function Subscription(opts) { | ||
this.isDestroyed = false; | ||
this.events = new SubscriptionEventEmitter(); | ||
this.opts = _extends({ | ||
getInitialOutput: function getInitialOutput() {// no-op | ||
} | ||
}, opts); | ||
} | ||
var _proto = Subscription.prototype; | ||
_proto.destroy = function destroy(reason) { | ||
if (this.isDestroyed) { | ||
return; | ||
} // debug('Subscription.destroy()', reason); | ||
this.isDestroyed = true; | ||
this.events.emit('destroy', reason); | ||
this.events.removeAllListeners(); | ||
}; | ||
_proto.start = /*#__PURE__*/function () { | ||
var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() { | ||
var _this2 = this; | ||
var emit, cancel; | ||
return runtime_1.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
if (!this.isDestroyed) { | ||
_context.next = 2; | ||
break; | ||
} | ||
throw new Error('Called start() on a destroyed subscription'); | ||
case 2: | ||
_context.prev = 2; | ||
emit = { | ||
error: function error(err) { | ||
return _this2.emitError(err); | ||
}, | ||
data: function data(_data) { | ||
return _this2.emitOutput(_data); | ||
} | ||
}; | ||
_context.next = 6; | ||
return this.opts.getInitialOutput(emit); | ||
case 6: | ||
cancel = this.opts.start(emit); | ||
this.events.on('destroy', function () { | ||
cancel(); | ||
}); | ||
_context.next = 13; | ||
break; | ||
case 10: | ||
_context.prev = 10; | ||
_context.t0 = _context["catch"](2); | ||
this.emitError(_context.t0); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this, [[2, 10]]); | ||
})); | ||
function start() { | ||
return _start.apply(this, arguments); | ||
} | ||
return start; | ||
}(); | ||
_proto.onceOutputAndStop = /*#__PURE__*/function () { | ||
var _onceOutputAndStop = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3() { | ||
var _this3 = this; | ||
return runtime_1.wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
return _context3.abrupt("return", new Promise( /*#__PURE__*/function () { | ||
var _ref = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(resolve, reject) { | ||
var onDestroy, onOutput, onError, cleanup; | ||
return runtime_1.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
onDestroy = function onDestroy(reason) { | ||
reject(new SubscriptionDestroyError(reason)); | ||
cleanup(); | ||
}; | ||
onOutput = function onOutput(data) { | ||
resolve(data); | ||
cleanup(); | ||
_this3.destroy('stopped'); | ||
}; | ||
onError = function onError(err) { | ||
reject(err); | ||
cleanup(); | ||
_this3.destroy('stopped'); | ||
}; | ||
cleanup = function cleanup() { | ||
_this3.events.off('data', onOutput); | ||
_this3.events.off('destroy', onDestroy); | ||
_this3.events.off('error', onError); | ||
}; | ||
_this3.events.once('data', onOutput); | ||
_this3.events.once('destroy', onDestroy); | ||
_this3.events.once('error', onError); | ||
_this3.start()["catch"](function () {// is handled through event | ||
}); | ||
case 8: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2); | ||
})); | ||
return function (_x, _x2) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}())); | ||
case 1: | ||
case "end": | ||
return _context3.stop(); | ||
} | ||
} | ||
}, _callee3); | ||
})); | ||
function onceOutputAndStop() { | ||
return _onceOutputAndStop.apply(this, arguments); | ||
} | ||
return onceOutputAndStop; | ||
}() | ||
/** | ||
* Emit data | ||
*/ | ||
; | ||
_proto.emitOutput = function emitOutput(data) { | ||
this.events.emit('data', data); | ||
} | ||
/** | ||
* Emit error | ||
*/ | ||
; | ||
_proto.emitError = function emitError(err) { | ||
this.events.emit('error', err); | ||
}; | ||
return Subscription; | ||
}(); | ||
function subscriptionPullFatory(opts) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
var timer; | ||
var stopped = false; | ||
function _pull(_x3) { | ||
return _pull2.apply(this, arguments); | ||
} | ||
function _pull2() { | ||
_pull2 = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee4(emit) { | ||
return runtime_1.wrap(function _callee4$(_context4) { | ||
while (1) { | ||
switch (_context4.prev = _context4.next) { | ||
case 0: | ||
if (!stopped) { | ||
_context4.next = 2; | ||
break; | ||
} | ||
return _context4.abrupt("return"); | ||
case 2: | ||
_context4.prev = 2; | ||
_context4.next = 5; | ||
return opts.pull(emit); | ||
case 5: | ||
_context4.next = 10; | ||
break; | ||
case 7: | ||
_context4.prev = 7; | ||
_context4.t0 = _context4["catch"](2); | ||
emit.error(_context4.t0); | ||
case 10: | ||
if (!stopped) { | ||
timer = setTimeout(function () { | ||
return _pull(emit); | ||
}, opts.interval); | ||
} | ||
case 11: | ||
case "end": | ||
return _context4.stop(); | ||
} | ||
} | ||
}, _callee4, null, [[2, 7]]); | ||
})); | ||
return _pull2.apply(this, arguments); | ||
} | ||
return new Subscription({ | ||
start: function start(emit) { | ||
_pull(emit); | ||
return function () { | ||
clearTimeout(timer); | ||
stopped = true; | ||
}; | ||
} | ||
}); | ||
} | ||
assertNotBrowser(); | ||
@@ -1051,3 +1318,3 @@ var HTTPError = /*#__PURE__*/function (_Error) { | ||
_requestHandler = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(_ref2) { | ||
var req, res, router, path, subscriptions, createContext, teardown, _ref2$transformer, transformer, maxBodySize, _req$method, _res$statusCode, output, ctx, method, deserializeInput, body, input, query, _input, _body, _input2, sub, json, _json; | ||
var req, res, router, endpoint, subscriptions, createContext, teardown, _ref2$transformer, transformer, maxBodySize, _req$method, _res$statusCode, output, ctx, method, deserializeInput, body, input, query, _input, _subscriptions$timeou, _body, _input2, sub, onClose, timeout, timer, json, _json; | ||
@@ -1058,3 +1325,3 @@ return runtime_1.wrap(function _callee2$(_context2) { | ||
case 0: | ||
req = _ref2.req, res = _ref2.res, router = _ref2.router, path = _ref2.path, subscriptions = _ref2.subscriptions, createContext = _ref2.createContext, teardown = _ref2.teardown, _ref2$transformer = _ref2.transformer, transformer = _ref2$transformer === void 0 ? { | ||
req = _ref2.req, res = _ref2.res, router = _ref2.router, endpoint = _ref2.endpoint, subscriptions = _ref2.subscriptions, createContext = _ref2.createContext, teardown = _ref2.teardown, _ref2$transformer = _ref2.transformer, transformer = _ref2$transformer === void 0 ? { | ||
serialize: function serialize(data) { | ||
@@ -1111,3 +1378,3 @@ return data; | ||
ctx: ctx, | ||
path: path | ||
path: endpoint | ||
}); | ||
@@ -1117,3 +1384,3 @@ | ||
output = _context2.sent; | ||
_context2.next = 42; | ||
_context2.next = 57; | ||
break; | ||
@@ -1135,3 +1402,3 @@ | ||
ctx: ctx, | ||
path: path | ||
path: endpoint | ||
}); | ||
@@ -1141,3 +1408,3 @@ | ||
output = _context2.sent; | ||
_context2.next = 42; | ||
_context2.next = 57; | ||
break; | ||
@@ -1147,3 +1414,3 @@ | ||
if (!(method === 'PATCH')) { | ||
_context2.next = 41; | ||
_context2.next = 56; | ||
break; | ||
@@ -1166,3 +1433,3 @@ } | ||
ctx: ctx, | ||
path: path | ||
path: endpoint | ||
}); | ||
@@ -1172,84 +1439,54 @@ | ||
sub = _context2.sent; | ||
_context2.next = 38; | ||
return new Promise(function (resolve, reject) { | ||
var _subscriptions$reques, _subscriptions$backpr; | ||
var startTime = Date.now(); | ||
var buffer = []; | ||
var requestTimeoutMs = (_subscriptions$reques = subscriptions == null ? void 0 : subscriptions.requestTimeoutMs) != null ? _subscriptions$reques : 9000; // 10s is vercel's api timeout | ||
onClose = function onClose() { | ||
sub.destroy('closed'); | ||
}; // FIXME - refactor | ||
// this is a bit complex | ||
// needs to handle a few cases: | ||
// - ok subscription | ||
// - error subscription | ||
// - request got prematurely closed | ||
// - request timed out | ||
var backpressureMs = (_subscriptions$backpr = subscriptions == null ? void 0 : subscriptions.backpressureMs) != null ? _subscriptions$backpr : 0; // timers | ||
var backpressureTimer = null; | ||
var requestTimeoutTimer = null; | ||
res.once('close', onClose); | ||
timeout = (_subscriptions$timeou = subscriptions == null ? void 0 : subscriptions.timeout) != null ? _subscriptions$timeou : 9000; // 10s is vercel's api timeout | ||
function cleanup() { | ||
sub.off('data', onData); | ||
sub.off('error', onError); | ||
sub.off('destroy', onDestroy); | ||
req.off('close', onClose); | ||
clearTimeout(requestTimeoutTimer); | ||
clearTimeout(backpressureTimer); | ||
sub.destroy(); | ||
} | ||
timer = setTimeout(function () { | ||
sub.destroy('timeout'); | ||
}, timeout); | ||
_context2.prev = 40; | ||
_context2.next = 43; | ||
return sub.onceOutputAndStop(); | ||
function onData(data) { | ||
buffer.push(data); | ||
var requestTimeLeft = requestTimeoutMs - (Date.now() - startTime); | ||
case 43: | ||
output = _context2.sent; | ||
res.off('close', onClose); | ||
_context2.next = 54; | ||
break; | ||
var success = function success() { | ||
cleanup(); | ||
resolve(buffer); | ||
}; | ||
case 47: | ||
_context2.prev = 47; | ||
_context2.t1 = _context2["catch"](40); | ||
res.off('close', onClose); | ||
clearTimeout(timer); | ||
if (requestTimeLeft >= backpressureMs) { | ||
// will timeout before next backpressure tick | ||
success(); | ||
return; | ||
} | ||
if (!(_context2.t1 instanceof SubscriptionDestroyError && _context2.t1.reason === 'timeout')) { | ||
_context2.next = 53; | ||
break; | ||
} | ||
if (!backpressureTimer) { | ||
backpressureTimer = setTimeout(success, backpressureMs); | ||
return; | ||
} | ||
} | ||
throw new HTTPError(408, "Subscription exceeded " + timeout + "ms - please reconnect."); | ||
function onError(err) { | ||
cleanup(); // maybe if `buffer` has length here we should just return instead? | ||
case 53: | ||
throw _context2.t1; | ||
reject(err); | ||
} | ||
function onClose() { | ||
cleanup(); | ||
reject(new HTTPError(499, "Client Closed Request")); | ||
} | ||
function onRequestTimeout() { | ||
cleanup(); | ||
reject(new HTTPError(408, "Subscription exceeded " + requestTimeoutMs + "ms - please reconnect.")); | ||
} | ||
function onDestroy() { | ||
reject(new HTTPError(500, "Subscription was destroyed prematurely")); | ||
cleanup(); | ||
} | ||
sub.on('data', onData); | ||
sub.on('error', onError); | ||
sub.on('destroy', onDestroy); | ||
req.once('close', onClose); | ||
requestTimeoutTimer = setTimeout(onRequestTimeout, requestTimeoutMs); | ||
sub.start(); | ||
}); | ||
case 38: | ||
output = _context2.sent; | ||
_context2.next = 42; | ||
case 54: | ||
_context2.next = 57; | ||
break; | ||
case 41: | ||
case 56: | ||
throw httpError.badRequest("Unexpected request method " + method); | ||
case 42: | ||
case 57: | ||
json = { | ||
@@ -1263,9 +1500,9 @@ ok: true, | ||
res.end(JSON.stringify(transformer.serialize(json))); | ||
_context2.next = 54; | ||
_context2.next = 69; | ||
break; | ||
case 48: | ||
_context2.prev = 48; | ||
_context2.t1 = _context2["catch"](1); | ||
_json = getErrorResponseEnvelope(_context2.t1); | ||
case 63: | ||
_context2.prev = 63; | ||
_context2.t2 = _context2["catch"](1); | ||
_json = getErrorResponseEnvelope(_context2.t2); | ||
res.statusCode = _json.statusCode; | ||
@@ -1275,24 +1512,24 @@ res.setHeader('Content-Type', 'application/json'); | ||
case 54: | ||
_context2.prev = 54; | ||
_context2.t2 = teardown; | ||
case 69: | ||
_context2.prev = 69; | ||
_context2.t3 = teardown; | ||
if (!_context2.t2) { | ||
_context2.next = 59; | ||
if (!_context2.t3) { | ||
_context2.next = 74; | ||
break; | ||
} | ||
_context2.next = 59; | ||
_context2.next = 74; | ||
return teardown(); | ||
case 59: | ||
_context2.next = 64; | ||
case 74: | ||
_context2.next = 79; | ||
break; | ||
case 61: | ||
_context2.prev = 61; | ||
_context2.t3 = _context2["catch"](54); | ||
console.error('Teardown failed', _context2.t3); | ||
case 76: | ||
_context2.prev = 76; | ||
_context2.t4 = _context2["catch"](69); | ||
console.error('Teardown failed', _context2.t4); | ||
case 64: | ||
case 79: | ||
case "end": | ||
@@ -1302,3 +1539,3 @@ return _context2.stop(); | ||
} | ||
}, _callee2, null, [[1, 48], [54, 61]]); | ||
}, _callee2, null, [[1, 63], [40, 47], [69, 76]]); | ||
})); | ||
@@ -1487,211 +1724,2 @@ return _requestHandler.apply(this, arguments); | ||
var SubscriptionEventEmitter = /*#__PURE__*/function (_EventEmitter) { | ||
_inheritsLoose(SubscriptionEventEmitter, _EventEmitter); | ||
function SubscriptionEventEmitter() { | ||
return _EventEmitter.apply(this, arguments) || this; | ||
} | ||
return SubscriptionEventEmitter; | ||
}(EventEmitter); | ||
var Subscription = /*#__PURE__*/function () { | ||
function Subscription(opts) { | ||
this.isDestroyed = false; | ||
this.events = new SubscriptionEventEmitter(); | ||
this.opts = _extends({}, opts); | ||
} | ||
var _proto = Subscription.prototype; | ||
_proto.destroy = function destroy() { | ||
if (this.isDestroyed) { | ||
return; | ||
} // debug('Subscription.destroy()', reason); | ||
this.isDestroyed = true; | ||
this.events.emit('destroy'); | ||
this.events.removeAllListeners(); | ||
}; | ||
_proto.start = /*#__PURE__*/function () { | ||
var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() { | ||
var _this = this; | ||
var emit, cancel; | ||
return runtime_1.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
if (!this.isDestroyed) { | ||
_context.next = 2; | ||
break; | ||
} | ||
throw new Error('Called start() on a destroyed subscription'); | ||
case 2: | ||
_context.prev = 2; | ||
emit = { | ||
error: function error(err) { | ||
return _this.emitError(err); | ||
}, | ||
data: function data(_data) { | ||
return _this.emitOutput(_data); | ||
} | ||
}; | ||
_context.next = 6; | ||
return this.opts.start(emit); | ||
case 6: | ||
cancel = _context.sent; | ||
if (this.isDestroyed) { | ||
cancel(); | ||
} else { | ||
this.events.on('destroy', cancel); | ||
} | ||
_context.next = 13; | ||
break; | ||
case 10: | ||
_context.prev = 10; | ||
_context.t0 = _context["catch"](2); | ||
this.emitError(_context.t0); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this, [[2, 10]]); | ||
})); | ||
function start() { | ||
return _start.apply(this, arguments); | ||
} | ||
return start; | ||
}(); | ||
_proto.onceOutputAndStop = /*#__PURE__*/function () { | ||
var _onceOutputAndStop = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2() { | ||
return runtime_1.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
throw new Error('Legacy'); | ||
case 1: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2); | ||
})); | ||
function onceOutputAndStop() { | ||
return _onceOutputAndStop.apply(this, arguments); | ||
} | ||
return onceOutputAndStop; | ||
}() | ||
/** | ||
* Emit data | ||
*/ | ||
; | ||
_proto.emitOutput = function emitOutput(data) { | ||
this.events.emit('data', data); | ||
} | ||
/** | ||
* Emit error | ||
*/ | ||
; | ||
_proto.emitError = function emitError(err) { | ||
this.events.emit('error', err); | ||
}; | ||
_proto.on = function on() { | ||
var _this$events; | ||
return (_this$events = this.events).on.apply(_this$events, arguments); | ||
}; | ||
_proto.off = function off() { | ||
var _this$events2; | ||
return (_this$events2 = this.events).off.apply(_this$events2, arguments); | ||
}; | ||
return Subscription; | ||
}(); | ||
function subscriptionPullFactory(opts) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
var timer; | ||
var stopped = false; | ||
function _pull(_x) { | ||
return _pull2.apply(this, arguments); | ||
} | ||
function _pull2() { | ||
_pull2 = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3(emit) { | ||
return runtime_1.wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
if (!stopped) { | ||
_context3.next = 2; | ||
break; | ||
} | ||
return _context3.abrupt("return"); | ||
case 2: | ||
_context3.prev = 2; | ||
_context3.next = 5; | ||
return opts.pull(emit); | ||
case 5: | ||
_context3.next = 10; | ||
break; | ||
case 7: | ||
_context3.prev = 7; | ||
_context3.t0 = _context3["catch"](2); | ||
emit.error(_context3.t0); | ||
case 10: | ||
if (!stopped) { | ||
timer = setTimeout(function () { | ||
return _pull(emit); | ||
}, opts.intervalMs); | ||
} | ||
case 11: | ||
case "end": | ||
return _context3.stop(); | ||
} | ||
} | ||
}, _callee3, null, [[2, 7]]); | ||
})); | ||
return _pull2.apply(this, arguments); | ||
} | ||
return new Subscription({ | ||
start: function start(emit) { | ||
_pull(emit); | ||
return function () { | ||
clearTimeout(timer); | ||
stopped = true; | ||
}; | ||
} | ||
}); | ||
} | ||
function createExpressMiddleware(opts) { | ||
@@ -1703,3 +1731,3 @@ return function (req, res) { | ||
res: res, | ||
path: endpoint | ||
endpoint: endpoint | ||
})); | ||
@@ -1733,3 +1761,3 @@ }; | ||
res: res, | ||
path: endpoint | ||
endpoint: endpoint | ||
})); | ||
@@ -1764,3 +1792,3 @@ | ||
res: res, | ||
path: endpoint | ||
endpoint: endpoint | ||
})); | ||
@@ -1798,3 +1826,3 @@ | ||
export { HTTPError, Router, Subscription, assertNotBrowser, createExpressMiddleware, createHttpHandler, createHttpServer, createNextApiHandler, getErrorResponseEnvelope, getQueryInput, httpError, requestHandler, router, subscriptionPullFactory }; | ||
export { HTTPError, Router, Subscription, SubscriptionDestroyError, assertNotBrowser, createExpressMiddleware, createHttpHandler, createHttpServer, createNextApiHandler, getErrorResponseEnvelope, getQueryInput, httpError, requestHandler, router, subscriptionPullFatory }; | ||
//# sourceMappingURL=server.esm.js.map |
@@ -1,15 +0,6 @@ | ||
/// <reference types="node" /> | ||
import { EventEmitter } from 'events'; | ||
interface SubscriptionEvents<TOutput> { | ||
data: (data: TOutput) => void; | ||
destroy: () => void; | ||
error: (error: Error) => void; | ||
declare type SubscriptionDestroyReason = 'timeout' | 'stopped' | 'startError' | 'closed'; | ||
export declare class SubscriptionDestroyError extends Error { | ||
readonly reason: SubscriptionDestroyReason; | ||
constructor(reason: SubscriptionDestroyReason); | ||
} | ||
declare interface SubscriptionEventEmitter<TOutput> { | ||
on<U extends keyof SubscriptionEvents<TOutput>>(event: U, listener: SubscriptionEvents<TOutput>[U]): this; | ||
once<U extends keyof SubscriptionEvents<TOutput>>(event: U, listener: SubscriptionEvents<TOutput>[U]): this; | ||
emit<U extends keyof SubscriptionEvents<TOutput>>(event: U, ...args: Parameters<SubscriptionEvents<TOutput>[U]>): boolean; | ||
} | ||
declare class SubscriptionEventEmitter<TOutput> extends EventEmitter { | ||
} | ||
declare type UnsubscribeFn = () => void; | ||
@@ -22,3 +13,4 @@ declare type EmitFn<TOutput> = (data: TOutput) => void; | ||
export interface SubscriptionOptions<TOutput> { | ||
start: (emit: SubscriptionEmit<TOutput>) => UnsubscribeFn | Promise<UnsubscribeFn>; | ||
getInitialOutput?: (emit: SubscriptionEmit<TOutput>) => void | Promise<void>; | ||
start: (emit: SubscriptionEmit<TOutput>) => UnsubscribeFn; | ||
} | ||
@@ -30,3 +22,3 @@ export declare class Subscription<TOutput = unknown> { | ||
constructor(opts: SubscriptionOptions<TOutput>); | ||
destroy(): void; | ||
destroy(reason: SubscriptionDestroyReason): void; | ||
start(): Promise<void>; | ||
@@ -42,12 +34,7 @@ onceOutputAndStop(): Promise<TOutput>; | ||
emitError(err: Error): void; | ||
on(...args: Parameters<SubscriptionEventEmitter<TOutput>['on']>): SubscriptionEventEmitter<TOutput>; | ||
off(...args: Parameters<SubscriptionEventEmitter<TOutput>['off']>): SubscriptionEventEmitter<TOutput>; | ||
} | ||
export declare function subscriptionPullFactory<TOutput>(opts: { | ||
/** | ||
* The interval of how often the function should run | ||
*/ | ||
intervalMs: number; | ||
export declare function subscriptionPullFatory<TOutput>(opts: { | ||
interval: number; | ||
pull(emit: SubscriptionEmit<TOutput>): void | Promise<void>; | ||
}): Subscription<TOutput>; | ||
export {}; |
{ | ||
"name": "@trpc/server", | ||
"version": "1.4.0-alpha.1", | ||
"version": "1.4.0", | ||
"description": "TRPC Server", | ||
@@ -46,3 +46,3 @@ "author": "KATT", | ||
}, | ||
"gitHead": "fe71b0c08558c4191decebc738b8e5e99b0c86eb" | ||
"gitHead": "f55262c2bbb60769e509fd351f5ef5d1cf7f0ea1" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
397072
3328
2