pockethost 1.7.0 → 3.0.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +119 -86
  2. package/README.md +96 -0
  3. package/dist/cli.js +21542 -0
  4. package/package.json +55 -55
  5. package/changesetx.ts +0 -110
  6. package/common.ts +0 -1
  7. package/core.ts +0 -1
  8. package/readme.md +0 -129
  9. package/src/cli/commands/ConfigCommand/index.ts +0 -28
  10. package/src/cli/commands/PluginCommand/index.ts +0 -113
  11. package/src/cli/commands/PluginCommand/plugin-template/package.json +0 -38
  12. package/src/cli/commands/PluginCommand/plugin-template/readme.md +0 -33
  13. package/src/cli/commands/PluginCommand/plugin-template/src/constants.ts +0 -22
  14. package/src/cli/commands/PluginCommand/plugin-template/src/db.ts +0 -30
  15. package/src/cli/commands/PluginCommand/plugin-template/src/index.ts +0 -3
  16. package/src/cli/commands/PluginCommand/plugin-template/src/log.ts +0 -5
  17. package/src/cli/commands/PluginCommand/plugin-template/src/plugin.ts +0 -58
  18. package/src/cli/commands/PluginCommand/util.ts +0 -140
  19. package/src/cli/commands/ServeCommand/index.ts +0 -36
  20. package/src/cli/index.ts +0 -70
  21. package/src/common/CleanupManager.ts +0 -65
  22. package/src/common/Logger.ts +0 -174
  23. package/src/common/ResourceAllocator.ts +0 -49
  24. package/src/common/TimerManager.ts +0 -64
  25. package/src/common/assert.ts +0 -26
  26. package/src/common/debug.ts +0 -8
  27. package/src/common/error.ts +0 -16
  28. package/src/common/events.ts +0 -53
  29. package/src/common/index.ts +0 -12
  30. package/src/common/mergeConfig.ts +0 -27
  31. package/src/common/mkSingleton.ts +0 -28
  32. package/src/common/plugin/action.ts +0 -164
  33. package/src/common/plugin/filter.ts +0 -197
  34. package/src/common/plugin/index.ts +0 -21
  35. package/src/common/promiseSerializer.ts +0 -22
  36. package/src/common/schema/BaseFields.ts +0 -10
  37. package/src/common/schema/Instance.ts +0 -46
  38. package/src/common/schema/InstanceLog.ts +0 -12
  39. package/src/common/schema/index.ts +0 -3
  40. package/src/common/schema/util.ts +0 -7
  41. package/src/constants.ts +0 -70
  42. package/src/core/Settings.ts +0 -119
  43. package/src/core/asyncExecutionGuard.ts +0 -49
  44. package/src/core/config.ts +0 -108
  45. package/src/core/exit.ts +0 -11
  46. package/src/core/index.ts +0 -8
  47. package/src/core/internal.ts +0 -3
  48. package/src/core/smartFetch.ts +0 -32
  49. package/src/core/tryFetch.ts +0 -69
  50. package/src/plugin.ts +0 -54
  51. package/src/server.ts +0 -129
  52. /package/{src/cli/commands/PluginCommand/plugin-template/LICENSE.md → LICENSE.md} +0 -0
