@trpc/server 11.0.0-alpha-tmp-issues-5557-types-node-wut.322 → 11.0.0-alpha-tmp-issues-4129-lazy-routers.305

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.
@@ -6,8 +6,8 @@ var TRPCError = require('./error/TRPCError.js');
6
6
  var transformer = require('./transformer.js');
7
7
  var utils = require('./utils.js');
8
8
 
9
- function isRouter(procedureOrRouter) {
10
- return procedureOrRouter._def && 'router' in procedureOrRouter._def;
9
+ function isRouter(value) {
10
+ return typeof value === 'object' && value._def && 'router' in value._def;
11
11
  }
12
12
  const emptyRouter = {
13
13
  _ctx: null,
@@ -27,6 +27,21 @@ const emptyRouter = {
27
27
  * since JS will think that `.then` is something that exists
28
28
  */ 'then'
29
29
  ];
30
+ const lazySymbol = Symbol('lazy');
31
+ function lazy(getRouter) {
32
+ let cachedPromise = null;
33
+ const lazyGetter = ()=>{
34
+ if (!cachedPromise) {
35
+ cachedPromise = getRouter();
36
+ }
37
+ return cachedPromise;
38
+ };
39
+ lazyGetter[lazySymbol] = true;
40
+ return lazyGetter;
41
+ }
42
+ function isLazy(input) {
43
+ return typeof input === 'function' && lazySymbol in input;
44
+ }
30
45
  /**
31
46
  * @internal
32
47
  */ function createRouterFactory(config) {
@@ -36,9 +51,52 @@ const emptyRouter = {
36
51
  throw new Error('Reserved words used in `router({})` call: ' + Array.from(reservedWordsUsed).join(', '));
37
52
  }
38
53
  const procedures = utils.omitPrototype({});
54
+ const lazy = utils.omitPrototype({});
55
+ function createLazyLoader(opts) {
56
+ return {
57
+ ref: opts.ref,
58
+ load: async ()=>{
59
+ const router = await opts.ref();
60
+ const lazyPath = [
61
+ ...opts.path,
62
+ opts.key
63
+ ];
64
+ const lazyKey = lazyPath.join('.');
65
+ opts.aggregate[opts.key] = step(router._def.record, lazyPath);
66
+ //
67
+ delete lazy[lazyKey];
68
+ // add lazy loaders for nested routers
69
+ for (const [nestedKey, nestedItem] of Object.entries(router._def.lazy)){
70
+ const nestedRouterKey = [
71
+ ...lazyPath,
72
+ nestedKey
73
+ ].join('.');
74
+ // console.log('adding lazy', nestedRouterKey);
75
+ lazy[nestedRouterKey] = createLazyLoader({
76
+ ref: nestedItem.ref,
77
+ path: lazyPath,
78
+ key: nestedKey,
79
+ aggregate: opts.aggregate[opts.key]
80
+ });
81
+ }
82
+ }
83
+ };
84
+ }
39
85
  function step(from, path = []) {
40
86
  const aggregate = utils.omitPrototype({});
41
87
  for (const [key, item] of Object.entries(from ?? {})){
88
+ if (isLazy(item)) {
89
+ lazy[[
90
+ ...path,
91
+ key
92
+ ].join('.')] = createLazyLoader({
93
+ path,
94
+ ref: item,
95
+ key,
96
+ aggregate
97
+ });
98
+ continue;
99
+ }
42
100
  if (isRouter(item)) {
43
101
  aggregate[key] = step(item._def.record, [
44
102
  ...path,
@@ -71,69 +129,82 @@ const emptyRouter = {
71
129
  _config: config,
72
130
  router: true,
73
131
  procedures,
132
+ lazy,
74
133
  ...emptyRouter,
75
134
  record
76
135
  };
77
136
  return {
78
137
  ...record,
79
138
  _def,
80
- createCaller (ctx) {
81
- const proxy = createProxy.createRecursiveProxy(({ path , args })=>{
82
- const fullPath = path.join('.');
83
- const procedure = _def.procedures[fullPath];
84
- return procedure({
85
- path: fullPath,
86
- getRawInput: async ()=>args[0],
87
- ctx,
88
- type: procedure._def.type
89
- });
90
- });
91
- return proxy;
92
- }
139
+ createCaller: createCallerInner(_def)
93
140
  };
94
141
  }
95
142
  return createRouterInner;
96
143
  }
97
- function isProcedure(procedureOrRouter) {
98
- return typeof procedureOrRouter === 'function';
144
+ function isProcedure(value) {
145
+ return typeof value === 'function' && 'procedure' in value;
146
+ }
147
+ async function getProcedureAtPath(_def, path) {
148
+ let procedure = _def.procedures[path];
149
+ while(!procedure){
150
+ const key = Object.keys(_def.lazy).find((key)=>path.startsWith(key));
151
+ // console.log(`found lazy: ${key ?? 'NOPE'} (fullPath: ${fullPath})`);
152
+ if (!key) {
153
+ throw new TRPCError.TRPCError({
154
+ code: 'NOT_FOUND',
155
+ message: `No "query"-procedure on path "${path}"`
156
+ });
157
+ }
158
+ // console.log('loading', key, '.......');
159
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
160
+ const lazyRouter = _def.lazy[key];
161
+ await lazyRouter.load();
162
+ procedure = _def.procedures[path];
163
+ }
164
+ return procedure;
99
165
  }
100
166
  /**
101
167
  * @internal
102
- */ function callProcedure(opts) {
103
- const { type , path } = opts;
104
- const proc = opts.procedures[path];
105
- if (!proc || !isProcedure(proc) || proc._def.type !== type && !opts.allowMethodOverride) {
168
+ */ async function callProcedure(opts) {
169
+ const { type , path , _def } = opts;
170
+ const procedure = await getProcedureAtPath(_def, path);
171
+ if (procedure._def.type !== type && !opts.allowMethodOverride) {
106
172
  throw new TRPCError.TRPCError({
107
173
  code: 'NOT_FOUND',
108
174
  message: `No "${type}"-procedure on path "${path}"`
109
175
  });
110
176
  }
111
- return proc(opts);
177
+ return procedure(opts);
178
+ }
179
+ function createCallerInner(_def) {
180
+ return function createCaller(maybeContext) {
181
+ const proxy = createProxy.createRecursiveProxy(({ path , args })=>{
182
+ const fullPath = path.join('.');
183
+ async function callProc(ctx) {
184
+ const procedure = await getProcedureAtPath(_def, fullPath);
185
+ return procedure({
186
+ path: fullPath,
187
+ getRawInput: async ()=>args[0],
188
+ ctx,
189
+ type: procedure._def.type
190
+ });
191
+ }
192
+ if (typeof maybeContext === 'function') {
193
+ const context = maybeContext();
194
+ if (context instanceof Promise) {
195
+ return context.then(callProc);
196
+ }
197
+ return callProc(context);
198
+ }
199
+ return callProc(maybeContext);
200
+ });
201
+ return proxy;
202
+ };
112
203
  }
113
204
  function createCallerFactory() {
114
- return function createCallerInner(router) {
205
+ return function createCaller(router) {
115
206
  const _def = router._def;
116
- return function createCaller(maybeContext) {
117
- const proxy = createProxy.createRecursiveProxy(({ path , args })=>{
118
- const fullPath = path.join('.');
119
- const procedure = _def.procedures[fullPath];
120
- const callProc = (ctx)=>procedure({
121
- path: fullPath,
122
- getRawInput: async ()=>args[0],
123
- ctx,
124
- type: procedure._def.type
125
- });
126
- if (typeof maybeContext === 'function') {
127
- const context = maybeContext();
128
- if (context instanceof Promise) {
129
- return context.then(callProc);
130
- }
131
- return callProc(context);
132
- }
133
- return callProc(maybeContext);
134
- });
135
- return proxy;
136
- };
207
+ return createCallerInner(_def);
137
208
  };
138
209
  }
139
210
  function mergeRouters(...routerList) {
@@ -170,4 +241,5 @@ function mergeRouters(...routerList) {
170
241
  exports.callProcedure = callProcedure;
171
242
  exports.createCallerFactory = createCallerFactory;
172
243
  exports.createRouterFactory = createRouterFactory;
244
+ exports.lazy = lazy;
173
245
  exports.mergeRouters = mergeRouters;
@@ -4,8 +4,8 @@ import { TRPCError } from './error/TRPCError.mjs';
4
4
  import { defaultTransformer } from './transformer.mjs';
5
5
  import { mergeWithoutOverrides, omitPrototype } from './utils.mjs';
6
6
 
7
- function isRouter(procedureOrRouter) {
8
- return procedureOrRouter._def && 'router' in procedureOrRouter._def;
7
+ function isRouter(value) {
8
+ return typeof value === 'object' && value._def && 'router' in value._def;
9
9
  }
10
10
  const emptyRouter = {
11
11
  _ctx: null,
@@ -25,6 +25,21 @@ const emptyRouter = {
25
25
  * since JS will think that `.then` is something that exists
26
26
  */ 'then'
27
27
  ];
28
+ const lazySymbol = Symbol('lazy');
29
+ function lazy(getRouter) {
30
+ let cachedPromise = null;
31
+ const lazyGetter = ()=>{
32
+ if (!cachedPromise) {
33
+ cachedPromise = getRouter();
34
+ }
35
+ return cachedPromise;
36
+ };
37
+ lazyGetter[lazySymbol] = true;
38
+ return lazyGetter;
39
+ }
40
+ function isLazy(input) {
41
+ return typeof input === 'function' && lazySymbol in input;
42
+ }
28
43
  /**
29
44
  * @internal
30
45
  */ function createRouterFactory(config) {
@@ -34,9 +49,52 @@ const emptyRouter = {
34
49
  throw new Error('Reserved words used in `router({})` call: ' + Array.from(reservedWordsUsed).join(', '));
35
50
  }
36
51
  const procedures = omitPrototype({});
52
+ const lazy = omitPrototype({});
53
+ function createLazyLoader(opts) {
54
+ return {
55
+ ref: opts.ref,
56
+ load: async ()=>{
57
+ const router = await opts.ref();
58
+ const lazyPath = [
59
+ ...opts.path,
60
+ opts.key
61
+ ];
62
+ const lazyKey = lazyPath.join('.');
63
+ opts.aggregate[opts.key] = step(router._def.record, lazyPath);
64
+ //
65
+ delete lazy[lazyKey];
66
+ // add lazy loaders for nested routers
67
+ for (const [nestedKey, nestedItem] of Object.entries(router._def.lazy)){
68
+ const nestedRouterKey = [
69
+ ...lazyPath,
70
+ nestedKey
71
+ ].join('.');
72
+ // console.log('adding lazy', nestedRouterKey);
73
+ lazy[nestedRouterKey] = createLazyLoader({
74
+ ref: nestedItem.ref,
75
+ path: lazyPath,
76
+ key: nestedKey,
77
+ aggregate: opts.aggregate[opts.key]
78
+ });
79
+ }
80
+ }
81
+ };
82
+ }
37
83
  function step(from, path = []) {
38
84
  const aggregate = omitPrototype({});
39
85
  for (const [key, item] of Object.entries(from ?? {})){
86
+ if (isLazy(item)) {
87
+ lazy[[
88
+ ...path,
89
+ key
90
+ ].join('.')] = createLazyLoader({
91
+ path,
92
+ ref: item,
93
+ key,
94
+ aggregate
95
+ });
96
+ continue;
97
+ }
40
98
  if (isRouter(item)) {
41
99
  aggregate[key] = step(item._def.record, [
42
100
  ...path,
@@ -69,69 +127,82 @@ const emptyRouter = {
69
127
  _config: config,
70
128
  router: true,
71
129
  procedures,
130
+ lazy,
72
131
  ...emptyRouter,
73
132
  record
74
133
  };
75
134
  return {
76
135
  ...record,
77
136
  _def,
78
- createCaller (ctx) {
79
- const proxy = createRecursiveProxy(({ path , args })=>{
80
- const fullPath = path.join('.');
81
- const procedure = _def.procedures[fullPath];
82
- return procedure({
83
- path: fullPath,
84
- getRawInput: async ()=>args[0],
85
- ctx,
86
- type: procedure._def.type
87
- });
88
- });
89
- return proxy;
90
- }
137
+ createCaller: createCallerInner(_def)
91
138
  };
92
139
  }
93
140
  return createRouterInner;
94
141
  }
95
- function isProcedure(procedureOrRouter) {
96
- return typeof procedureOrRouter === 'function';
142
+ function isProcedure(value) {
143
+ return typeof value === 'function' && 'procedure' in value;
144
+ }
145
+ async function getProcedureAtPath(_def, path) {
146
+ let procedure = _def.procedures[path];
147
+ while(!procedure){
148
+ const key = Object.keys(_def.lazy).find((key)=>path.startsWith(key));
149
+ // console.log(`found lazy: ${key ?? 'NOPE'} (fullPath: ${fullPath})`);
150
+ if (!key) {
151
+ throw new TRPCError({
152
+ code: 'NOT_FOUND',
153
+ message: `No "query"-procedure on path "${path}"`
154
+ });
155
+ }
156
+ // console.log('loading', key, '.......');
157
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
158
+ const lazyRouter = _def.lazy[key];
159
+ await lazyRouter.load();
160
+ procedure = _def.procedures[path];
161
+ }
162
+ return procedure;
97
163
  }
98
164
  /**
99
165
  * @internal
100
- */ function callProcedure(opts) {
101
- const { type , path } = opts;
102
- const proc = opts.procedures[path];
103
- if (!proc || !isProcedure(proc) || proc._def.type !== type && !opts.allowMethodOverride) {
166
+ */ async function callProcedure(opts) {
167
+ const { type , path , _def } = opts;
168
+ const procedure = await getProcedureAtPath(_def, path);
169
+ if (procedure._def.type !== type && !opts.allowMethodOverride) {
104
170
  throw new TRPCError({
105
171
  code: 'NOT_FOUND',
106
172
  message: `No "${type}"-procedure on path "${path}"`
107
173
  });
108
174
  }
109
- return proc(opts);
175
+ return procedure(opts);
176
+ }
177
+ function createCallerInner(_def) {
178
+ return function createCaller(maybeContext) {
179
+ const proxy = createRecursiveProxy(({ path , args })=>{
180
+ const fullPath = path.join('.');
181
+ async function callProc(ctx) {
182
+ const procedure = await getProcedureAtPath(_def, fullPath);
183
+ return procedure({
184
+ path: fullPath,
185
+ getRawInput: async ()=>args[0],
186
+ ctx,
187
+ type: procedure._def.type
188
+ });
189
+ }
190
+ if (typeof maybeContext === 'function') {
191
+ const context = maybeContext();
192
+ if (context instanceof Promise) {
193
+ return context.then(callProc);
194
+ }
195
+ return callProc(context);
196
+ }
197
+ return callProc(maybeContext);
198
+ });
199
+ return proxy;
200
+ };
110
201
  }
111
202
  function createCallerFactory() {
112
- return function createCallerInner(router) {
203
+ return function createCaller(router) {
113
204
  const _def = router._def;
114
- return function createCaller(maybeContext) {
115
- const proxy = createRecursiveProxy(({ path , args })=>{
116
- const fullPath = path.join('.');
117
- const procedure = _def.procedures[fullPath];
118
- const callProc = (ctx)=>procedure({
119
- path: fullPath,
120
- getRawInput: async ()=>args[0],
121
- ctx,
122
- type: procedure._def.type
123
- });
124
- if (typeof maybeContext === 'function') {
125
- const context = maybeContext();
126
- if (context instanceof Promise) {
127
- return context.then(callProc);
128
- }
129
- return callProc(context);
130
- }
131
- return callProc(maybeContext);
132
- });
133
- return proxy;
134
- };
205
+ return createCallerInner(_def);
135
206
  };
136
207
  }
137
208
  function mergeRouters(...routerList) {
@@ -165,4 +236,4 @@ function mergeRouters(...routerList) {
165
236
  return router;
166
237
  }
167
238
 
168
- export { callProcedure, createCallerFactory, createRouterFactory, mergeRouters };
239
+ export { callProcedure, createCallerFactory, createRouterFactory, lazy, mergeRouters };
@@ -51,6 +51,7 @@ exports.isServerDefault = rootConfig.isServerDefault;
51
51
  exports.callProcedure = router.callProcedure;
52
52
  exports.createCallerFactory = router.createCallerFactory;
53
53
  exports.createRouterFactory = router.createRouterFactory;
54
+ exports.lazy = router.lazy;
54
55
  exports.mergeRouters = router.mergeRouters;
55
56
  exports.TRPC_ERROR_CODES_BY_KEY = codes.TRPC_ERROR_CODES_BY_KEY;
56
57
  exports.TRPC_ERROR_CODES_BY_NUMBER = codes.TRPC_ERROR_CODES_BY_NUMBER;
@@ -13,7 +13,7 @@ export { getParseFn } from './unstable-core-do-not-import/parser.mjs';
13
13
  export { procedureTypes } from './unstable-core-do-not-import/procedure.mjs';
14
14
  export { createBuilder, unsetMarker } from './unstable-core-do-not-import/procedureBuilder.mjs';
15
15
  export { isServerDefault } from './unstable-core-do-not-import/rootConfig.mjs';
16
- export { callProcedure, createCallerFactory, createRouterFactory, mergeRouters } from './unstable-core-do-not-import/router.mjs';
16
+ export { callProcedure, createCallerFactory, createRouterFactory, lazy, mergeRouters } from './unstable-core-do-not-import/router.mjs';
17
17
  export { TRPC_ERROR_CODES_BY_KEY, TRPC_ERROR_CODES_BY_NUMBER } from './unstable-core-do-not-import/rpc/codes.mjs';
18
18
  export { parseTRPCMessage } from './unstable-core-do-not-import/rpc/parseTRPCMessage.mjs';
19
19
  export { defaultTransformer, getDataTransformer, transformResult, transformTRPCResponse } from './unstable-core-do-not-import/transformer.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trpc/server",
3
- "version": "11.0.0-alpha-tmp-issues-5557-types-node-wut.322+689319477",
3
+ "version": "11.0.0-alpha-tmp-issues-4129-lazy-routers.305+cf8d1abcd",
4
4
  "description": "The tRPC server library",
5
5
  "author": "KATT",
6
6
  "license": "MIT",
@@ -156,5 +156,5 @@
156
156
  "funding": [
157
157
  "https://trpc.io/sponsor"
158
158
  ],
159
- "gitHead": "6893194772277fb2f638cb1e9874cd0f1c1456b1"
159
+ "gitHead": "cf8d1abcda5327f4caab1ac38c648b31c89d9c0a"
160
160
  }
@@ -127,7 +127,7 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
127
127
  await ctxPromise; // asserts context has been set
128
128
 
129
129
  const result = await callProcedure({
130
- procedures: router._def.procedures,
130
+ _def: router._def,
131
131
  path,
132
132
  getRawInput: async () => input,
133
133
  ctx,
@@ -300,7 +300,7 @@ export async function resolveHTTPResponse<
300
300
  const input = inputs[index];
301
301
  try {
302
302
  const data = await callProcedure({
303
- procedures: opts.router._def.procedures,
303
+ _def: router._def,
304
304
  path,
305
305
  getRawInput: async () => input,
306
306
  ctx,
@@ -84,7 +84,10 @@ class TRPCBuilder<TContext extends object, TMeta extends object> {
84
84
 
85
85
  const config: RootConfig<$Root> = {
86
86
  transformer: getDataTransformer(opts?.transformer ?? defaultTransformer),
87
- isDev: opts?.isDev ?? globalThis.process?.env.NODE_ENV !== 'production',
87
+ isDev:
88
+ opts?.isDev ??
89
+ // eslint-disable-next-line @typescript-eslint/dot-notation
90
+ globalThis.process?.env['NODE_ENV'] !== 'production',
88
91
  allowOutsideOfServer: opts?.allowOutsideOfServer ?? false,
89
92
  errorFormatter: opts?.errorFormatter ?? defaultFormatter,
90
93
  isServer: opts?.isServer ?? isServerDefault,
@@ -538,6 +538,7 @@ function createProcedureCaller(_def: AnyProcedureBuilderDef): AnyProcedure {
538
538
  }
539
539
 
540
540
  procedure._def = _def;
541
+ procedure.procedure = true;
541
542
 
542
543
  // FIXME typecast shouldn't be needed - fixittt
543
544
  return procedure as unknown as AnyProcedure;