arri 0.58.1 → 0.60.1

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.
@@ -1,493 +0,0 @@
1
- import { existsSync } from 'node:fs';
2
- import { listen } from '@joshmossas/listhen';
3
- import { loadConfig } from 'c12';
4
- import { defineCommand } from 'citty';
5
- import * as esbuild from 'esbuild';
6
- import { dynamicEventHandler, toNodeListener, fromNodeMiddleware } from 'h3';
7
- import path from 'pathe';
8
- import fs from 'node:fs/promises';
9
- import { camelCase, removeDisallowedChars, kebabCase } from '@arrirpc/codegen-utils';
10
- import { a, ValidationError } from '@arrirpc/schema';
11
- import { ofetch } from '@joshmossas/ofetch';
12
- import { createConsola } from 'consola';
13
- import prettier from 'prettier';
14
-
15
- const logger = createConsola().withTag("arri");
16
- const GEN_APP_FILE = "__arri_app.ts";
17
- const OUT_APP_FILE = "app.mjs";
18
- const OUT_SERVER_ENTRY = "server.mjs";
19
- const OUT_CODEGEN = "codegen.mjs";
20
- async function setupWorkingDir(config) {
21
- const arriDir = path.resolve(config.rootDir, config.buildDir);
22
- const outDir = path.resolve(config.rootDir, ".output");
23
- if (existsSync(arriDir)) {
24
- await fs.rm(arriDir, { recursive: true, force: true });
25
- }
26
- if (existsSync(outDir)) {
27
- await fs.rm(outDir, { recursive: true, force: true });
28
- }
29
- await fs.mkdir(arriDir);
30
- await fs.mkdir(outDir);
31
- }
32
- async function createAppWithRoutesModule(config) {
33
- const glob = await import('globby');
34
- const appModule = path.resolve(config.rootDir, config.srcDir, config.entry);
35
- const appImportParts = path.relative(path.resolve(config.rootDir, config.buildDir), appModule).split(".");
36
- appImportParts.pop();
37
- const routes = [];
38
- const existingRoutes = [];
39
- await Promise.all(
40
- config.procedureGlobPatterns.map(async (pattern) => {
41
- const results = await getFsRouteBatch(glob.globby, pattern, config);
42
- for (const result of results) {
43
- if (!existingRoutes.includes(result.name)) {
44
- routes.push(result);
45
- existingRoutes.push(result.name);
46
- }
47
- }
48
- })
49
- );
50
- routes.sort((a2, b) => a2.name < b.name ? -1 : 1);
51
- const module = await prettier.format(
52
- `import sourceMapSupport from 'source-map-support';
53
- sourceMapSupport.install();
54
- import app from '${appImportParts.join(".")}';
55
- ${routes.map(
56
- (route) => `import ${route.importName} from '${route.importPath}';`
57
- ).join("\n")}
58
-
59
- ${routes.map((route) => `app.rpc('${route.name}', ${route.importName});`).join("\n")}
60
-
61
- export default app;`,
62
- { parser: "typescript", tabWidth: 4 }
63
- );
64
- await fs.writeFile(
65
- path.resolve(config.rootDir, config.buildDir, GEN_APP_FILE),
66
- module
67
- );
68
- }
69
- async function getFsRouteBatch(glob, globPattern, config) {
70
- if (!config.procedureDir) {
71
- return [];
72
- }
73
- const target = `${config.rootDir}/${config.srcDir}/${config.procedureDir}/${globPattern}`.split("//").join("/").split("//").join("/");
74
- const files = await glob(target, {
75
- onlyFiles: true
76
- });
77
- const routes = [];
78
- for (const file of files) {
79
- const meta = getRpcMetaFromPath(config, file);
80
- if (meta) {
81
- const importParts = path.relative(path.resolve(config.rootDir, config.buildDir), file).split(".");
82
- importParts.pop();
83
- routes.push({
84
- name: meta.id,
85
- importName: camelCase(meta.id.split(".").join("_")),
86
- importPath: `./${importParts.join(".")}`
87
- });
88
- }
89
- }
90
- return routes;
91
- }
92
- const disallowedNameChars = "~`!@#$%^&*()-+=[]{}\\|:;\"'<>,./";
93
- const getRpcMetaFromPath = (config, filePath) => {
94
- if (!config.procedureDir) {
95
- return void 0;
96
- }
97
- const resolvedFilePath = filePath.split("./").join("/");
98
- const parts = resolvedFilePath.split("/");
99
- const reversedParts = [...parts].reverse();
100
- const nameParts = [];
101
- for (const part of reversedParts) {
102
- if (part === config.procedureDir) {
103
- break;
104
- }
105
- nameParts.push(part);
106
- }
107
- const fileName = nameParts.reverse().pop() ?? "";
108
- const serviceParts = nameParts.filter((part) => part.trim().length > 0).map((part) => removeDisallowedChars(part, disallowedNameChars));
109
- const fileNameParts = fileName.split(".");
110
- if (!fileNameParts.length) {
111
- return void 0;
112
- }
113
- const rpcName = removeDisallowedChars(
114
- fileNameParts[0],
115
- disallowedNameChars
116
- );
117
- const httpParts = [
118
- ...serviceParts.map((part) => kebabCase(part)),
119
- kebabCase(rpcName)
120
- ];
121
- return {
122
- id: [...serviceParts, rpcName].join("."),
123
- httpPath: `/${httpParts.join("/")}`
124
- };
125
- };
126
- function isInsideDir(dir, parentDir) {
127
- if (path.resolve(dir).startsWith(path.resolve(parentDir))) {
128
- return true;
129
- }
130
- return false;
131
- }
132
- async function getArriPackageMetadata() {
133
- const npmPackageResponse = await ofetch("https://registry.npmjs.com/arri");
134
- const arriInfo = a.safeParse(NpmRegistryPackage, npmPackageResponse);
135
- if (!arriInfo.success) {
136
- const errors = a.errors(NpmRegistryPackage, npmPackageResponse);
137
- console.warn(errors);
138
- throw new ValidationError({
139
- message: "Arri parsing response from registry",
140
- errors
141
- });
142
- }
143
- return arriInfo.value;
144
- }
145
- const NpmPackageVersion = a.partial(
146
- a.object({
147
- name: a.string(),
148
- version: a.string(),
149
- _id: a.string(),
150
- maintainers: a.array(
151
- a.object({
152
- name: a.string(),
153
- email: a.string()
154
- })
155
- ),
156
- bin: a.record(a.string()),
157
- dist: a.any(),
158
- main: a.string(),
159
- type: a.string(),
160
- types: a.string(),
161
- module: a.string(),
162
- gitHead: a.string(),
163
- _npmUser: a.object({
164
- name: a.string(),
165
- email: a.string()
166
- }),
167
- description: a.string(),
168
- directories: a.record(a.any()),
169
- _nodeVersion: a.string(),
170
- dependencies: a.record(a.string()),
171
- _hasShrinkWrap: a.boolean(),
172
- _npmOperationalInternal: a.any()
173
- })
174
- );
175
- const NpmRegistryPackage = a.object({
176
- _id: a.string(),
177
- _rev: a.string(),
178
- name: a.string(),
179
- description: a.string(),
180
- "dist-tags": a.record(a.string()),
181
- versions: a.record(NpmPackageVersion),
182
- time: a.record(a.string()),
183
- maintainers: a.array(
184
- a.object({
185
- name: a.string(),
186
- email: a.string()
187
- })
188
- ),
189
- author: a.object({
190
- name: a.string(),
191
- url: a.string()
192
- }),
193
- repository: a.optional(
194
- a.partial(
195
- a.object({
196
- type: a.string(),
197
- url: a.string(),
198
- directory: a.string()
199
- })
200
- )
201
- ),
202
- license: a.optional(a.string()),
203
- homepage: a.optional(a.string()),
204
- bugs: a.optional(
205
- a.partial(
206
- a.object({
207
- url: a.string()
208
- })
209
- )
210
- ),
211
- readme: a.optional(a.string()),
212
- readmeFilename: a.optional(a.string())
213
- });
214
-
215
- function isArriConfig(input) {
216
- if (typeof input !== "object" || input === null) {
217
- return false;
218
- }
219
- if ("generators" in input) {
220
- if (!Array.isArray(input.generators)) {
221
- return false;
222
- }
223
- }
224
- if ("port" in input) {
225
- if (typeof input.port !== "number") {
226
- return false;
227
- }
228
- if (Number.isNaN(input.port)) {
229
- return false;
230
- }
231
- }
232
- if ("entry" in input && typeof input.entry !== "string") {
233
- return false;
234
- }
235
- return true;
236
- }
237
- function isResolvedArriConfig(input) {
238
- if (!isArriConfig(input)) {
239
- return false;
240
- }
241
- return typeof input.rootDir === "string" && typeof input.srcDir === "string" && (typeof input.procedureDir === "string" || typeof input.procedureDir === "boolean") && Array.isArray(input.procedureGlobPatterns) && Array.isArray(input.generators);
242
- }
243
- const defaultConfig = {
244
- port: 3e3,
245
- rootDir: ".",
246
- srcDir: "src",
247
- entry: "app.ts",
248
- serverEntry: "",
249
- procedureDir: "procedures",
250
- procedureGlobPatterns: ["**/*.rpc.ts"],
251
- generators: [],
252
- buildDir: ".arri",
253
- esbuild: {},
254
- https: false,
255
- http2: false,
256
- devServer: {}
257
- };
258
- function defineConfig(config) {
259
- return {
260
- port: config.port ?? defaultConfig.port,
261
- rootDir: config.rootDir ?? defaultConfig.rootDir,
262
- srcDir: config.srcDir ?? defaultConfig.srcDir,
263
- entry: config.entry ?? defaultConfig.entry,
264
- procedureDir: config.procedureDir ?? defaultConfig.procedureDir,
265
- procedureGlobPatterns: config.procedureGlobPatterns ?? defaultConfig.procedureGlobPatterns,
266
- generators: config.generators ?? defaultConfig.generators,
267
- buildDir: config.buildDir ?? defaultConfig.buildDir,
268
- esbuild: config.esbuild ?? defaultConfig.esbuild,
269
- serverEntry: config.serverEntry ?? "",
270
- https: config.https ?? false,
271
- http2: config.http2 ?? false,
272
- devServer: config.devServer ?? {}
273
- };
274
- }
275
-
276
- const DEV_ENDPOINT_ROOT = `/__arri_dev__`;
277
- const DEV_DEFINITION_ENDPOINT = `${DEV_ENDPOINT_ROOT}/__definition`;
278
- const dev = defineCommand({
279
- meta: {
280
- name: "dev",
281
- description: "Start the arri dev server"
282
- },
283
- args: {
284
- config: {
285
- type: "string",
286
- description: "Path to the arri config file",
287
- alias: "c",
288
- default: "./arri.config.ts"
289
- }
290
- },
291
- async run({ args }) {
292
- const { config } = await loadConfig({
293
- configFile: path.resolve(args.config)
294
- });
295
- if (!isResolvedArriConfig(config)) {
296
- throw new Error("Unable to find config");
297
- }
298
- const appEntry = path.resolve(
299
- config.rootDir,
300
- config.srcDir,
301
- config.entry
302
- );
303
- if (!existsSync(appEntry)) {
304
- throw new Error(`Unable to find entry at ${appEntry}`);
305
- }
306
- await startDevServer(config);
307
- }
308
- });
309
- async function bundleFilesContext(config) {
310
- return await esbuild.context({
311
- ...config.esbuild,
312
- entryPoints: [
313
- path.resolve(config.rootDir, config.buildDir, GEN_APP_FILE)
314
- ],
315
- outfile: path.resolve(config.rootDir, ".output", OUT_APP_FILE),
316
- format: "esm",
317
- bundle: true,
318
- packages: "external",
319
- sourcemap: config.esbuild.sourcemap ?? true,
320
- target: config.esbuild.target ?? "node20",
321
- platform: config.esbuild.platform ?? "node"
322
- });
323
- }
324
- async function createDevServer(config) {
325
- const h3 = await import('h3');
326
- const app = h3.createApp();
327
- const dynamicHandler = dynamicEventHandler(
328
- () => "<div>initializing server...</div>"
329
- );
330
- app.use(dynamicHandler);
331
- let ws;
332
- const listener = await listen(toNodeListener(app), {
333
- port: config.port,
334
- https: config.https,
335
- http2: config.http2,
336
- public: true,
337
- ws: {
338
- resolve(info) {
339
- if (ws?.resolve) {
340
- return ws.resolve(info);
341
- }
342
- return {};
343
- }
344
- }
345
- });
346
- let secondaryListener;
347
- if (config.devServer.httpWithHttps) {
348
- secondaryListener = await listen(toNodeListener(app), {
349
- port: config.devServer.httpWithHttpsPort ?? config.port + 1,
350
- https: false,
351
- http2: config.http2,
352
- public: true,
353
- ws: {
354
- resolve(info) {
355
- if (ws?.resolve) {
356
- return ws.resolve(info);
357
- }
358
- return {};
359
- }
360
- },
361
- qr: false,
362
- showURL: false
363
- });
364
- logger.info(
365
- `Serving unencrypted traffic from port ${secondaryListener.address.port}`
366
- );
367
- }
368
- async function reload() {
369
- const appEntry = (await import(path.resolve(
370
- config.rootDir,
371
- ".output",
372
- `${OUT_APP_FILE}?version=${Date.now()}`
373
- ))).default;
374
- dynamicHandler.set(fromNodeMiddleware(appEntry.h3App.handler));
375
- ws = appEntry.h3App.websocket;
376
- return appEntry.getAppDefinition();
377
- }
378
- await reload();
379
- return {
380
- h3App: app,
381
- listener,
382
- secondaryListener,
383
- reload,
384
- ws
385
- };
386
- }
387
- async function startDevServer(config) {
388
- await setupWorkingDir(config);
389
- const watcher = await import('chokidar');
390
- let fileWatcher;
391
- await createAppWithRoutesModule(config);
392
- const context = await bundleFilesContext(config);
393
- await context.rebuild();
394
- const devServer = await createDevServer(config);
395
- let appDef = await devServer.reload();
396
- let appDefStr = JSON.stringify(appDef);
397
- if (config.generators.length) {
398
- logger.info(`Running generators...`);
399
- await generateClientsFromDefinition(appDef, config);
400
- } else {
401
- logger.warn(`No generators specified in config. Skipping codegen.`);
402
- }
403
- const cleanExit = async () => {
404
- process.exit();
405
- };
406
- process.on("exit", async () => {
407
- await Promise.allSettled([fileWatcher?.close(), context.dispose()]);
408
- });
409
- process.on("SIGINT", cleanExit);
410
- process.on("SIGTERM", cleanExit);
411
- async function load(_isRestart, _reason) {
412
- if (fileWatcher) {
413
- await fileWatcher.close();
414
- }
415
- const srcDir = path.resolve(config.rootDir ?? "", config.srcDir);
416
- const dirsToWatch = [srcDir];
417
- if (config.esbuild.alias) {
418
- for (const key of Object.keys(config.esbuild.alias)) {
419
- const alias = config.esbuild.alias[key];
420
- if (alias) {
421
- if (!isInsideDir(alias, srcDir)) {
422
- dirsToWatch.push(alias);
423
- }
424
- }
425
- }
426
- }
427
- if (config.devServer.additionalWatchDirs?.length) {
428
- for (const dir of config.devServer.additionalWatchDirs) {
429
- dirsToWatch.push(dir);
430
- }
431
- }
432
- const buildDir = path.resolve(config.rootDir, config.buildDir);
433
- const outDir = path.resolve(config.rootDir, ".output");
434
- fileWatcher = watcher.watch(dirsToWatch, {
435
- ignoreInitial: true,
436
- ignored: [
437
- buildDir,
438
- outDir,
439
- "**/.output",
440
- "**/dist/**",
441
- "**/node_modules/**",
442
- "**/.git/**"
443
- ]
444
- });
445
- fileWatcher.on("all", async (eventName, _path) => {
446
- if (eventName === "addDir" || eventName === "add") {
447
- return;
448
- }
449
- await createAppWithRoutesModule(config);
450
- try {
451
- const reloadStart = (/* @__PURE__ */ new Date()).getTime();
452
- logger.log(
453
- "Change detected. Bundling files and restarting server...."
454
- );
455
- await context.rebuild();
456
- const newAppDef = await devServer.reload();
457
- const newAppDefStr = JSON.stringify(newAppDef);
458
- logger.log(
459
- `Server restarted in ${( new Date()).getTime() - reloadStart}ms`
460
- );
461
- if (config.generators.length && newAppDefStr !== appDefStr) {
462
- logger.info(
463
- `App Definition updated. Regenerating clients...`
464
- );
465
- await generateClientsFromDefinition(newAppDef, config);
466
- appDef = newAppDef;
467
- appDefStr = newAppDefStr;
468
- }
469
- } catch (err) {
470
- logger.error("ERROR", err);
471
- }
472
- });
473
- }
474
- await load();
475
- }
476
- async function generateClientsFromDefinition(appDef, config) {
477
- const startTime = (/* @__PURE__ */ new Date()).getTime();
478
- try {
479
- const clientCount = config.generators.length;
480
- await Promise.allSettled(
481
- config.generators.map(
482
- (generator) => generator.generator(appDef, true)
483
- )
484
- );
485
- logger.success(
486
- `Generated ${clientCount} client${clientCount === 1 ? "" : "s"} in ${( new Date()).getTime() - startTime}ms`
487
- );
488
- } catch (err) {
489
- logger.error(err);
490
- }
491
- }
492
-
493
- export { DEV_DEFINITION_ENDPOINT as D, GEN_APP_FILE as G, OUT_CODEGEN as O, isResolvedArriConfig as a, defineConfig as b, createAppWithRoutesModule as c, defaultConfig as d, OUT_SERVER_ENTRY as e, OUT_APP_FILE as f, getArriPackageMetadata as g, dev as h, isArriConfig as i, logger as l, setupWorkingDir as s };