@platformatic/nitro 0.0.1 → 3.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ import neostandard from 'neostandard'
2
+
3
+ export default neostandard({
4
+ ignores: ['**/.output', '**/.nitro', '**/tmp', 'test/fixtures/**']
5
+ })
package/index.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { BaseCapability, BaseContext, BaseOptions } from '@platformatic/basic'
2
+ import { Configuration, ConfigurationOptions } from '@platformatic/foundation'
3
+ import { ViteCapability } from '@platformatic/vite'
4
+ import { JSONSchemaType } from 'ajv'
5
+ import type { PlatformaticNitroConfig } from './config.d.ts'
6
+
7
+ export type { PlatformaticNitroConfig } from './config.d.ts'
8
+
9
+ export interface NitroContext extends BaseContext {}
10
+ export type NitroConfiguration = Configuration<PlatformaticNitroConfig>
11
+
12
+ export interface ResolvedNitroPackage {
13
+ name: 'nitro' | 'nitropack'
14
+ root: string
15
+ packageJson: {
16
+ version: string
17
+ [key: string]: unknown
18
+ }
19
+ }
20
+
21
+ export declare function resolveNitroPackage (root: string): Promise<ResolvedNitroPackage>
22
+ export declare function hasViteConfigFile (root: string, config?: PlatformaticNitroConfig): boolean
23
+
24
+ export declare function transform (
25
+ config: NitroConfiguration,
26
+ schema?: object,
27
+ options?: ConfigurationOptions
28
+ ): Promise<NitroConfiguration>
29
+
30
+ export declare function loadConfiguration (
31
+ root: string | PlatformaticNitroConfig,
32
+ source?: string | PlatformaticNitroConfig,
33
+ context?: ConfigurationOptions
34
+ ): Promise<NitroConfiguration>
35
+
36
+ export declare function create (
37
+ configOrRoot: string | PlatformaticNitroConfig,
38
+ sourceOrConfig?: string | PlatformaticNitroConfig,
39
+ context?: ConfigurationOptions
40
+ ): Promise<NitroCapability | NitroViteCapability>
41
+
42
+ export declare class NitroCapability extends BaseCapability<PlatformaticNitroConfig, BaseOptions<NitroContext>> {
43
+ constructor (root: string, config: PlatformaticNitroConfig, context?: object)
44
+ }
45
+
46
+ export declare class NitroViteCapability extends ViteCapability {
47
+ constructor (root: string, config: PlatformaticNitroConfig, context?: object)
48
+ }
49
+
50
+ export declare const packageJson: Record<string, unknown>
51
+ export declare const schema: JSONSchemaType<PlatformaticNitroConfig>
52
+ export declare const schemaComponents: { nitro: JSONSchemaType<object> }
53
+ export declare const version: string
54
+ export declare const supportedVersions: { nitro: string, nitropack: string }
package/index.js ADDED
@@ -0,0 +1,39 @@
1
+ import { resolve, transform as basicTransform, validationOptions } from '@platformatic/basic'
2
+ import { kMetadata, loadConfiguration as utilsLoadConfiguration } from '@platformatic/foundation'
3
+ import { hasViteConfigFile, NitroCapability, NitroViteCapability } from './lib/capability.js'
4
+ import { schema } from './lib/schema.js'
5
+
6
+ /* c8 ignore next 6 */
7
+ export async function transform (config, schema, options) {
8
+ config = await basicTransform(config, schema, options)
9
+
10
+ if (config.application.include === undefined) {
11
+ config.application.include = [config.nitro.outputDirectory ?? config.application.outputDirectory]
12
+ }
13
+
14
+ config.watch = { enabled: false }
15
+ return config
16
+ }
17
+
18
+ export async function loadConfiguration (configOrRoot, sourceOrConfig, context) {
19
+ const { root, source } = await resolve(configOrRoot, sourceOrConfig, 'application')
20
+
21
+ return utilsLoadConfiguration(source, context?.schema ?? schema, {
22
+ validationOptions,
23
+ transform,
24
+ replaceEnv: true,
25
+ root,
26
+ ...context
27
+ })
28
+ }
29
+
30
+ export async function create (configOrRoot, sourceOrConfig, context) {
31
+ const config = await loadConfiguration(configOrRoot, sourceOrConfig, context)
32
+ const root = config[kMetadata].root
33
+ const Capability = hasViteConfigFile(root, config) ? NitroViteCapability : NitroCapability
34
+
35
+ return new Capability(root, config, context)
36
+ }
37
+
38
+ export * from './lib/capability.js'
39
+ export { packageJson, schema, schemaComponents, version } from './lib/schema.js'
@@ -0,0 +1,558 @@
1
+ import {
2
+ BaseCapability,
3
+ buildAdditionalServerOptions,
4
+ cleanBasePath,
5
+ createServerListener,
6
+ ensureTrailingSlash,
7
+ errors,
8
+ getServerUrl,
9
+ importFile,
10
+ injectViaRequest,
11
+ resolvePackageViaCJS
12
+ } from '@platformatic/basic'
13
+ import { hasDependency, sanitizeHTTPSOptions } from '@platformatic/foundation'
14
+ import { ViteCapability } from '@platformatic/vite'
15
+ import inject from 'light-my-request'
16
+ import { existsSync } from 'node:fs'
17
+ import { readFile } from 'node:fs/promises'
18
+ import { dirname, resolve } from 'node:path'
19
+ import { satisfies } from 'semver'
20
+ import { version } from './schema.js'
21
+
22
+ export const supportedVersions = {
23
+ nitro: '>=3.0.0-alpha.0 <4.0.0',
24
+ nitropack: '^2.10.0'
25
+ }
26
+
27
+ const viteConfigFiles = [
28
+ 'vite.config.js',
29
+ 'vite.config.mjs',
30
+ 'vite.config.cjs',
31
+ 'vite.config.ts',
32
+ 'vite.config.mts',
33
+ 'vite.config.cts'
34
+ ]
35
+
36
+ const productionEnvironmentKeys = [
37
+ 'HOST',
38
+ 'NITRO_HOST',
39
+ 'PORT',
40
+ 'NITRO_PORT',
41
+ 'NITRO_SHUTDOWN_DISABLED',
42
+ 'NITRO_SHUTDOWN_NO_FORCE_EXIT',
43
+ 'NITRO_SSL_CERT',
44
+ 'NITRO_SSL_KEY'
45
+ ]
46
+
47
+ export async function resolveNitroPackage (root) {
48
+ let names = ['nitro', 'nitropack']
49
+
50
+ try {
51
+ const applicationPackageJson = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf-8'))
52
+ const declared = names.filter(name => hasDependency(applicationPackageJson, name))
53
+
54
+ if (declared.length > 0) {
55
+ names = declared
56
+ }
57
+ } catch {
58
+ // Package resolution below provides the useful error when package.json is absent or invalid.
59
+ }
60
+
61
+ for (const name of names) {
62
+ let packageJsonPath
63
+
64
+ try {
65
+ packageJsonPath = resolvePackageViaCJS(root, `${name}/package.json`)
66
+ } catch {
67
+ continue
68
+ }
69
+
70
+ const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf-8'))
71
+ return { name, root: dirname(packageJsonPath), packageJson }
72
+ }
73
+
74
+ throw new Error('Cannot find the "nitro" or "nitropack" package. Please add it to the application dependencies.')
75
+ }
76
+
77
+ export function hasViteConfigFile (root, config) {
78
+ const configFile = config?.vite?.configFile
79
+
80
+ if (configFile === false) {
81
+ return false
82
+ }
83
+
84
+ if (typeof configFile === 'string') {
85
+ return existsSync(resolve(root, configFile))
86
+ }
87
+
88
+ return viteConfigFiles.some(file => existsSync(resolve(root, file)))
89
+ }
90
+
91
+ export class NitroCapability extends BaseCapability {
92
+ #nitro
93
+ #basePath
94
+ #server
95
+ #dispatcher
96
+
97
+ constructor (root, config, context) {
98
+ super('nitro', version, root, config, context)
99
+ this.exitOnUnhandledErrors = false
100
+ this.subprocessTerminationSignal = 'SIGKILL'
101
+ }
102
+
103
+ async init () {
104
+ await super.init()
105
+
106
+ if (this.serverConfig?.http2) {
107
+ throw new Error(
108
+ 'Nitro does not support server.http2. Remove it from the application or runtime server configuration.'
109
+ )
110
+ }
111
+
112
+ if (!this.isProduction) {
113
+ this.#nitro = await resolveNitroPackage(this.root)
114
+ const range = supportedVersions[this.#nitro.name]
115
+
116
+ if (!satisfies(this.#nitro.packageJson.version, range, { includePrerelease: true })) {
117
+ throw new errors.UnsupportedVersion(this.#nitro.name, this.#nitro.packageJson.version, range)
118
+ }
119
+ }
120
+
121
+ this.#basePath = this.config.application?.basePath
122
+ ? ensureTrailingSlash(cleanBasePath(this.config.application.basePath))
123
+ : undefined
124
+ this.registerGlobals({ basePath: this.#basePath })
125
+ }
126
+
127
+ async start ({ listen }) {
128
+ /* c8 ignore next 3 */
129
+ if (this.url) {
130
+ return this.url
131
+ }
132
+
133
+ await super._start({ listen })
134
+
135
+ const command = this.config.application.commands[this.isProduction ? 'production' : 'development']
136
+ if (command) {
137
+ if (!this.isProduction) {
138
+ return this.#runWithBasePathEnvironment(() => this.startWithCommand(command))
139
+ }
140
+
141
+ return this.startWithCommand(command)
142
+ }
143
+
144
+ if (this.isProduction) {
145
+ await this.#startProduction()
146
+ } else {
147
+ await this.#startDevelopment()
148
+ }
149
+
150
+ await this._collectMetrics()
151
+ return this.url
152
+ }
153
+
154
+ async stop () {
155
+ await super.stop()
156
+
157
+ if (this.childManager) {
158
+ return this.stopCommand()
159
+ }
160
+
161
+ if (this.#server?.listening) {
162
+ return this._closeServer(this.#server)
163
+ }
164
+ }
165
+
166
+ setClosing () {
167
+ super.setClosing()
168
+
169
+ if (this.runtimeConfig?.gracefulShutdown?.closeConnections !== false) {
170
+ this.#server?.closeHttp2Sessions?.()
171
+ }
172
+ }
173
+
174
+ async build () {
175
+ if (!this.#nitro) {
176
+ await this.init()
177
+ }
178
+
179
+ const config = this.config
180
+ const command = config.application.commands.build ?? [
181
+ process.execPath,
182
+ resolve(this.#nitro.root, 'dist/cli/index.mjs'),
183
+ 'build'
184
+ ]
185
+
186
+ return this.#runWithBasePathEnvironment(() => this.buildWithCommand(command, this.#basePath))
187
+ }
188
+
189
+ async inject (injectParams, onInject) {
190
+ if (!this.isProduction || !this.#dispatcher) {
191
+ return injectViaRequest(this.url, injectParams, onInject)
192
+ }
193
+
194
+ const res = await inject(this.#dispatcher, injectParams, onInject)
195
+
196
+ if (onInject) {
197
+ return
198
+ }
199
+
200
+ const { statusCode, headers, body, payload, rawPayload } = res
201
+ return { statusCode, headers, body, payload, rawPayload }
202
+ }
203
+
204
+ getMeta () {
205
+ const hasBasePath = this.basePath || this.#basePath
206
+
207
+ return {
208
+ gateway: {
209
+ tcp: typeof this.url !== 'undefined',
210
+ url: this.url,
211
+ prefix: this.basePath ?? this.#basePath,
212
+ wantsAbsoluteUrls: !!hasBasePath,
213
+ needsRootTrailingSlash: false
214
+ }
215
+ }
216
+ }
217
+
218
+ /* c8 ignore next 5 */
219
+ async getWatchConfig () {
220
+ return {
221
+ enabled: false
222
+ }
223
+ }
224
+
225
+ async #startDevelopment () {
226
+ let { hostname, port, https } = this.serverConfig ?? {}
227
+ hostname ||= '127.0.0.1'
228
+ port ||= 0
229
+ const command = [
230
+ process.execPath,
231
+ resolve(this.#nitro.root, 'dist/cli/index.mjs'),
232
+ 'dev',
233
+ '--port',
234
+ port.toString(),
235
+ '--host',
236
+ hostname
237
+ ]
238
+
239
+ if (https && this.#nitro.name === 'nitro') {
240
+ throw new Error(
241
+ 'HTTPS is not supported by the Nitro 3 CLI in development mode. Use Nitro as a Vite plugin or a custom development command.'
242
+ )
243
+ }
244
+
245
+ if (https && this.#nitro.name === 'nitropack') {
246
+ command.push('--https')
247
+
248
+ for (const property of ['key', 'cert']) {
249
+ const value = https[property]
250
+ if (
251
+ value !== undefined &&
252
+ (typeof value !== 'object' || Array.isArray(value) || typeof value.path !== 'string')
253
+ ) {
254
+ throw new Error(
255
+ `Nitropack development HTTPS requires server.https.${property} to use a single { path } value; inline strings and arrays are not supported.`
256
+ )
257
+ }
258
+ }
259
+
260
+ if (https.key) {
261
+ command.push('--https.key', resolve(this.root, https.key.path))
262
+ }
263
+ if (https.cert) {
264
+ command.push('--https.cert', resolve(this.root, https.cert.path))
265
+ }
266
+ }
267
+
268
+ await this.#runWithBasePathEnvironment(() => this.startWithCommand(command))
269
+
270
+ if (https && this.#nitro.name === 'nitropack') {
271
+ this.url = this.url.replace(/^http:/, 'https:')
272
+ }
273
+
274
+ return this.url
275
+ }
276
+
277
+ async #startProduction () {
278
+ const outputDirectory = resolve(
279
+ this.root,
280
+ this.config.nitro?.outputDirectory ?? this.config.application.outputDirectory ?? '.output'
281
+ )
282
+ const entrypoint = this.config.nitro?.entrypoint ?? 'server/index.mjs'
283
+ this.verifyOutputDirectory(outputDirectory)
284
+
285
+ const entrypointPath = resolve(outputDirectory, entrypoint)
286
+ if (!existsSync(entrypointPath)) {
287
+ throw new Error(
288
+ `Cannot access Nitro entrypoint '${entrypointPath}'. Please run the 'build' command before running in production mode.`
289
+ )
290
+ }
291
+
292
+ const serverConfig = this.serverConfig
293
+ const host = serverConfig?.hostname ?? '127.0.0.1'
294
+ const port = serverConfig?.port ?? 0
295
+ const originalEnvironment = Object.fromEntries(productionEnvironmentKeys.map(key => [key, process.env[key]]))
296
+ const httpsOptions = await sanitizeHTTPSOptions(serverConfig?.https)
297
+
298
+ process.env.HOST = host
299
+ process.env.NITRO_HOST = host
300
+ process.env.PORT = port.toString()
301
+ process.env.NITRO_PORT = port.toString()
302
+ process.env.NITRO_SHUTDOWN_DISABLED = 'true'
303
+ process.env.NITRO_SHUTDOWN_NO_FORCE_EXIT = 'true'
304
+ delete process.env.NITRO_SSL_CERT
305
+ delete process.env.NITRO_SSL_KEY
306
+
307
+ if (httpsOptions?.cert) {
308
+ process.env.NITRO_SSL_CERT = this.#serializeCertificate(httpsOptions.cert)
309
+ }
310
+ if (httpsOptions?.key) {
311
+ process.env.NITRO_SSL_KEY = this.#serializeCertificate(httpsOptions.key)
312
+ }
313
+
314
+ let serverPromise
315
+
316
+ try {
317
+ serverPromise = createServerListener(
318
+ serverConfig?.port ?? true,
319
+ serverConfig?.hostname ?? true,
320
+ await buildAdditionalServerOptions(serverConfig)
321
+ )
322
+ await importFile(entrypointPath)
323
+ this.#server = await serverPromise
324
+ this.#dispatcher = this.#server.listeners('request')[0]
325
+ this.url = getServerUrl(this.#server)
326
+ return this.url
327
+ } catch (error) {
328
+ serverPromise?.cancel()
329
+ throw error
330
+ } finally {
331
+ this.#restoreEnvironment(originalEnvironment)
332
+ }
333
+ }
334
+
335
+ #serializeCertificate (value) {
336
+ if (Array.isArray(value)) {
337
+ return value.map(item => item.toString()).join('\n')
338
+ }
339
+
340
+ return value.toString()
341
+ }
342
+
343
+ #restoreEnvironment (originalEnvironment) {
344
+ for (const key of productionEnvironmentKeys) {
345
+ if (typeof originalEnvironment[key] === 'undefined') {
346
+ delete process.env[key]
347
+ } else {
348
+ process.env[key] = originalEnvironment[key]
349
+ }
350
+ }
351
+ }
352
+
353
+ async #runWithBasePathEnvironment (fn) {
354
+ const originalValue = process.env.NITRO_APP_BASE_URL
355
+ process.env.NITRO_APP_BASE_URL = this.config.application?.basePath ?? '/'
356
+
357
+ try {
358
+ return await fn()
359
+ } finally {
360
+ if (originalValue === undefined) {
361
+ delete process.env.NITRO_APP_BASE_URL
362
+ } else {
363
+ process.env.NITRO_APP_BASE_URL = originalValue
364
+ }
365
+ }
366
+ }
367
+ }
368
+
369
+ export class NitroViteCapability extends ViteCapability {
370
+ #basePath
371
+ #server
372
+ #dispatcher
373
+
374
+ constructor (root, config, context) {
375
+ super(root, config, context)
376
+ this.type = 'nitro'
377
+ this.version = version
378
+ this.exitOnUnhandledErrors = false
379
+ this.subprocessTerminationSignal = 'SIGKILL'
380
+ }
381
+
382
+ async init () {
383
+ await super.init()
384
+
385
+ if (this.serverConfig?.http2) {
386
+ throw new Error(
387
+ 'Nitro does not support server.http2. Remove it from the application or runtime server configuration.'
388
+ )
389
+ }
390
+
391
+ if (!this.isProduction) {
392
+ const nitro = await resolveNitroPackage(this.root)
393
+ const range = supportedVersions[nitro.name]
394
+
395
+ if (!satisfies(nitro.packageJson.version, range, { includePrerelease: true })) {
396
+ throw new errors.UnsupportedVersion(nitro.name, nitro.packageJson.version, range)
397
+ }
398
+ }
399
+
400
+ this.#basePath = this.config.application?.basePath
401
+ ? ensureTrailingSlash(cleanBasePath(this.config.application.basePath))
402
+ : undefined
403
+ this.registerGlobals({ basePath: this.#basePath })
404
+ }
405
+
406
+ async stop () {
407
+ const commandWasRunning = !!this.childManager
408
+ await super.stop()
409
+
410
+ if (!commandWasRunning && this.isProduction && this.#server?.listening) {
411
+ return this._closeServer(this.#server)
412
+ }
413
+ }
414
+
415
+ setClosing () {
416
+ super.setClosing()
417
+
418
+ if (this.isProduction && this.runtimeConfig?.gracefulShutdown?.closeConnections !== false) {
419
+ this.#server?.closeHttp2Sessions?.()
420
+ }
421
+ }
422
+
423
+ async build () {
424
+ const command = this.config.application.commands.build
425
+ if (command) {
426
+ return this.buildWithCommand(command)
427
+ }
428
+
429
+ const outputDirectory = resolve(
430
+ this.root,
431
+ this.config.nitro?.outputDirectory ?? this.config.application.outputDirectory ?? '.output'
432
+ )
433
+ this.buildInfoPath = resolve(outputDirectory, '.platformatic-build.json')
434
+ return super.build()
435
+ }
436
+
437
+ async inject (injectParams, onInject) {
438
+ if (!this.isProduction || !this.#dispatcher) {
439
+ return injectViaRequest(this.url, injectParams, onInject)
440
+ }
441
+
442
+ const res = await inject(this.#dispatcher, injectParams, onInject)
443
+ if (onInject) {
444
+ return
445
+ }
446
+
447
+ const { statusCode, headers, body, payload, rawPayload } = res
448
+ return { statusCode, headers, body, payload, rawPayload }
449
+ }
450
+
451
+ async getChildManagerContext (basePath) {
452
+ const context = await super.getChildManagerContext(basePath)
453
+ context.exitOnUnhandledErrors = false
454
+ return context
455
+ }
456
+
457
+ getMeta () {
458
+ if (!this.isProduction) {
459
+ return super.getMeta()
460
+ }
461
+
462
+ const hasBasePath = this.basePath || this.#basePath
463
+
464
+ return {
465
+ gateway: {
466
+ tcp: typeof this.url !== 'undefined',
467
+ url: this.url,
468
+ prefix: this.basePath ?? this.#basePath,
469
+ wantsAbsoluteUrls: !!hasBasePath,
470
+ needsRootTrailingSlash: false
471
+ }
472
+ }
473
+ }
474
+
475
+ async _startProduction () {
476
+ const command = this.config.application.commands.production
477
+ if (command) {
478
+ return this.startWithCommand(command)
479
+ }
480
+
481
+ const outputDirectory = resolve(
482
+ this.root,
483
+ this.config.nitro?.outputDirectory ?? this.config.application.outputDirectory ?? '.output'
484
+ )
485
+ const entrypoint = this.config.nitro?.entrypoint ?? 'server/index.mjs'
486
+ this.verifyOutputDirectory(outputDirectory)
487
+
488
+ this.buildInfoPath = resolve(outputDirectory, '.platformatic-build.json')
489
+ this.#basePath = await this._getBasePathFromBuildInfo()
490
+
491
+ const entrypointPath = resolve(outputDirectory, entrypoint)
492
+ if (!existsSync(entrypointPath)) {
493
+ throw new Error(
494
+ `Cannot access Nitro entrypoint '${entrypointPath}'. Please run the 'build' command before running in production mode.`
495
+ )
496
+ }
497
+
498
+ const serverConfig = this.serverConfig
499
+ const host = serverConfig?.hostname ?? '127.0.0.1'
500
+ const port = serverConfig?.port ?? 0
501
+ const originalEnvironment = Object.fromEntries(productionEnvironmentKeys.map(key => [key, process.env[key]]))
502
+ const httpsOptions = await sanitizeHTTPSOptions(serverConfig?.https)
503
+
504
+ process.env.HOST = host
505
+ process.env.NITRO_HOST = host
506
+ process.env.PORT = port.toString()
507
+ process.env.NITRO_PORT = port.toString()
508
+ process.env.NITRO_SHUTDOWN_DISABLED = 'true'
509
+ process.env.NITRO_SHUTDOWN_NO_FORCE_EXIT = 'true'
510
+ delete process.env.NITRO_SSL_CERT
511
+ delete process.env.NITRO_SSL_KEY
512
+
513
+ if (httpsOptions?.cert) {
514
+ process.env.NITRO_SSL_CERT = this.#serializeCertificate(httpsOptions.cert)
515
+ }
516
+ if (httpsOptions?.key) {
517
+ process.env.NITRO_SSL_KEY = this.#serializeCertificate(httpsOptions.key)
518
+ }
519
+
520
+ let serverPromise
521
+
522
+ try {
523
+ serverPromise = createServerListener(
524
+ serverConfig?.port ?? true,
525
+ serverConfig?.hostname ?? true,
526
+ await buildAdditionalServerOptions(serverConfig)
527
+ )
528
+ await importFile(entrypointPath)
529
+ this.#server = await serverPromise
530
+ this.#dispatcher = this.#server.listeners('request')[0]
531
+ this.url = getServerUrl(this.#server)
532
+ return this.url
533
+ } catch (error) {
534
+ serverPromise?.cancel()
535
+ throw error
536
+ } finally {
537
+ this.#restoreEnvironment(originalEnvironment)
538
+ }
539
+ }
540
+
541
+ #serializeCertificate (value) {
542
+ if (Array.isArray(value)) {
543
+ return value.map(item => item.toString()).join('\n')
544
+ }
545
+
546
+ return value.toString()
547
+ }
548
+
549
+ #restoreEnvironment (originalEnvironment) {
550
+ for (const key of productionEnvironmentKeys) {
551
+ if (typeof originalEnvironment[key] === 'undefined') {
552
+ delete process.env[key]
553
+ } else {
554
+ process.env[key] = originalEnvironment[key]
555
+ }
556
+ }
557
+ }
558
+ }