@@ -1,53 +0,0 @@
1
- import { values } from '@s-libs/micro-dash'
2
-
3
- export type Unsubscribe = () => void
4
-
5
- export type EventSubscriber<TPayload> = (
6
- cb: EventHandler<TPayload>,
7
- ) => Unsubscribe
8
- export type EventEmitter<TPayload> = (
9
- payload: TPayload,
10
- stopOnHandled?: boolean,
11
- ) => Promise<boolean>
12
- export type EventHandler<TPayload> = (
13
- payload: TPayload,
14
- isHandled: boolean,
15
- ) => boolean | void | Promise<boolean | void>
16
-
17
- /**
18
- * @param defaultHandler Optional handler to call if no handler calls
19
- * `handled()`
20
- * @returns Void
21
- */
22
- export const createEvent = <TPayload>(
23
- defaultHandler?: EventHandler<TPayload>,
24
- ): [EventSubscriber<TPayload>, EventEmitter<TPayload>] => {
25
- let i = 0
26
- const callbacks: any = {}
27
- let callbacksArray: EventHandler<TPayload>[] = []
28
- const onEvent = (cb: EventHandler<TPayload>) => {
29
- const id = i++
30
- callbacks[id] = cb
31
- callbacksArray = values(callbacks)
32
- return () => {
33
- delete callbacks[id]
34
- }
35
- }
36
-
37
- const fireEvent = async (payload: TPayload, stopOnHandled = false) => {
38
- let _handled = false
39
- for (let i = 0; i < callbacksArray.length; i++) {
40
- const cb = callbacksArray[i]
41
- if (!cb) continue
42
- const res: boolean = !!(await cb(payload, _handled))
43
- _handled = _handled || res
44
- if (stopOnHandled && _handled) break
45
- }
46
- if (!_handled) {
47
- await defaultHandler?.(payload, false)
48
- }
49
- return _handled
50
- }
51
-
52
- return [onEvent, fireEvent]
53
- }
@@ -1,12 +0,0 @@
1
- export * from './CleanupManager'
2
- export * from './Logger'
3
- export * from './TimerManager'
4
- export * from './assert'
5
- export * from './debug'
6
- export * from './error'
7
- export * from './events'
8
- export * from './mergeConfig'
9
- export * from './mkSingleton'
10
- export * from './plugin'
11
- export * from './promiseSerializer'
12
- export * from './schema'
@@ -1,27 +0,0 @@
1
- /**
2
- * Merges a config object with defaults. Shallow copies root descendants,
3
- * skipping`undefined` values.
4
- *
5
- * @param defaultConfig The default config values
6
- * @param partialConfigs A partial config to merge with defaults
7
- * @returns
8
- */
9
- export function mergeConfig<T>(
10
- defaultConfig: T,
11
- ...partialConfigs: Partial<T>[]
12
- ): T {
13
- const result: T = { ...defaultConfig }
14
-
15
- for (const partialConfig of partialConfigs) {
16
- for (const key in partialConfig) {
17
- if (Object.prototype.hasOwnProperty.call(partialConfig, key)) {
18
- const value = partialConfig[key as keyof typeof partialConfig]
19
- if (value !== undefined) {
20
- result[key as keyof T] = value as T[keyof T]
21
- }
22
- }
23
- }
24
- }
25
-
26
- return result
27
- }
@@ -1,28 +0,0 @@
1
- export type SingletonApi = Object
2
-
3
- export type SingletonBaseConfig = {}
4
-
5
- export function mkSingleton<TConfig, TInstance>(
6
- factory: (config: TConfig) => TInstance,
7
- ): (config?: TConfig) => TInstance {
8
- let instance: TInstance | undefined
9
-
10
- return (config?: TConfig): TInstance => {
11
- if (instance && config) {
12
- console.warn('Attempted to initialize service twice.')
13
- console.warn(new Error().stack)
14
- return instance
15
- }
16
-
17
- if (!instance && !config) {
18
- console.warn(new Error().stack)
19
- throw new Error('Attempted to use service before initialization.')
20
- }
21
-
22
- if (!instance) {
23
- instance = factory(config as TConfig)
24
- }
25
-
26
- return instance
27
- }
28
- }
@@ -1,164 +0,0 @@
1
- import { uniqueId } from '@s-libs/micro-dash'
2
- import { Express, Request, Response } from 'express'
3
- import { dbg } from '../../cli'
4
- import { LogLevelName } from '../Logger'
5
- import { DEBUG } from '../debug'
6
- import { InstanceFields } from '../schema'
7
-
8
- enum CoreActions {
9
- AfterPluginsLoaded = 'core_after_plugins_loaded',
10
- Init = 'core_init',
11
- Serve = 'core_serve',
12
- AppMounted = 'core_on_app_mount',
13
- AfterServeStart = 'core_after_serve_start',
14
-
15
- Cli_Before_ServeCommand = 'core_before_serve',
16
- Log = 'core_log',
17
- InstanceLog = 'core_instance_log',
18
-
19
- StartInstance = 'core_start_instance',
20
-
21
- BeforeInstanceStarted = 'core_before_instance_started',
22
- AfterInstanceStarted = 'core_after_instance_started',
23
-
24
- KillInstance = 'core_kill_instance',
25
-
26
- BeforeInstanceStopped = 'core_before_instance_stopped',
27
- AfterInstanceStopped = 'core_after_instance_stopped',
28
-
29
- AfterInstanceFound = 'core_after_instance_found',
30
-
31
- RequestError = 'core_edge_on_request_error',
32
- Request = 'core_edge_request',
33
- }
34
-
35
- export type ActionHandler<TContext = {}> = (
36
- context: TContext extends never ? [] : TContext,
37
- ) => Promise<void>
38
-
39
- interface Action {
40
- priority: number
41
- handler: ActionHandler<any>
42
- }
43
-
44
- const actions: {
45
- [key: string]: Action[]
46
- } = {}
47
-
48
- function registerAction(
49
- action: string,
50
- handler: (...args: any[]) => Promise<void>,
51
- priority: number = 10,
52
- ): () => void {
53
- if (!(action in actions)) actions[action] = []
54
- const uid = uniqueId(`a:${action}:`)
55
- dbg(`${uid}:subscribe`)
56
- actions[action]!.push({ priority, handler })
57
- actions[action]!.sort((a, b) => a.priority - b.priority)
58
-
59
- return () => {
60
- dbg(`${uid}:unsubscribe`)
61
- actions[action] = actions[action]!.filter((a) => a.handler !== handler)
62
- }
63
- }
64
-
65
- async function action(actionName: string, context: any) {
66
- if (DEBUG() && actionName !== CoreActions.Log) {
67
- console.log(`a:${actionName}`)
68
- }
69
- const action = actions[actionName]
70
- if (!action) return false
71
- for (const { handler } of action) {
72
- await handler(context)
73
- }
74
- return true
75
- }
76
-
77
- export function createCustomActionWithContext<TContext extends {}>(
78
- actionName: CoreActions,
79
- ) {
80
- return [
81
- async (context: TContext) => action(actionName, context),
82
- (handler: ActionHandler<TContext>, priority = 10) =>
83
- registerAction(actionName, handler, priority),
84
- ] as const
85
- }
86
-
87
- export function createCustomAction(actionName: CoreActions) {
88
- return [
89
- async () => action(actionName, {}),
90
- (handler: ActionHandler, priority = 10) =>
91
- registerAction(actionName, handler, priority),
92
- ] as const
93
- }
94
-
95
- export const [doAfterPluginsLoadedAction, onAfterPluginsLoadedAction] =
96
- createCustomAction(CoreActions.AfterPluginsLoaded)
97
-
98
- export const [doRequestErrorAction, onRequestErrorAction] =
99
- createCustomActionWithContext<{
100
- err: Error
101
- }>(CoreActions.RequestError)
102
-
103
- export const [doAfterServerStartAction, onAfterServerStartAction] =
104
- createCustomAction(CoreActions.AfterServeStart)
105
-
106
- export const [doLogAction, onLogAction] = createCustomActionWithContext<{
107
- currentLevel: LogLevelName
108
- levelIn: LogLevelName
109
- args: any[]
110
- }>(CoreActions.Log)
111
-
112
- export const [doInstanceLogAction, onInstanceLogAction] =
113
- createCustomActionWithContext<{
114
- instance: InstanceFields
115
- type: 'stdout' | 'stderr'
116
- data: string
117
- }>(CoreActions.InstanceLog)
118
-
119
- export const [doAppMountedAction, onAppMountedAction] =
120
- createCustomActionWithContext<{ app: Express; internalApp: Express }>(
121
- CoreActions.AppMounted,
122
- )
123
-
124
- export const [doIncomingRequestAction, onIncomingRequestAction] =
125
- createCustomActionWithContext<{ req: Request; res: Response; host: string }>(
126
- CoreActions.Request,
127
- )
128
-
129
- export const [doAfterInstanceFoundAction, onAfterInstanceFoundAction] =
130
- createCustomActionWithContext<{
131
- req: Request
132
- res: Response
133
- host: string
134
- instance: InstanceFields
135
- }>(CoreActions.AfterInstanceFound)
136
-
137
- export const [doBeforeInstanceStartedAction, onBeforeInstanceStartedAction] =
138
- createCustomActionWithContext<{ instance: InstanceFields }>(
139
- CoreActions.BeforeInstanceStarted,
140
- )
141
-
142
- export const [doAfterInstanceStartedAction, onAfterInstanceStartedAction] =
143
- createCustomActionWithContext<{ instance: InstanceFields; url: string }>(
144
- CoreActions.AfterInstanceStarted,
145
- )
146
-
147
- export const [doKillInstanceAction, onKillInstanceAction] =
148
- createCustomActionWithContext<{ instance: InstanceFields }>(
149
- CoreActions.KillInstance,
150
- )
151
-
152
- export const [doBeforeInstanceStoppedAction, onBeforeInstanceStoppedAction] =
153
- createCustomActionWithContext<{ instance: InstanceFields; url: string }>(
154
- CoreActions.BeforeInstanceStopped,
155
- )
156
-
157
- export const [doAfterInstanceStoppedAction, onAfterInstanceStoppedAction] =
158
- createCustomActionWithContext<{ instance: InstanceFields; url: string }>(
159
- CoreActions.AfterInstanceStopped,
160
- )
161
-
162
- export const [doServeAction, onServeAction] = createCustomActionWithContext<{
163
- only: string[]
164
- }>(CoreActions.Serve)
@@ -1,197 +0,0 @@
1
- import { Command } from 'commander'
2
- import { Request, Response } from 'express'
3
- import { DEBUG } from '../debug'
4
- import { InstanceFields, InstanceId } from '../schema'
5
- import { UserId } from '../schema/BaseFields'
6
-
7
- export enum CoreFilters {
8
- Settings = 'core_settings',
9
- CliCommands = 'core_cli_commands',
10
- ServeSlugs = 'core_serve_slugs',
11
- SpawnConfig = 'core_spawn_config',
12
- AuthenticateUser = 'core_authenticate_user',
13
- GetInstanceByRequestInfo = 'core_get_instance_by_request_info',
14
- GetInstanceById = 'core_get_instance_by_id',
15
- GetOneInstanceByExactCriteria = 'core_get_one_instance_by_exact_criteria',
16
- GetAllInstancesByExactCriteria = 'core_get_all_instances_by_exact_criteria',
17
- InstanceConfig = 'core_instance_config',
18
- ErrorSpawningInstanceMessage = 'core_error_spawning_instance_message',
19
- FailedToLaunchInstanceMessage = 'core_failed_to_launch_instance_message',
20
- AuthenticateRequest = 'core_authenticate_request',
21
- RequestError_Message = 'core_request_error_message',
22
- GetOrProvisionInstanceUrl = 'core_get_or_provision_instance_url',
23
- PocketBaseLaunchHandler = 'core_pocket_base_launch_handler',
24
- NewInstanceRecord = 'core_new_instance_record',
25
- IsInstanceRunning = 'core_is_instance_running',
26
- }
27
-
28
- export type FilterHandler<TCarry, TContext> = (
29
- carry: TCarry,
30
- context: TContext,
31
- ) => TCarry | Promise<TCarry>
32
- type FilterEntry<T> = {
33
- priority: number
34
- handler: FilterHandler<T, any>
35
- }
36
- const filters: {
37
- [key: string]: FilterEntry<any>[]
38
- } = {}
39
-
40
- function registerFilter<TCarry, TContext extends {} = {}>(
41
- filter: string,
42
- handler: FilterHandler<TCarry, TContext>,
43
- priority = 10,
44
- ): () => void {
45
- if (!(filter in filters)) filters[filter] = []
46
- filters[filter]!.push({ priority, handler })
47
- filters[filter]!.sort((a, b) => a.priority - b.priority)
48
-
49
- return () => {
50
- const index = filters[filter]!.findIndex(
51
- (entry) => entry.handler === handler,
52
- )
53
- if (index !== -1) {
54
- filters[filter]!.splice(index, 1)
55
- }
56
- }
57
- }
58
-
59
- async function filter<TCarry, TContext extends {} = {}>(
60
- filterName: string,
61
- initialValue: TCarry,
62
- context: TContext,
63
- ) {
64
- if (DEBUG()) {
65
- console.log(`f:${filterName}`)
66
- }
67
- const filter = filters[filterName]
68
- if (!filter) return initialValue
69
- return filter.reduce(
70
- (carry, entry) =>
71
- carry
72
- .then((carryRes) => entry.handler(carryRes, context))
73
- .then((carryRes) => {
74
- if (DEBUG()) {
75
- console.log(`f:${filterName}`, carryRes, context)
76
- }
77
- return carryRes
78
- }),
79
- Promise.resolve(initialValue),
80
- ) as TCarry
81
- }
82
-
83
- function createCustomFilterWithContext<TCarry, TContext extends {} = {}>(
84
- filterName: CoreFilters,
85
- ) {
86
- return [
87
- async (initialValue: TCarry, context: TContext) =>
88
- filter<TCarry, TContext>(filterName, initialValue, context),
89
- async <TExtraCarry = unknown>(
90
- handler: FilterHandler<TCarry & TExtraCarry, TContext>,
91
- priority = 10,
92
- ) =>
93
- registerFilter<TCarry & TExtraCarry, TContext>(
94
- filterName,
95
- handler,
96
- priority,
97
- ),
98
- ] as const
99
- }
100
-
101
- function createCustomFilter<TCarry>(filterName: string) {
102
- return [
103
- async (initialValue: TCarry) =>
104
- filter<TCarry>(filterName, initialValue, {}),
105
- async <TExtraCarry = unknown>(
106
- handler: FilterHandler<TCarry & TExtraCarry, {}>,
107
- priority = 10,
108
- ) =>
109
- registerFilter<TCarry & TExtraCarry, {}>(filterName, handler, priority),
110
- ] as const
111
- }
112
-
113
- export const [doSettingsFilter, onSettingsFilter] = createCustomFilter<{
114
- [_: string]: any
115
- }>(CoreFilters.Settings)
116
-
117
- export const [doAuthenticateUserFilter, onAuthenticateUserFilter] =
118
- createCustomFilterWithContext<
119
- UserId | undefined,
120
- { username: string; password: string }
121
- >(CoreFilters.AuthenticateUser)
122
-
123
- export const [
124
- doGetInstanceByRequestInfoFilter,
125
- onGetInstanceByRequestInfoFilter,
126
- ] = createCustomFilterWithContext<
127
- InstanceFields | undefined,
128
- { req: Request; res: Response; host: string; subdomain: string }
129
- >(CoreFilters.GetInstanceByRequestInfo)
130
-
131
- export const [doGetInstanceByIdFilter, onGetInstanceByIdFilter] =
132
- createCustomFilterWithContext<
133
- InstanceFields | undefined,
134
- { instanceId: InstanceId }
135
- >(CoreFilters.GetInstanceById)
136
-
137
- export const [
138
- doGetOneInstanceByExactCriteriaFilter,
139
- onGetOneInstanceByExactCriteriaFilter,
140
- ] = createCustomFilterWithContext<
141
- InstanceFields | undefined,
142
- Partial<InstanceFields & { [_: string]: string | number }>
143
- >(CoreFilters.GetOneInstanceByExactCriteria)
144
-
145
- export const [
146
- doGetAllInstancesByExactCriteriaFilter,
147
- onGetAllInstancesByExactCriteriaFilter,
148
- ] = createCustomFilterWithContext<
149
- InstanceFields[],
150
- Partial<InstanceFields & { [_: string]: string | number }>
151
- >(CoreFilters.GetAllInstancesByExactCriteria)
152
-
153
- export const [doCliCommandsFilter, onCliCommandsFilter] = createCustomFilter<
154
- Command[]
155
- >(CoreFilters.CliCommands)
156
-
157
- export const [doNewInstanceRecordFilter, onNewInstanceRecordFilter] =
158
- createCustomFilter<InstanceFields>(CoreFilters.NewInstanceRecord)
159
-
160
- export const [doRequestErrorMessageFilter, onRequestErrorMessageFilter] =
161
- createCustomFilter<string>(CoreFilters.RequestError_Message)
162
-
163
- export const [
164
- doGetOrProvisionInstanceUrlFilter,
165
- onGetOrProvisionInstanceUrlFilter,
166
- ] = createCustomFilterWithContext<
167
- string | undefined,
168
- {
169
- instance: InstanceFields
170
- }
171
- >(CoreFilters.GetOrProvisionInstanceUrl)
172
-
173
- export const [doServeSlugsFilter, onServeSlugsFilter] = createCustomFilter<
174
- string[]
175
- >(CoreFilters.ServeSlugs)
176
-
177
- export type Bind = {
178
- base: string
179
- src: string
180
- }
181
- export type Binds = {
182
- data: Bind[]
183
- hooks: Bind[]
184
- migrations: Bind[]
185
- public: Bind[]
186
- }
187
- export type InstanceConfig = {
188
- binds: Binds
189
- env: { [_: string]: string }
190
- }
191
- export const [doInstanceConfigFilter, onInstanceConfigFilter] =
192
- createCustomFilter<InstanceConfig>(CoreFilters.InstanceConfig)
193
-
194
- export const [doIsInstanceRunningFilter, onIsInstanceRunningFilter] =
195
- createCustomFilterWithContext<boolean, { instance: InstanceFields }>(
196
- CoreFilters.IsInstanceRunning,
197
- )
@@ -1,21 +0,0 @@
1
- import { isString } from '@s-libs/micro-dash'
2
- export * from './action'
3
- export * from './filter'
4
-
5
- export type PocketHostPlugin = (api: PocketHostPluginApi) => Promise<void>
6
-
7
- export type PocketHostPluginApi = {}
8
-
9
- export const loadPlugins = async (plugins: (string | PocketHostPlugin)[]) => {
10
- await Promise.all(
11
- plugins.map(async (pluginPathOrModule) => {
12
- const plugin = await (async () => {
13
- if (!isString(pluginPathOrModule)) return pluginPathOrModule
14
- const plugin = await import(pluginPathOrModule)
15
- return plugin.default
16
- })()
17
- await plugin({})
18
- }),
19
- )
20
- return plugins
21
- }
@@ -1,22 +0,0 @@
1
- type JobQueue = {
2
- [key: string]: Promise<any> | undefined
3
- }
4
-
5
- const jobQueue: JobQueue = {}
6
-
7
- export function enqueueJob(
8
- key: string,
9
- promiseFn: () => Promise<any>,
10
- ): Promise<any> {
11
- const currentJob = jobQueue[key]
12
-
13
- const chainedPromise = currentJob ? currentJob.then(promiseFn) : promiseFn()
14
-
15
- jobQueue[key] = chainedPromise.finally(() => {
16
- if (jobQueue[key] === chainedPromise) {
17
- delete jobQueue[key]
18
- }
19
- })
20
-
21
- return chainedPromise
22
- }
@@ -1,10 +0,0 @@
1
- export type RecordId = string
2
- export type UserId = RecordId
3
- export type IsoDate = string
4
- export type BaseFields = {
5
- id: RecordId
6
- created: IsoDate
7
- updated: IsoDate
8
- }
9
-
10
- export type AnyField = { [_: string]: string | number }
@@ -1,46 +0,0 @@
1
- import { doNewInstanceRecordFilter } from '../plugin'
2
- import { IsoDate } from './BaseFields'
3
- import { newId, pocketNow } from './util'
4
-
5
- export type VersionId = string
6
-
7
- export const INSTANCE_COLLECTION = 'instances'
8
-
9
- export enum InstanceStatus {
10
- Unknown = '',
11
- Idle = 'idle',
12
- Port = 'porting',
13
- Starting = 'starting',
14
- Running = 'running',
15
- Failed = 'failed',
16
- }
17
-
18
- export type InstanceId = string
19
- export type InstanceSecretKey = string
20
- export type InstanceSecretValue = string
21
- export type InstanceSecretCollection = {
22
- [name: InstanceSecretKey]: InstanceSecretValue
23
- }
24
-
25
- export type InstanceFields = {
26
- id: string
27
- subdomain: string
28
- version: VersionId
29
- secrets: InstanceSecretCollection
30
- dev: boolean // Should instance run in --dev mode
31
- created: IsoDate
32
- updated: IsoDate
33
- }
34
-
35
- export const mkInstance = (subdomain: string, id = newId()) => {
36
- const now = pocketNow()
37
- return doNewInstanceRecordFilter({
38
- id,
39
- subdomain,
40
- version: '*',
41
- secrets: {},
42
- dev: false,
43
- created: now,
44
- updated: now,
45
- })
46
- }
@@ -1,12 +0,0 @@
1
- export enum StreamNames {
2
- StdOut = 'stdout',
3
- StdErr = 'stderr',
4
- }
5
-
6
- export type InstanceLogFields = {
7
- message: string
8
- time: string
9
- stream: StreamNames
10
- }
11
-
12
- export type InstanceLogFields_Create = InstanceLogFields
@@ -1,3 +0,0 @@
1
- export * from './Instance'
2
- export * from './InstanceLog'
3
- export * from './util'
@@ -1,7 +0,0 @@
1
- import { customAlphabet } from 'nanoid'
2
- import { IsoDate } from './BaseFields'
3
-
4
- export const newId = customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 10)
5
- export const pocketNow = () => toPocketDate(new Date())
6
- export const toPocketDate = (date: Date) => date.toISOString()
7
- export const fromPocketDate = (iso: IsoDate) => new Date(iso)
package/src/constants.ts DELETED
@@ -1,70 +0,0 @@
1
- import { config } from 'dotenv'
2
- import envPaths from 'env-paths'
3
- import { dirname, join } from 'path'
4
- import { cwd } from 'process'
5
- import { fileURLToPath } from 'url'
6
- import { mkBoolean, mkCsvString, mkNumber, mkPath, mkString } from '../core'
7
- import { InstanceFields, InstanceId } from './common'
8
- import { DEBUG, IS_DEV } from './common/debug'
9
- import { Settings } from './core/Settings'
10
-
11
- const __dirname = dirname(fileURLToPath(import.meta.url))
12
-
13
- export const _PH_HOME = process.env.PH_HOME || envPaths(`pockethost`).data
14
-
15
- config({ path: [join(_PH_HOME, '.env'), join(cwd(), `.env`)] })
16
-
17
- export const _PH_PROJECT_DIR = join(__dirname, '..')
18
- export const _APEX_DOMAIN = process.env.APEX_DOMAIN || 'pockethost.lvh.me'
19
-
20
- export const settings = Settings({
21
- PH_PLUGINS: mkCsvString([
22
- `@pockethost/plugin-console-logger`,
23
- `@pockethost/plugin-launcher-spawn`,
24
- `@pockethost/plugin-auto-admin`,
25
- ]),
26
-
27
- PH_HOME: mkPath(_PH_HOME),
28
- PH_PROJECT_DIR: mkPath(_PH_PROJECT_DIR),
29
-
30
- PH_INTERNAL_HOST: mkString('localhost'),
31
- PH_APEX_DOMAIN: mkString(_APEX_DOMAIN),
32
-
33
- PH_PORT: mkNumber(3000),
34
-
35
- PH_DATA_DIR: mkPath(join(_PH_HOME, 'data'), { create: true }),
36
- PH_DEV: mkBoolean(IS_DEV()),
37
- PH_DEBUG: mkBoolean(DEBUG()),
38
- PH_INTERNAL_APP_SECRET: mkString(''),
39
- })
40
-
41
- /** Accessors */
42
- export const PH_PLUGINS = () => settings.PH_PLUGINS
43
-
44
- export const PH_HOME = (...paths: string[]) => join(settings.PH_HOME, ...paths)
45
- export const PH_PROJECT_DIR = (...paths: string[]) =>
46
- join(settings.PH_PROJECT_DIR, ...paths)
47
-
48
- export const APEX_DOMAIN = () => settings.PH_APEX_DOMAIN
49
-
50
- export const PORT = () => settings.PH_PORT
51
-
52
- export const DATA_DIR = (...paths: string[]) =>
53
- join(settings.PH_DATA_DIR, ...paths)
54
- export const NODE_ENV = () => process.env.NODE_ENV
55
- export const INSTANCE_DATA_DIR = (id: InstanceId, ...paths: string[]) =>
56
- join(DATA_DIR(), id, ...paths)
57
- export const INTERNAL_HOST = () => settings.PH_INTERNAL_HOST
58
- export const INTERNAL_APP_SECRET = () => settings.PH_INTERNAL_APP_SECRET
59
- export const INTERNAL_APP_URL = (...paths: string[]) =>
60
- `${HTTP_PROTOCOL()}//${INTERNAL_HOST()}:${PORT()}/${INTERNAL_APP_PREFIX}/${join(
61
- ...paths,
62
- )}`
63
- export const INTERNAL_APP_PREFIX = `_internal`
64
- export const INTERNAL_APP_AUTH_HEADER = `x-pockethost-authorization`
65
- export const HTTP_PROTOCOL = () => (PORT() === 443 ? 'https:' : 'http:')
66
- export const PUBLIC_INSTANCE_URL = ({ subdomain }: Partial<InstanceFields>) => {
67
- const url = new URL(`${HTTP_PROTOCOL()}//${subdomain}.${APEX_DOMAIN()}`)
68
- url.port = `${PORT() === 80 || PORT() == 443 ? '' : PORT()}`
69
- return url
70
- }