forked from felangel/mason
/
build_route_configuration.dart
447 lines (393 loc) · 12.6 KB
/
build_route_configuration.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import 'dart:io';
import 'package:dart_frog_gen/src/path_to_route.dart';
import 'package:path/path.dart' as path;
/// Build a [RouteConfiguration] based on the provided root project [directory].
RouteConfiguration buildRouteConfiguration(Directory directory) {
final routesDirectory = Directory(path.join(directory.path, 'routes'));
if (!routesDirectory.existsSync()) {
throw Exception('Could not find directory ${routesDirectory.path}');
}
final globalMiddlewareFile = File(
path.join(routesDirectory.path, '_middleware.dart'),
);
final globalMiddleware = globalMiddlewareFile.existsSync()
? MiddlewareFile(
name: 'middleware',
path: path
.join('..', path.relative(globalMiddlewareFile.path))
.replaceAll(r'\', '/'),
)
: null;
final endpoints = <String, List<RouteFile>>{};
final middleware = <MiddlewareFile>[
if (globalMiddleware != null) globalMiddleware
];
final routes = <RouteFile>[];
final rogueRoutes = <RouteFile>[];
final directories = _getRouteDirectories(
directory: routesDirectory,
routesDirectory: routesDirectory,
onRoute: routes.add,
onMiddleware: middleware.add,
onEndpoint: (endpoint, file) {
if (!endpoints.containsKey(endpoint)) {
endpoints[endpoint] = [file];
} else {
endpoints[endpoint]!.add(file);
}
},
onRogueRoute: rogueRoutes.add,
);
final publicDirectory = Directory(path.join(directory.path, 'public'));
final mainDartFile = File(path.join(directory.path, 'main.dart'));
return RouteConfiguration(
globalMiddleware: globalMiddleware,
middleware: middleware,
directories: directories,
routes: routes,
rogueRoutes: rogueRoutes,
endpoints: endpoints,
serveStaticFiles: publicDirectory.existsSync(),
invokeCustomEntrypoint: mainDartFile.existsSync(),
);
}
List<RouteDirectory> _getRouteDirectories({
required Directory directory,
required Directory routesDirectory,
required void Function(RouteFile route) onRoute,
required void Function(MiddlewareFile route) onMiddleware,
required void Function(String endpoint, RouteFile file) onEndpoint,
required void Function(RouteFile route) onRogueRoute,
List<MiddlewareFile> middleware = const [],
}) {
final directories = <RouteDirectory>[];
final entities = directory.listSync().sorted();
final directorySegment =
directory.path.split('routes').last.replaceAll(r'\', '/');
final directoryPath = directorySegment.startsWith('/')
? directorySegment
: '/$directorySegment';
// Only add nested middleware -- global middleware is added separately.
MiddlewareFile? localMiddleware;
if (directory.path != path.join(Directory.current.path, 'routes')) {
final middlewareFile = File(path.join(directory.path, '_middleware.dart'));
if (middlewareFile.existsSync()) {
final middlewarePath = path
.relative(middlewareFile.path, from: routesDirectory.path)
.replaceAll(r'\', '/');
localMiddleware = MiddlewareFile(
name: middlewarePath.toAlias(),
path: path.join('..', 'routes', middlewarePath).replaceAll(r'\', '/'),
);
onMiddleware(localMiddleware);
}
}
final updatedMiddleware = [
...middleware,
if (localMiddleware != null) localMiddleware,
];
final files = _getRouteFiles(
directory: directory,
routesDirectory: routesDirectory,
onRoute: onRoute,
onRogueRoute: onRogueRoute,
);
if (files.isNotEmpty) {
final baseRoute = directoryPath.toRoute();
for (final file in files) {
var endpoint = (baseRoute + file.route.toRoute()).replaceAll('//', '/');
if (endpoint.endsWith('/')) {
endpoint = endpoint.substring(0, endpoint.length - 1);
}
if (endpoint.isEmpty) endpoint = '/';
onEndpoint(endpoint, file);
}
directories.add(
RouteDirectory(
name: directoryPath.toAlias(),
route: baseRoute,
middleware: updatedMiddleware,
files: files,
params: directoryPath.toParams(),
),
);
}
entities.whereType<Directory>().forEach((directory) {
directories.addAll(
_getRouteDirectories(
directory: directory,
routesDirectory: routesDirectory,
onRoute: onRoute,
onMiddleware: onMiddleware,
onEndpoint: onEndpoint,
onRogueRoute: onRogueRoute,
middleware: updatedMiddleware,
),
);
});
return directories;
}
List<RouteFile> _getRouteFiles({
required Directory directory,
required Directory routesDirectory,
required void Function(RouteFile route) onRoute,
required void Function(RouteFile route) onRogueRoute,
String prefix = '',
}) {
final files = <RouteFile>[];
final directorySegment =
directory.path.split('routes').last.replaceAll(r'\', '/');
final directoryPath = directorySegment.startsWith('/')
? directorySegment
: '/$directorySegment';
final entities = directory.listSync().sorted();
final subDirectories = entities
.whereType<Directory>()
.map((directory) => path.basename(directory.path))
.toSet();
entities.where((e) => e.isRoute).cast<File>().forEach((entity) {
final filePath = path
.relative(entity.path, from: routesDirectory.path)
.replaceAll(r'\', '/');
String getFileRoute() {
final routePath = pathToRoute(path.join('..', 'routes', filePath));
final index = routePath.indexOf(directoryPath);
final fileRoutePath = index == -1
? routePath
: routePath.substring(index + directoryPath.length);
var fileRoute = fileRoutePath.isEmpty ? '/' : fileRoutePath;
fileRoute = prefix + fileRoute;
if (!fileRoute.startsWith('/')) fileRoute = '/$fileRoute';
return fileRoute;
}
final fileRoute = getFileRoute();
final relativeFilePath = path.join('..', 'routes', filePath);
final route = RouteFile(
name: filePath.toAlias(),
path: relativeFilePath.replaceAll(r'\', '/'),
route: fileRoute.toRoute(),
params: fileRoute.toParams(),
);
onRoute(route);
files.add(route);
final fileBasename = path.basenameWithoutExtension(filePath);
final conflictingIndexFile = File(
path.join(directory.path, fileBasename, 'index.dart'),
);
final isRogueRoute = subDirectories.contains(fileBasename) &&
!conflictingIndexFile.existsSync();
if (isRogueRoute) onRogueRoute(route);
});
return files;
}
extension on String {
String toAlias() {
final alias = path
.withoutExtension(this)
.replaceAll('[', r'$')
.replaceAll(']', '')
.replaceAll('/', '_');
if (alias == '') return 'index';
return alias;
}
String toRoute() {
return replaceAll('[', '<').replaceAll(']', '>').replaceAll(r'\', '/');
}
List<String> toParams() {
final regexp = RegExp(r'\[(.*?)\]');
final matches = regexp.allMatches(this);
return matches.map((m) => m[0]!.replaceAll(RegExp(r'\[|\]'), '')).toList();
}
}
extension on List<FileSystemEntity> {
List<FileSystemEntity> sorted() {
return this..sort((a, b) => b.path.compareTo(a.path));
}
}
extension on FileSystemEntity {
bool get isRoute {
return this is File &&
path.basename(this.path).endsWith('.dart') &&
path.basename(this.path) != '_middleware.dart';
}
}
/// {@template route_configuration}
/// An object containing all route configuration metadata
/// required to generate a dart frog server.
/// {@endtemplate}
class RouteConfiguration {
/// {@macro route_configuration}
const RouteConfiguration({
required this.middleware,
required this.directories,
required this.routes,
required this.endpoints,
required this.rogueRoutes,
this.globalMiddleware,
this.serveStaticFiles = false,
this.invokeCustomEntrypoint = false,
});
/// Whether to invoke a custom entrypoint script (`main.dart`).
final bool invokeCustomEntrypoint;
/// Whether to serve static files. Defaults to false.
final bool serveStaticFiles;
/// Optional global middleware.
final MiddlewareFile? globalMiddleware;
/// List of all nested middleware.
/// Top-level middleware is excluded (see [globalMiddleware]).
final List<MiddlewareFile> middleware;
/// List of all route directories.
/// Sorted from leaf nodes to root.
final List<RouteDirectory> directories;
/// List of all route files.
final List<RouteFile> routes;
/// A map of all endpoint paths to resolved route files.
final Map<String, List<RouteFile>> endpoints;
/// List of all rogue routes.
///
/// A route is considered rogue when it is defined outside
/// of an existing subdirectory with the same name.
///
/// For example:
///
/// ```
/// ├── routes
/// │ ├── foo
/// │ │ └── example.dart
/// │ ├── foo.dart
/// ```
///
/// In the above scenario, `foo.dart` is rogue because it is defined
/// outside of the existing `foo` directory.
///
/// Instead, `foo.dart` should be renamed to `index.dart` and placed within
/// the `foo` directory like:
///
/// ```
/// ├── routes
/// │ ├── foo
/// │ │ ├── example.dart
/// │ │ └── index.dart
/// ```
final List<RouteFile> rogueRoutes;
}
/// {@template route_directory}
/// A class containing metadata regarding a route directory.
/// {@endtemplate}
class RouteDirectory {
/// {@macro route_directory}
const RouteDirectory({
required this.name,
required this.route,
required this.middleware,
required this.files,
required this.params,
});
/// The alias for the current directory.
final String name;
/// The route which will be used to mount routers.
final String route;
/// The dynamic route params associated with the directory.
final List<String> params;
/// List of middleware for the provided router.
final List<MiddlewareFile> middleware;
/// A list of nested route files within the directory.
final List<RouteFile> files;
/// Create a copy of the current instance and override zero or more values.
RouteDirectory copyWith({
String? name,
String? route,
List<MiddlewareFile>? middleware,
List<RouteFile>? files,
List<String>? params,
}) {
return RouteDirectory(
name: name ?? this.name,
route: route ?? this.route,
middleware: middleware ?? this.middleware,
files: files ?? this.files,
params: params ?? this.params,
);
}
/// Convert the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() {
return <String, dynamic>{
'name': name,
'route': route,
'middleware': middleware.map((m) => m.toJson()).toList(),
'files': files.map((f) => f.toJson()).toList(),
'directory_params': params,
};
}
}
/// {@template route_file}
/// A class containing metadata regarding a route file.
/// {@endtemplate}
class RouteFile {
/// {@macro route_file}
const RouteFile({
required this.name,
required this.path,
required this.route,
required this.params,
});
/// The alias for the current file.
final String name;
/// The import path for the current instance.
final String path;
/// The route used by router instances.
final String route;
/// The dynamic route params associated with the file.
final List<String> params;
/// Create a copy of the current instance and override zero or more values.
RouteFile copyWith({
String? name,
String? path,
String? route,
List<String>? params,
}) {
return RouteFile(
name: name ?? this.name,
path: path ?? this.path,
route: route ?? this.route,
params: params ?? this.params,
);
}
/// Convert the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() {
return <String, dynamic>{
'name': name,
'path': path,
'route': route,
'file_params': params,
};
}
}
/// {@template middleware_file}
/// A class containing metadata regarding a route directory.
/// {@endtemplate}
class MiddlewareFile {
/// {@macro middleware_file}
const MiddlewareFile({
required this.name,
required this.path,
});
/// The alias for the current directory.
final String name;
/// The import path for the current instance.
final String path;
/// Create a copy of the current instance and override zero or more values.
MiddlewareFile copyWith({String? name, String? path}) {
return MiddlewareFile(
name: name ?? this.name,
path: path ?? this.path,
);
}
/// Convert the current instance to a `Map<String, dynamic>`.
Map<String, dynamic> toJson() {
return <String, dynamic>{
'name': name,
'path': path,
};
}
}