@ms-cloudpack/api-server 0.42.1 → 0.44.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 (81) hide show
  1. package/lib/apis/addPackageOverride.js +1 -1
  2. package/lib/apis/addPackageOverride.js.map +1 -1
  3. package/lib/apis/index.d.ts +2 -0
  4. package/lib/apis/index.d.ts.map +1 -1
  5. package/lib/apis/index.js +2 -0
  6. package/lib/apis/index.js.map +1 -1
  7. package/lib/apis/openCodeEditor.d.ts +4 -4
  8. package/lib/apis/restartAllTasks.d.ts +19 -0
  9. package/lib/apis/restartAllTasks.d.ts.map +1 -0
  10. package/lib/apis/restartAllTasks.js +19 -0
  11. package/lib/apis/restartAllTasks.js.map +1 -0
  12. package/lib/apis/restartTask.d.ts +38 -0
  13. package/lib/apis/restartTask.d.ts.map +1 -0
  14. package/lib/apis/restartTask.js +19 -0
  15. package/lib/apis/restartTask.js.map +1 -0
  16. package/lib/common/createPartialApiContext.d.ts.map +1 -1
  17. package/lib/common/createPartialApiContext.js +5 -1
  18. package/lib/common/createPartialApiContext.js.map +1 -1
  19. package/lib/common/createSession.d.ts.map +1 -1
  20. package/lib/common/createSession.js +2 -6
  21. package/lib/common/createSession.js.map +1 -1
  22. package/lib/data/busSources.d.ts +42 -36
  23. package/lib/data/busSources.d.ts.map +1 -1
  24. package/lib/data/busSources.js +2 -4
  25. package/lib/data/busSources.js.map +1 -1
  26. package/lib/index.browser.d.ts +4 -1
  27. package/lib/index.browser.d.ts.map +1 -1
  28. package/lib/index.browser.js +2 -1
  29. package/lib/index.browser.js.map +1 -1
  30. package/lib/index.d.ts +1 -1
  31. package/lib/index.d.ts.map +1 -1
  32. package/lib/index.js +0 -1
  33. package/lib/index.js.map +1 -1
  34. package/lib/trpc/createAppRouter.d.ts +36 -2
  35. package/lib/trpc/createAppRouter.d.ts.map +1 -1
  36. package/lib/trpc/createCloudpackClient.d.ts.map +1 -1
  37. package/lib/trpc/createCloudpackClient.js +0 -7
  38. package/lib/trpc/createCloudpackClient.js.map +1 -1
  39. package/lib/trpc/createCloudpackServer.d.ts +8 -16
  40. package/lib/trpc/createCloudpackServer.d.ts.map +1 -1
  41. package/lib/trpc/createCloudpackServer.js +12 -9
  42. package/lib/trpc/createCloudpackServer.js.map +1 -1
  43. package/lib/trpc/createContextFactory.d.ts +1 -14
  44. package/lib/trpc/createContextFactory.d.ts.map +1 -1
  45. package/lib/trpc/createContextFactory.js +2 -35
  46. package/lib/trpc/createContextFactory.js.map +1 -1
  47. package/lib/tsdoc-metadata.json +1 -1
  48. package/lib/types/Session.d.ts +11 -13
  49. package/lib/types/Session.d.ts.map +1 -1
  50. package/lib/types/Session.js.map +1 -1
  51. package/lib/types/TaskDescription.d.ts +23 -20
  52. package/lib/types/TaskDescription.d.ts.map +1 -1
  53. package/lib/types/TaskList.d.ts +392 -0
  54. package/lib/types/TaskList.d.ts.map +1 -0
  55. package/lib/types/TaskList.js +6 -0
  56. package/lib/types/TaskList.js.map +1 -0
  57. package/lib/types/TaskRunnerContext.d.ts +3 -0
  58. package/lib/types/TaskRunnerContext.d.ts.map +1 -0
  59. package/lib/types/TaskRunnerContext.js +2 -0
  60. package/lib/types/TaskRunnerContext.js.map +1 -0
  61. package/lib/utilities/TaskRunner.d.ts +19 -6
  62. package/lib/utilities/TaskRunner.d.ts.map +1 -1
  63. package/lib/utilities/TaskRunner.js +96 -24
  64. package/lib/utilities/TaskRunner.js.map +1 -1
  65. package/lib/utilities/createBundleTask.d.ts +1 -1
  66. package/lib/utilities/createBundleTask.d.ts.map +1 -1
  67. package/lib/utilities/createBundleTask.js +8 -2
  68. package/lib/utilities/createBundleTask.js.map +1 -1
  69. package/lib/utilities/getDefaultTaskStats.d.ts +3 -0
  70. package/lib/utilities/getDefaultTaskStats.d.ts.map +1 -0
  71. package/lib/utilities/getDefaultTaskStats.js +8 -0
  72. package/lib/utilities/getDefaultTaskStats.js.map +1 -0
  73. package/lib/utilities/notifyReload.d.ts +3 -1
  74. package/lib/utilities/notifyReload.d.ts.map +1 -1
  75. package/lib/utilities/notifyReload.js +3 -3
  76. package/lib/utilities/notifyReload.js.map +1 -1
  77. package/package.json +13 -13
  78. package/lib/startApiServer.d.ts +0 -28
  79. package/lib/startApiServer.d.ts.map +0 -1
  80. package/lib/startApiServer.js +0 -277
  81. package/lib/startApiServer.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"TaskRunner.js","sourceRoot":"","sources":["../../src/utilities/TaskRunner.ts"],"names":[],"mappings":"AAIA,OAAO,MAAM,MAAM,SAAS,CAAC;AAC7B,OAAO,YAAY,MAAM,QAAQ,CAAC;AAElC,6DAA6D;AAC7D,MAAM,GAAG,GAAG,CAAC,GAAG,QAAmB,EAAE,EAAE;IACrC,2CAA2C;AAC7C,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,OAAO,UAAW,SAAQ,YAAY;IAU1C;QACE,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,aAAa,GAAG,IAAI,GAAG,EAAE,CAAC;QAC/B,IAAI,CAAC,eAAe,GAAG,IAAI,GAAG,EAAE,CAAC;QACjC,IAAI,CAAC,cAAc,GAAG,IAAI,GAAG,EAAE,CAAC;QAChC,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,EAAE,CAAC;IAC9B,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAU,IAAmB,EAAE,OAAqB;QACrD,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACnC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAEjD,KAAK,EAAE,EAAE,CAAC;QAEV,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;YA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AAC,GAAG,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC3B,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC/B,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAClC,CAAC;IAED,2CAA2C;IAC3C,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IAED,sDAAsD;IACtD,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACF","sourcesContent":["import type { TaskStartDescription } from '../types/TaskStartDescription.js';\nimport type { TaskEndDescription } from '../types/TaskEndDescription.js';\nimport type { TaskOptions } from '../types/TaskOptions.js';\nimport type { Task } from '../types/Task.js';\nimport PQueue from 'p-queue';\nimport EventEmitter from 'events';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst log = (...messages: unknown[]) => {\n // console.log(`TaskRunner:`, ...messages);\n};\n\n/**\n * TaskRunner class manages the state of Tasks.\n * This class is to be called by the api server.\n */\nexport class TaskRunner extends EventEmitter {\n private _queue: PQueue;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _pendingTasks: Map<string, Promise<any>>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _completedTasks: Map<string, any>;\n private _requiresRerun: Set<string>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _prevTasks: Map<string, Task<any>>;\n\n constructor() {\n super();\n\n this._queue = new PQueue({ concurrency: 10 });\n this._pendingTasks = new Map();\n this._completedTasks = new Map();\n this._requiresRerun = new Set();\n this._prevTasks = new Map();\n }\n\n /**\n * The add method enqueues a Task and returns its Promise.\n * If a Task with the same id has already been processed,\n * it returns either the result or the promise.\n * Rerun flag forces the Task to be run again.\n */\n add<TReturn>(task: Task<TReturn>, options?: TaskOptions): Promise<TReturn> {\n const { name, id, execute } = task;\n const { rerun, watch, priority } = options || {};\n\n watch?.();\n\n if (!this._prevTasks.get(id)) {\n this._prevTasks.set(id, task);\n }\n\n // Check if we are already completed the task with that id.\n const action = this._completedTasks.get(id) as TReturn | undefined;\n if (action !== undefined && !rerun) {\n log(`Previous action found, returning: \"${name}:${id}\"`);\n return Promise.resolve(action);\n }\n\n // Check if we are already running the task with that id.\n const pending = this._pendingTasks.get(id) as Promise<TReturn> | undefined;\n if (pending !== undefined) {\n if (rerun) {\n this._requiresRerun.add(id);\n }\n log(`Previous action found, waiting: \"${name}:${id}\"`);\n return pending;\n }\n\n const resultPromise = (async () => {\n let taskResult: TReturn | undefined;\n\n do {\n // Delete from rerun list (if present).\n this._requiresRerun.delete(id);\n\n taskResult = await this._queue.add(\n async () => {\n const startDescription: TaskStartDescription = {\n ...task.getStartDescription?.(),\n id: task.id,\n };\n this.emit('executeStarted', startDescription);\n\n const result = await execute();\n\n const endDescription: TaskEndDescription = {\n ...task.getEndDescription?.(result),\n id: task.id,\n };\n this.emit('executeCompleted', endDescription);\n\n return result;\n },\n // Removes void from return type.\n // Read more on: https://github.com/sindresorhus/p-queue/issues/175\n { throwOnTimeout: true, priority },\n );\n } while (this._requiresRerun.has(id));\n\n log(`Task finished: \"${name}:${id}\"`);\n\n // Delete from pending list.\n this._pendingTasks.delete(id);\n\n // Extra check to ensure that the task returned a value.\n // It should never throw, if it does we have a bug.\n if (taskResult === undefined) {\n throw new Error(`Task \"${name}:${id}\" returned undefined, without throwing an error, which was unexpected.`);\n }\n\n // Update finished Tasks.\n this._completedTasks.set(id, taskResult);\n\n return taskResult;\n })();\n\n this._pendingTasks.set(id, resultPromise);\n this._completedTasks.delete(id);\n\n return resultPromise;\n }\n\n /**\n * The remove method disposes a task if available\n * and then removes it from the TaskRunner.\n *\n * This is useful when the state of a task needs to be cleared.\n *\n * It is intended to be used by the api server\n * to clear the TaskRunner's state before reloading the page.\n */\n remove(id: string): void {\n this._prevTasks\n .get(id)\n ?.dispose?.()\n .catch(() => {\n log(`Error disposing task: ${id}`);\n });\n this._prevTasks.get(id)?.clear?.();\n this._prevTasks.delete(id);\n this._requiresRerun.delete(id);\n this._pendingTasks.delete(id);\n this._completedTasks.delete(id);\n }\n\n /** Pauses the TaskRunner (for testing). */\n pause(): void {\n this._queue.pause();\n }\n\n /** Starts or resumes the TaskRunner (for testing). */\n start(): void {\n this._queue.start();\n }\n}\n"]}
1
+ {"version":3,"file":"TaskRunner.js","sourceRoot":"","sources":["../../src/utilities/TaskRunner.ts"],"names":[],"mappings":"AAOA,OAAO,MAAM,MAAM,SAAS,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,eAAe,EAAwB,MAAM,qBAAqB,CAAC;AAE5F;;;GAGG;AACH,MAAM,OAAO,UAAU;IAcrB,YAAY,OAA2B;QACrC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,mBAAmB,EAAE,CAAC;QACxC,IAAI,CAAC,aAAa,GAAG,IAAI,GAAG,EAAE,CAAC;QAC/B,IAAI,CAAC,eAAe,GAAG,IAAI,GAAG,EAAE,CAAC;QACjC,IAAI,CAAC,cAAc,GAAG,IAAI,GAAG,EAAE,CAAC;QAChC,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,EAAE,CAAC;QAE5B,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC;YACvC,GAAG,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,EAAE,EAAE,QAAQ,CA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,GAAG,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAC9C,GAAG,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TaskStartDescription } from '../types/TaskStartDescription.js';\nimport type { TaskEndDescription } from '../types/TaskEndDescription.js';\nimport type { TaskOptions } from '../types/TaskOptions.js';\nimport type { Task } from '../types/Task.js';\nimport type { TaskRunnerContext } from '../types/TaskRunnerContext.js';\nimport type { TaskStats } from '../types/TaskStats.js';\nimport type { TaskList } from '../types/TaskList.js';\nimport PQueue from 'p-queue';\nimport { getDefaultTaskStats } from './getDefaultTaskStats.js';\nimport { taskListSource, taskStatsSource, type TaskDescription } from '../index.browser.js';\n\n/**\n * TaskRunner class manages the state of Tasks.\n * This class is to be called by the api server.\n */\nexport class TaskRunner {\n // Context is used to publish task status to the bus,\n // so it is optional, as it is not needed during init or testing.\n private _context: TaskRunnerContext | undefined;\n private _queue: PQueue;\n private _taskStats: TaskStats;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _pendingTasks: Map<string, Promise<any>>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _completedTasks: Map<string, any>;\n private _requiresRerun: Set<string>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _prevTasks: Map<string, Task<any>>;\n\n constructor(context?: TaskRunnerContext) {\n this._context = context;\n this._queue = new PQueue({ concurrency: 10 });\n this._taskStats = getDefaultTaskStats();\n this._pendingTasks = new Map();\n this._completedTasks = new Map();\n this._requiresRerun = new Set();\n this._prevTasks = new Map();\n\n if (this._context) {\n const { bus, session } = this._context;\n bus.publish([session.id, 'status'], this._taskStats);\n }\n }\n\n /**\n * The add method enqueues a Task and returns its Promise.\n * If a Task with the same id has already been processed,\n * it returns either the result or the promise.\n * Rerun flag forces the Task to be run again.\n */\n add<TReturn>(task: Task<TReturn>, options?: TaskOptions): Promise<TReturn> {\n const { name, id, execute } = task;\n const { rerun, watch, priority } = options || {};\n\n watch?.();\n\n if (!this._prevTasks.get(id)) {\n this._prevTasks.set(id, task);\n }\n\n // Check if we are already completed the task with that id.\n const action = this._completedTasks.get(id) as TReturn | undefined;\n if (action !== undefined && !rerun) {\n return Promise.resolve(action);\n }\n\n // Check if we are already running the task with that id.\n const pending = this._pendingTasks.get(id) as Promise<TReturn> | undefined;\n if (pending !== undefined) {\n if (rerun) {\n this._requiresRerun.add(id);\n }\n return pending;\n }\n\n const resultPromise = (async () => {\n let taskResult: TReturn | undefined;\n\n do {\n // Delete from rerun list (if present).\n this._requiresRerun.delete(id);\n\n taskResult = await this._queue.add(\n async () => {\n if (task.getStartDescription) {\n this._reportStart(id, task.getStartDescription());\n }\n\n const result = await execute();\n\n if (task.getEndDescription) {\n this._reportEnd(id, task.getEndDescription(result));\n }\n return result;\n },\n // Removes void from return type.\n // Read more on: https://github.com/sindresorhus/p-queue/issues/175\n { throwOnTimeout: true, priority },\n );\n } while (this._requiresRerun.has(id));\n\n // Delete from pending list.\n this._pendingTasks.delete(id);\n\n // Extra check to ensure that the task returned a value.\n // It should never throw, if it does we have a bug.\n if (taskResult === undefined) {\n throw new Error(`Task \"${name}:${id}\" returned undefined, without throwing an error, which was unexpected.`);\n }\n\n // Update finished Tasks.\n this._completedTasks.set(id, taskResult);\n\n return taskResult;\n })();\n\n this._pendingTasks.set(id, resultPromise);\n this._completedTasks.delete(id);\n\n return resultPromise;\n }\n\n /**\n * The remove method disposes a task if available\n * and then removes it from the TaskRunner.\n *\n * This is useful when the state of a task needs to be cleared.\n *\n * It is intended to be used by the api server\n * to clear the TaskRunner's state before reloading the page.\n */\n remove(id: string): void {\n this._prevTasks\n .get(id)\n ?.dispose?.()\n .catch(() => {\n console.debug(`Error disposing task: ${id}`);\n });\n this._prevTasks.get(id)?.clear?.();\n this._prevTasks.delete(id);\n this._requiresRerun.delete(id);\n this._pendingTasks.delete(id);\n this._completedTasks.delete(id);\n }\n /**\n * The clear method disposes all tasks and clears the TaskRunner.\n */\n clear(): void {\n this._taskStats = getDefaultTaskStats();\n if (this._context) {\n const { bus, session } = this._context;\n bus.publish([session.id, 'status'], this._taskStats);\n bus.publish(taskListSource, { tasks: [] });\n }\n for (const id of this._prevTasks.keys()) {\n this.remove(id);\n }\n }\n\n /** Pauses the TaskRunner (for testing). */\n _pause(): void {\n this._queue.pause();\n }\n\n /** Starts or resumes the TaskRunner (for testing). */\n _start(): void {\n this._queue.start();\n }\n\n /**\n * Internal method to report the start of a task to the bus.\n */\n private _reportStart(id: string, description: TaskStartDescription): void {\n if (!this._context) return;\n const { bus } = this._context;\n const { tasks } = bus.getData<TaskList>(taskListSource.path) || { tasks: [] };\n const index = tasks.findIndex((t) => t.id === id);\n const previousDescription = tasks[index];\n const now = new Date().getTime();\n\n if (!previousDescription) {\n this._taskStats.totalTasks++;\n }\n\n if (previousDescription?.status === 'complete') {\n this._taskStats.totalErrors -= previousDescription.errors?.length || 0;\n this._taskStats.totalWarnings -= previousDescription.warnings?.length || 0;\n }\n\n this._taskStats.remainingTasks++;\n this._taskStats.status = 'pending';\n\n const task: TaskDescription = {\n ...description,\n status: 'pending',\n startTime: now,\n };\n if (index === -1) {\n tasks.push(task);\n } else {\n tasks[index] = task;\n }\n\n bus.publish(taskStatsSource, this._taskStats);\n bus.publish(taskListSource, { tasks });\n }\n\n /**\n * Internal method to report the end of a task to the bus.\n */\n private _reportEnd(id: string, description: TaskEndDescription): void {\n if (!this._context) return;\n const { bus } = this._context;\n const { tasks } = bus.getData<TaskList>(taskListSource.path) || { tasks: [] };\n const index = tasks.findIndex((t) => t.id === id);\n const previousDescription = tasks[index];\n const now = new Date().getTime();\n\n if (previousDescription) {\n this._taskStats.remainingTasks--;\n this._taskStats.totalErrors += description?.errors?.length || 0;\n this._taskStats.totalWarnings += description?.warnings?.length || 0;\n\n tasks[index] = {\n ...previousDescription,\n ...description,\n status: 'complete',\n durationMilliseconds: now - previousDescription.startTime,\n lastUpdated: now,\n };\n\n if (this._taskStats.remainingTasks === 0) {\n this._taskStats.status = 'idle';\n }\n\n bus.publish(taskStatsSource, this._taskStats);\n bus.publish(taskListSource, { tasks });\n }\n }\n}\n"]}
@@ -6,5 +6,5 @@ import type { PartialContext } from '../types/Context.js';
6
6
  * Create a bundle task (internally calls `bundleTask()`) that can be executed by the server's TaskRunner.
7
7
  * This allows active tasks to be tracked remotely (e.g. in the browser) and allows the user to cancel tasks.
8
8
  */
9
- export declare function createBundleTask(options: BundleTaskInternalOptions, context: BundleTaskInternalContext & PartialContext<'packageHashes' | 'packageImportPaths', keyof BundleTaskInternalContext['session'] | 'importMap'>): Task<BundleRequest>;
9
+ export declare function createBundleTask(options: BundleTaskInternalOptions, context: BundleTaskInternalContext & PartialContext<'packageHashes' | 'packageImportPaths', keyof BundleTaskInternalContext['session'] | 'importMap' | 'urls'>): Task<BundleRequest>;
10
10
  //# sourceMappingURL=createBundleTask.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createBundleTask.d.ts","sourceRoot":"","sources":["../../src/utilities/createBundleTask.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAc,KAAK,yBAAyB,EAAE,KAAK,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAC7G,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,yBAAyB,EAClC,OAAO,EAAE,yBAAyB,GAChC,cAAc,CAAC,eAAe,GAAG,oBAAoB,EAAE,MAAM,yBAAyB,CAAC,SAAS,CAAC,GAAG,WAAW,CAAC,GACjH,IAAI,CAAC,aAAa,CAAC,CAqDrB"}
1
+ {"version":3,"file":"createBundleTask.d.ts","sourceRoot":"","sources":["../../src/utilities/createBundleTask.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAc,KAAK,yBAAyB,EAAE,KAAK,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAC7G,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,yBAAyB,EAClC,OAAO,EAAE,yBAAyB,GAChC,cAAc,CACZ,eAAe,GAAG,oBAAoB,EACtC,MAAM,yBAAyB,CAAC,SAAS,CAAC,GAAG,WAAW,GAAG,MAAM,CAClE,GACF,IAAI,CAAC,aAAa,CAAC,CA8DrB"}
@@ -21,8 +21,14 @@ export function createBundleTask(options, context) {
21
21
  async execute() {
22
22
  await bundleTask(options, context);
23
23
  try {
24
- const importMapHash = sourceHash || hash || (await packageHashes.get({ packagePath, isSourceHashingEnabled: !isExternal }));
25
- addImportMapHash({ packageName, version, hash: importMapHash }, { ...context, ...session });
24
+ // Add a hash to the import map for this package.
25
+ // (Read the session properties here rather than above because they might not be set yet.)
26
+ const importMap = session.importMap;
27
+ const bundleServer = session.urls.bundleServer;
28
+ if (importMap && bundleServer) {
29
+ const importMapHash = sourceHash || hash || (await packageHashes.get({ packagePath, isSourceHashingEnabled: !isExternal }));
30
+ addImportMapHash({ packageName, version, hash: importMapHash }, { ...context, ...session, importMap, urls: { bundleServer } });
31
+ }
26
32
  }
27
33
  catch (e) {
28
34
  console.error(`Error adding hash to import map for ${bundleRequest.packagePath}:`, e.stack || e);
@@ -1 +1 @@
1
- {"version":3,"file":"createBundleTask.js","sourceRoot":"","sources":["../../src/utilities/createBundleTask.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,MAAM,IAAI,CAA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D,KAAK,EAAE,GAAG,EAAE;YACV,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC;gBAC1B,OAAO;YACT,CAAC;YAED,aAAa,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;YAEjC,qGAAqG;YACrG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YAE7E,aAAa,CAAC,MAAM,GAAG,SAAS,CAAC;QACnC,CAAC;QACD,SAAS,EAAE,GAAG,EAAE;YACd,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC;QACpC,CAAC;QACD,SAAS,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM;QAC7C,mBAAmB,EAAE,GAAG,EAAE,CAAC,CAAC;YAC1B,EAAE;YACF,kCAAkC;YAClC,IAAI;YACJ,SAAS,EAAE,WAAW,IAAI,EAAE;SAC7B,CAAC;QACF,iBAAiB,EAAE,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;YAClC,EAAE;YACF,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM;YAClC,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ;YACtC,UAAU,EAAE,aAAa,CAAC,MAAM,EAAE,UAAU,IAAI,EAAE;SACnD,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import { addImportMapHash } from '@ms-cloudpack/import-map';\nimport fs from 'fs';\nimport path from 'path';\nimport type { BundleRequest } from '../types/BundleRequest.js';\nimport type { Task } from '../types/Task.js';\nimport { bundleTask, type BundleTaskInternalContext, type BundleTaskInternalOptions } from './bundleTask.js';\nimport type { PartialContext } from '../types/Context.js';\n\n/**\n * Create a bundle task (internally calls `bundleTask()`) that can be executed by the server's TaskRunner.\n * This allows active tasks to be tracked remotely (e.g. in the browser) and allows the user to cancel tasks.\n */\nexport function createBundleTask(\n options: BundleTaskInternalOptions,\n context: BundleTaskInternalContext &\n PartialContext<'packageHashes' | 'packageImportPaths', keyof BundleTaskInternalContext['session'] | 'importMap'>,\n): Task<BundleRequest> {\n const { bundleRequest } = options;\n const { id, packageName, version, packagePath, isExternal } = bundleRequest;\n const { packageHashes, session } = context;\n const { hash, sourceHash } = options;\n const name = `Bundle ${packageName}@${version}`;\n\n return {\n // Name for task runner logging.\n name,\n id,\n dir: `${path.join(packagePath, 'src')}`,\n watch: !isExternal,\n async execute(): Promise<BundleRequest> {\n await bundleTask(options, context);\n try {\n const importMapHash =\n sourceHash || hash || (await packageHashes.get({ packagePath, isSourceHashingEnabled: !isExternal }));\n addImportMapHash({ packageName, version, hash: importMapHash }, { ...context, ...session });\n } catch (e) {\n console.error(`Error adding hash to import map for ${bundleRequest.packagePath}:`, (e as Error).stack || e);\n }\n return bundleRequest;\n },\n clear: () => {\n if (!bundleRequest.result) {\n return;\n }\n\n bundleRequest.result.dispose?.();\n\n // eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem -- this function can't be async\n fs.rmSync(bundleRequest.result.outputPath, { recursive: true, force: true });\n\n bundleRequest.result = undefined;\n },\n onDispose: () => {\n bundleRequest.result?.dispose?.();\n },\n getErrors: () => bundleRequest.result?.errors,\n getStartDescription: () => ({\n id,\n // Name to display in the overlay.\n name,\n inputPath: packagePath || '',\n }),\n getEndDescription: (taskResult) => ({\n id,\n errors: taskResult?.result?.errors,\n warnings: taskResult?.result?.warnings,\n outputPath: bundleRequest.result?.outputPath || '',\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"createBundleTask.js","sourceRoot":"","sources":["../../src/utilities/createBundleTask.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,OAAO,EAAE,UAAU,EAAkE,MAAM,iBAAiB,CAAC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ACX,OAAO,CAAC,KAAK,CAAC,uCAAuC,aAAa,CAAC,WAAW,GAAG,EAAG,CAAW,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;YAC9G,CAAC;YACD,OAAO,aAAa,CAAC;QACvB,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACV,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC;gBAC1B,OAAO;YACT,CAAC;YAED,aAAa,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;YAEjC,qGAAqG;YACrG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YAE7E,aAAa,CAAC,MAAM,GAAG,SAAS,CAAC;QACnC,CAAC;QACD,SAAS,EAAE,GAAG,EAAE;YACd,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC;QACpC,CAAC;QACD,SAAS,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM;QAC7C,mBAAmB,EAAE,GAAG,EAAE,CAAC,CAAC;YAC1B,EAAE;YACF,kCAAkC;YAClC,IAAI;YACJ,SAAS,EAAE,WAAW,IAAI,EAAE;SAC7B,CAAC;QACF,iBAAiB,EAAE,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;YAClC,EAAE;YACF,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM;YAClC,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ;YACtC,UAAU,EAAE,aAAa,CAAC,MAAM,EAAE,UAAU,IAAI,EAAE;SACnD,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import { addImportMapHash } from '@ms-cloudpack/import-map';\nimport fs from 'fs';\nimport path from 'path';\nimport type { BundleRequest } from '../types/BundleRequest.js';\nimport type { Task } from '../types/Task.js';\nimport { bundleTask, type BundleTaskInternalContext, type BundleTaskInternalOptions } from './bundleTask.js';\nimport type { PartialContext } from '../types/Context.js';\n\n/**\n * Create a bundle task (internally calls `bundleTask()`) that can be executed by the server's TaskRunner.\n * This allows active tasks to be tracked remotely (e.g. in the browser) and allows the user to cancel tasks.\n */\nexport function createBundleTask(\n options: BundleTaskInternalOptions,\n context: BundleTaskInternalContext &\n PartialContext<\n 'packageHashes' | 'packageImportPaths',\n keyof BundleTaskInternalContext['session'] | 'importMap' | 'urls'\n >,\n): Task<BundleRequest> {\n const { bundleRequest } = options;\n const { id, packageName, version, packagePath, isExternal } = bundleRequest;\n const { packageHashes, session } = context;\n const { hash, sourceHash } = options;\n const name = `Bundle ${packageName}@${version}`;\n\n return {\n // Name for task runner logging.\n name,\n id,\n dir: `${path.join(packagePath, 'src')}`,\n watch: !isExternal,\n async execute(): Promise<BundleRequest> {\n await bundleTask(options, context);\n try {\n // Add a hash to the import map for this package.\n // (Read the session properties here rather than above because they might not be set yet.)\n const importMap = session.importMap;\n const bundleServer = session.urls.bundleServer;\n if (importMap && bundleServer) {\n const importMapHash =\n sourceHash || hash || (await packageHashes.get({ packagePath, isSourceHashingEnabled: !isExternal }));\n addImportMapHash(\n { packageName, version, hash: importMapHash },\n { ...context, ...session, importMap, urls: { bundleServer } },\n );\n }\n } catch (e) {\n console.error(`Error adding hash to import map for ${bundleRequest.packagePath}:`, (e as Error).stack || e);\n }\n return bundleRequest;\n },\n clear: () => {\n if (!bundleRequest.result) {\n return;\n }\n\n bundleRequest.result.dispose?.();\n\n // eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem -- this function can't be async\n fs.rmSync(bundleRequest.result.outputPath, { recursive: true, force: true });\n\n bundleRequest.result = undefined;\n },\n onDispose: () => {\n bundleRequest.result?.dispose?.();\n },\n getErrors: () => bundleRequest.result?.errors,\n getStartDescription: () => ({\n id,\n // Name to display in the overlay.\n name,\n inputPath: packagePath || '',\n }),\n getEndDescription: (taskResult) => ({\n id,\n errors: taskResult?.result?.errors,\n warnings: taskResult?.result?.warnings,\n outputPath: bundleRequest.result?.outputPath || '',\n }),\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import type { TaskStats } from '../types/TaskStats.js';
2
+ export declare const getDefaultTaskStats: () => TaskStats;
3
+ //# sourceMappingURL=getDefaultTaskStats.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getDefaultTaskStats.d.ts","sourceRoot":"","sources":["../../src/utilities/getDefaultTaskStats.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEvD,eAAO,MAAM,mBAAmB,EAAE,MAAM,SAMtC,CAAC"}
@@ -0,0 +1,8 @@
1
+ export const getDefaultTaskStats = () => ({
2
+ status: 'idle',
3
+ remainingTasks: 0,
4
+ totalTasks: 0,
5
+ totalErrors: 0,
6
+ totalWarnings: 0,
7
+ });
8
+ //# sourceMappingURL=getDefaultTaskStats.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getDefaultTaskStats.js","sourceRoot":"","sources":["../../src/utilities/getDefaultTaskStats.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,mBAAmB,GAAoB,GAAG,EAAE,CAAC,CAAC;IACzD,MAAM,EAAE,MAAM;IACd,cAAc,EAAE,CAAC;IACjB,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,aAAa,EAAE,CAAC;CACjB,CAAC,CAAC","sourcesContent":["import type { TaskStats } from '../types/TaskStats.js';\n\nexport const getDefaultTaskStats: () => TaskStats = () => ({\n status: 'idle',\n remainingTasks: 0,\n totalTasks: 0,\n totalErrors: 0,\n totalWarnings: 0,\n});\n"]}
@@ -1,8 +1,10 @@
1
1
  import type { DataBus } from '@ms-cloudpack/data-bus';
2
+ import type { Session } from '../types/Session.js';
2
3
  /**
3
4
  * Notifies clients that a reload is needed by incrementing the session version.
4
5
  */
5
- export declare function notifyReload({ bus }: {
6
+ export declare function notifyReload({ bus, session }: {
6
7
  bus: DataBus;
8
+ session: Session;
7
9
  }): void;
8
10
  //# sourceMappingURL=notifyReload.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"notifyReload.d.ts","sourceRoot":"","sources":["../../src/utilities/notifyReload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAGtD;;GAEG;AACH,wBAAgB,YAAY,CAAC,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,EAAE,OAAO,CAAA;CAAE,QAIrD"}
1
+ {"version":3,"file":"notifyReload.d.ts","sourceRoot":"","sources":["../../src/utilities/notifyReload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAEtD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAEnD;;GAEG;AACH,wBAAgB,YAAY,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE;IAAE,GAAG,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,QAGhF"}
@@ -2,8 +2,8 @@ import { reloadCountSource } from '../data/busSources.js';
2
2
  /**
3
3
  * Notifies clients that a reload is needed by incrementing the session version.
4
4
  */
5
- export function notifyReload({ bus }) {
6
- const version = bus.getData(reloadCountSource) || 0;
7
- bus.publish(reloadCountSource, version + 1);
5
+ export function notifyReload({ bus, session }) {
6
+ session.sequence++;
7
+ bus.publish(reloadCountSource, session.sequence);
8
8
  }
9
9
  //# sourceMappingURL=notifyReload.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"notifyReload.js","sourceRoot":"","sources":["../../src/utilities/notifyReload.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,EAAE,GAAG,EAAoB;IACpD,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAEpD,GAAG,CAAC,OAAO,CAAC,iBAAiB,EAAE,OAAO,GAAG,CAAC,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import type { DataBus } from '@ms-cloudpack/data-bus';\nimport { reloadCountSource } from '../data/busSources.js';\n\n/**\n * Notifies clients that a reload is needed by incrementing the session version.\n */\nexport function notifyReload({ bus }: { bus: DataBus }) {\n const version = bus.getData(reloadCountSource) || 0;\n\n bus.publish(reloadCountSource, version + 1);\n}\n"]}
1
+ {"version":3,"file":"notifyReload.js","sourceRoot":"","sources":["../../src/utilities/notifyReload.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAG1D;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,EAAE,GAAG,EAAE,OAAO,EAAsC;IAC/E,OAAO,CAAC,QAAQ,EAAE,CAAC;IACnB,GAAG,CAAC,OAAO,CAAC,iBAAiB,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import type { DataBus } from '@ms-cloudpack/data-bus';\nimport { reloadCountSource } from '../data/busSources.js';\nimport type { Session } from '../types/Session.js';\n\n/**\n * Notifies clients that a reload is needed by incrementing the session version.\n */\nexport function notifyReload({ bus, session }: { bus: DataBus; session: Session }) {\n session.sequence++;\n bus.publish(reloadCountSource, session.sequence);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ms-cloudpack/api-server",
3
- "version": "0.42.1",
3
+ "version": "0.44.0",
4
4
  "description": "An implementation of the API server that does interacts with a task scheduler.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -23,25 +23,25 @@
23
23
  }
24
24
  },
25
25
  "dependencies": {
26
- "@lage-run/hasher": "^1.0.5",
26
+ "@lage-run/hasher": "^1.1.1",
27
27
  "@lage-run/logger": "^1.3.0",
28
- "@lage-run/scheduler": "^1.1.9",
28
+ "@lage-run/scheduler": "^1.2.1",
29
29
  "@lage-run/target-graph": "^0.8.9",
30
- "@ms-cloudpack/bundler": "^0.20.6",
31
- "@ms-cloudpack/common-types": "^0.5.0",
32
- "@ms-cloudpack/config": "^0.20.3",
33
- "@ms-cloudpack/create-express-app": "^1.6.10",
30
+ "@ms-cloudpack/bundler": "^0.20.8",
31
+ "@ms-cloudpack/common-types": "^0.5.2",
32
+ "@ms-cloudpack/config": "^0.20.5",
33
+ "@ms-cloudpack/create-express-app": "^1.6.12",
34
34
  "@ms-cloudpack/data-bus": "^0.4.2",
35
35
  "@ms-cloudpack/file-watcher": "^0.1.2",
36
- "@ms-cloudpack/import-map": "^0.4.0",
36
+ "@ms-cloudpack/import-map": "^0.5.1",
37
37
  "@ms-cloudpack/json-utilities": "^0.1.4",
38
- "@ms-cloudpack/package-hashes": "^0.5.14",
39
- "@ms-cloudpack/package-utilities": "^7.4.2",
38
+ "@ms-cloudpack/package-hashes": "^0.5.16",
39
+ "@ms-cloudpack/package-utilities": "^7.4.4",
40
40
  "@ms-cloudpack/path-string-parsing": "^1.2.2",
41
- "@ms-cloudpack/path-utilities": "^2.7.7",
42
- "@ms-cloudpack/remote-cache": "^0.7.2",
41
+ "@ms-cloudpack/path-utilities": "^2.7.9",
42
+ "@ms-cloudpack/remote-cache": "^0.7.3",
43
43
  "@ms-cloudpack/task-reporter": "^0.14.0",
44
- "@ms-cloudpack/telemetry": "^0.5.1",
44
+ "@ms-cloudpack/telemetry": "^0.5.2",
45
45
  "@trpc/client": "^10.45.0",
46
46
  "@trpc/server": "^10.45.0",
47
47
  "cors": "^2.8.5",
@@ -1,28 +0,0 @@
1
- import type { DataBus } from '@ms-cloudpack/data-bus';
2
- import type { TaskRunner } from './utilities/TaskRunner.js';
3
- import type { ApiServer } from './types/ApiServer.js';
4
- import type { Session } from './types/Session.js';
5
- import type { TelemetryClient } from '@ms-cloudpack/telemetry';
6
- import type { PackageDefinitionsCache } from '@ms-cloudpack/common-types';
7
- /**
8
- * The api server handles the data pub/sub (for things like reporting build status)
9
- * and hosting the dashboard verb backend (for executing actions like loading vscode,
10
- * changing dependencies, connecting new projects to the running session, etc.)
11
- *
12
- * Each time `cloudpack start` is run, an api server will start up for that session. The
13
- * hosted web page will have a "cloudpack-api-server" header which points
14
- * to the websocket server.
15
- *
16
- * The bundle server will call the api server to publish build status updates.
17
- *
18
- * The app server will burn the api server url on the host html, so that client-side
19
- * javascript can connect and subscribe to page changes.
20
- */
21
- export declare function startApiServer(params: {
22
- session: Session;
23
- telemetryClient: TelemetryClient;
24
- packages: PackageDefinitionsCache;
25
- bus: DataBus;
26
- taskRunner: TaskRunner;
27
- }): Promise<ApiServer>;
28
- //# sourceMappingURL=startApiServer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"startApiServer.d.ts","sourceRoot":"","sources":["../src/startApiServer.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAM5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAGlD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE/D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAS1E;;;;;;;;;;;;;GAaG;AACH,wBAAsB,cAAc,CAAC,MAAM,EAAE;IAC3C,OAAO,EAAE,OAAO,CAAC;IACjB,eAAe,EAAE,eAAe,CAAC;IACjC,QAAQ,EAAE,uBAAuB,CAAC;IAClC,GAAG,EAAE,OAAO,CAAC;IACb,UAAU,EAAE,UAAU,CAAC;CACxB,GAAG,OAAO,CAAC,SAAS,CAAC,CAsTrB"}
@@ -1,277 +0,0 @@
1
- import getPort from 'get-port';
2
- import http from 'http';
3
- import https from 'https';
4
- import WebSocket, { WebSocketServer } from 'ws';
5
- import { getCachePath } from './utilities/getCachePath.js';
6
- import fsExtra from 'fs-extra';
7
- import { validateOverride } from './utilities/validateOverride.js';
8
- import { parseHttpsConfig, getDomain } from '@ms-cloudpack/create-express-app';
9
- import { editCloudpackConfig } from './utilities/editCloudpackConfig.js';
10
- import { reloadCountSource, taskListSource, taskStatsSource } from './data/busSources.js';
11
- import { addPackageOverride } from './apis/addPackageOverride.js';
12
- import { openCodeEditor } from './apis/openCodeEditor.js';
13
- import { openFilePath } from './apis/openFilePath.js';
14
- import { reportMetric } from './apis/reportMetric.js';
15
- /**
16
- * The api server handles the data pub/sub (for things like reporting build status)
17
- * and hosting the dashboard verb backend (for executing actions like loading vscode,
18
- * changing dependencies, connecting new projects to the running session, etc.)
19
- *
20
- * Each time `cloudpack start` is run, an api server will start up for that session. The
21
- * hosted web page will have a "cloudpack-api-server" header which points
22
- * to the websocket server.
23
- *
24
- * The bundle server will call the api server to publish build status updates.
25
- *
26
- * The app server will burn the api server url on the host html, so that client-side
27
- * javascript can connect and subscribe to page changes.
28
- */
29
- export async function startApiServer(params) {
30
- const { session, telemetryClient, packages, bus, taskRunner } = params;
31
- const host = getDomain(session.config?.devServer?.domain);
32
- const port = await getPort({ port: [9890, 9891, 9892, 9893] });
33
- const sessionStats = {
34
- status: 'idle',
35
- remainingTasks: 0,
36
- totalTasks: 0,
37
- totalErrors: 0,
38
- totalWarnings: 0,
39
- };
40
- const allTasks = new Map();
41
- function reportStart(taskStart) {
42
- const previousResult = allTasks.get(taskStart.id);
43
- const now = new Date().getTime();
44
- if (!previousResult) {
45
- sessionStats.totalTasks++;
46
- }
47
- if (previousResult?.status === 'complete') {
48
- sessionStats.totalErrors -= previousResult.errors?.length || 0;
49
- sessionStats.totalWarnings -= previousResult.warnings?.length || 0;
50
- }
51
- sessionStats.remainingTasks++;
52
- sessionStats.status = 'pending';
53
- allTasks.set(taskStart.id, {
54
- ...taskStart,
55
- status: 'pending',
56
- startTime: now,
57
- });
58
- bus.publish(taskStatsSource, sessionStats);
59
- bus.publish(taskListSource, { tasks: Array.from(allTasks.values()) });
60
- }
61
- function reportEnd(taskEnd) {
62
- const previousResult = allTasks.get(taskEnd.id);
63
- const now = new Date().getTime();
64
- if (previousResult) {
65
- sessionStats.remainingTasks--;
66
- sessionStats.totalErrors += taskEnd.errors?.length || 0;
67
- sessionStats.totalWarnings += taskEnd.warnings?.length || 0;
68
- allTasks.set(taskEnd.id, {
69
- ...previousResult,
70
- ...taskEnd,
71
- status: 'complete',
72
- durationMilliseconds: now - previousResult.startTime,
73
- lastUpdated: now,
74
- });
75
- if (sessionStats.remainingTasks === 0) {
76
- sessionStats.status = 'idle';
77
- }
78
- bus.publish(taskStatsSource, sessionStats);
79
- bus.publish(taskListSource, { tasks: Array.from(allTasks.values()) });
80
- }
81
- }
82
- taskRunner.on('executeStarted', reportStart);
83
- taskRunner.on('executeCompleted', reportEnd);
84
- bus.publish([session.id, 'status'], sessionStats);
85
- // Create a node http(s) server.
86
- let server;
87
- const httpsConfig = session.config?.devServer?.https;
88
- const protocol = httpsConfig ? 'wss' : 'ws';
89
- if (httpsConfig) {
90
- const { key, cert, passphrase } = parseHttpsConfig(httpsConfig);
91
- if (!key || !cert) {
92
- console.error('Invalid https config in cloudpack.config.json. Make sure key and cert are valid.');
93
- throw new Error('Invalid https config.');
94
- }
95
- server = https
96
- .createServer({
97
- key,
98
- cert,
99
- passphrase,
100
- }, () => {
101
- /* no-op */
102
- })
103
- .listen(port, host);
104
- }
105
- else {
106
- server = http.createServer().listen(port, host);
107
- }
108
- // Create a websocket server which listens for subscriptions and verb requests,
109
- // and broadcasts the data to all connected clients.
110
- const socketServer = new WebSocketServer({ server }, () => {
111
- // console.log(`ApiServer: Started on port ${port}`);
112
- }).on('connection', (socket) => {
113
- const disposables = new Map();
114
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
115
- function sendMessage(message) {
116
- socket.send(JSON.stringify(message, null, 2));
117
- }
118
- socket.send(JSON.stringify({
119
- type: 'sequence',
120
- sequence: session.sequence,
121
- }));
122
- socket
123
- .on('message', (rawData) => {
124
- try {
125
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
126
- const request = JSON.parse(rawData.toString());
127
- const requestId = request.requestId || '';
128
- switch (request.type) {
129
- /**
130
- * Subscribe to a data subscription.
131
- */
132
- case 'subscribe': {
133
- const { path: subscriptionPath, id } = request.data;
134
- disposables.set(id, bus.subscribe(subscriptionPath,
135
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
136
- (data) => sendMessage({ type: 'notify', id, path: subscriptionPath, data })));
137
- break;
138
- }
139
- /**
140
- * Unsubscribe from a data subscription.
141
- */
142
- case 'unsubscribe': {
143
- const id = request.data.id;
144
- if (id) {
145
- const dispose = disposables.get(id);
146
- if (dispose) {
147
- dispose();
148
- disposables.delete(id);
149
- }
150
- }
151
- break;
152
- }
153
- /**
154
- * Open a file in VSCode.
155
- */
156
- case 'openSource': {
157
- openCodeEditor({ input: request.data, ctx: {} }).catch(() => {
158
- // ignore
159
- });
160
- break;
161
- }
162
- /**
163
- * Open a file or folder in the OS's default file manager.
164
- */
165
- case 'open': {
166
- openFilePath({ input: request.data, ctx: { session } }).catch(() => {
167
- // ignore
168
- });
169
- break;
170
- }
171
- /**
172
- * Opens the cloudpack config in VSCode for the user to manually edit. If the file doesn't exist,
173
- * it will be created.
174
- */
175
- case 'editConfig': {
176
- editCloudpackConfig(session.appPath).catch(() => {
177
- /* no-op */
178
- });
179
- break;
180
- }
181
- /**
182
- * Adds an override to the cloudpack config.
183
- */
184
- case 'addOverride': {
185
- // TODO: Send filename from request data to findResolveMapEntry when chromium Issue 1371551 is fixed.
186
- (async () => {
187
- const { packageName, importPath } = request.data;
188
- await addPackageOverride({
189
- input: { packageName, importPath },
190
- ctx: { session, bus, packages, taskRunner },
191
- });
192
- })().catch(() => {
193
- // no-op
194
- });
195
- break;
196
- }
197
- case 'validateOverride': {
198
- // TODO: Get filename from request data when chromium Issue 1371551 is fixed.
199
- (async () => {
200
- const input = request.data;
201
- const fixable = await validateOverride(input, { session, packages });
202
- const result = { fixable };
203
- sendMessage({ type: 'validateOverride', requestId, data: result });
204
- })().catch(() => {
205
- // no-op
206
- });
207
- break;
208
- }
209
- case 'restartAllTasks': {
210
- console.log('ApiServer: Restarting all tasks');
211
- // Clear entire local cache.
212
- // eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem
213
- fsExtra.emptyDirSync(getCachePath());
214
- // All tasks can be removed as notifyReload()
215
- // will cause the client to add the tasks again.
216
- allTasks.forEach((_, id) => {
217
- taskRunner.remove(id);
218
- });
219
- // Update session version.
220
- session.incrementSessionVersion();
221
- notifyReload();
222
- break;
223
- }
224
- case 'restartTask': {
225
- const { id, inputPath } = request.data;
226
- console.log(`ApiServer: Restarting task ${id}`);
227
- taskRunner.remove(id);
228
- session.incrementTargetVersion(inputPath);
229
- notifyReload();
230
- break;
231
- }
232
- case 'reportMetric': {
233
- reportMetric({ input: request.data, ctx: { telemetryClient } });
234
- break;
235
- }
236
- case 'getSessionId': {
237
- sendMessage({ type: 'sessionId', requestId, data: { sessionId: session.id } });
238
- break;
239
- }
240
- }
241
- }
242
- catch (err) {
243
- console.error('ApiServer: error handling message');
244
- console.error('Error:', err.stack || err);
245
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
246
- console.error('Message:', rawData.toString());
247
- }
248
- })
249
- .on('close', () => {
250
- for (const d of disposables.values()) {
251
- d();
252
- }
253
- });
254
- });
255
- const notifyReload = () => {
256
- session.sequence++;
257
- socketServer.clients.forEach((socket) => {
258
- if (socket.readyState === WebSocket.OPEN) {
259
- socket.send(JSON.stringify({
260
- type: 'reload',
261
- data: { sessionId: session.id },
262
- }));
263
- }
264
- });
265
- };
266
- bus.subscribe(reloadCountSource, notifyReload);
267
- return {
268
- url: `${protocol}://${host}:${port}`,
269
- port,
270
- close: () => new Promise((resolve, reject) => {
271
- socketServer.clients.forEach((socket) => socket.terminate());
272
- socketServer.close((err) => (err ? reject(err) : resolve()));
273
- server.close();
274
- }),
275
- };
276
- }
277
- //# sourceMappingURL=startApiServer.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"startApiServer.js","sourceRoot":"","sources":["../src/startApiServer.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,SAAS,EAAE,EAAE,eAAe,EAAE,MAAM,IAAI,CAAC;AAGhD,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,OAAO,MAAM,UAAU,CAAC;AAM/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AAE/E,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAEzE,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE1F,OAAO,EAAE,kBAAkB,EAAgC,MAAM,8BAA8B,CAAC;AAEhG,OAAO,EAAE,cAAc,EAA4B,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,YAAY,EAA0B,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,YAAY,EAA0B,MAAM,wBAAwB,CAAC;AAE9E;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,MAMpC;IACC,MAAM,EAAE,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IACvE,MAAM,IAAI,GAAG,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE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OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACpC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAiB,EAAE,EAAE,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC;YACxE,YAAY,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;YAC7D,MAAM,CAAC,KAAK,EAAE,CAAC;QACjB,CAAC,CAAC;KACL,CAAC;AACJ,CAAC","sourcesContent":["import getPort from 'get-port';\nimport http from 'http';\nimport https from 'https';\nimport WebSocket, { WebSocketServer } from 'ws';\nimport type { DataBus } from '@ms-cloudpack/data-bus';\nimport type { TaskRunner } from './utilities/TaskRunner.js';\nimport { getCachePath } from './utilities/getCachePath.js';\nimport fsExtra from 'fs-extra';\nimport type { TaskDescription } from './types/TaskDescription.js';\nimport type { TaskEndDescription } from './types/TaskEndDescription.js';\nimport type { TaskStartDescription } from './types/TaskStartDescription.js';\nimport type { ApiServer } from './types/ApiServer.js';\nimport type { Session } from './types/Session.js';\nimport { validateOverride } from './utilities/validateOverride.js';\nimport { parseHttpsConfig, getDomain } from '@ms-cloudpack/create-express-app';\nimport type { TelemetryClient } from '@ms-cloudpack/telemetry';\nimport { editCloudpackConfig } from './utilities/editCloudpackConfig.js';\nimport type { PackageDefinitionsCache } from '@ms-cloudpack/common-types';\nimport { reloadCountSource, taskListSource, taskStatsSource } from './data/busSources.js';\nimport type { TaskStats } from './types/TaskStats.js';\nimport { addPackageOverride, type AddPackageOverrideInput } from './apis/addPackageOverride.js';\nimport type { ValidatePackageOverrideInput, ValidatePackageOverrideOutput } from './apis/validatePackageOverride.js';\nimport { openCodeEditor, type OpenCodeEditorInput } from './apis/openCodeEditor.js';\nimport { openFilePath, type OpenFilePathInput } from './apis/openFilePath.js';\nimport { reportMetric, type ReportMetricInput } from './apis/reportMetric.js';\n\n/**\n * The api server handles the data pub/sub (for things like reporting build status)\n * and hosting the dashboard verb backend (for executing actions like loading vscode,\n * changing dependencies, connecting new projects to the running session, etc.)\n *\n * Each time `cloudpack start` is run, an api server will start up for that session. The\n * hosted web page will have a \"cloudpack-api-server\" header which points\n * to the websocket server.\n *\n * The bundle server will call the api server to publish build status updates.\n *\n * The app server will burn the api server url on the host html, so that client-side\n * javascript can connect and subscribe to page changes.\n */\nexport async function startApiServer(params: {\n session: Session;\n telemetryClient: TelemetryClient;\n packages: PackageDefinitionsCache;\n bus: DataBus;\n taskRunner: TaskRunner;\n}): Promise<ApiServer> {\n const { session, telemetryClient, packages, bus, taskRunner } = params;\n const host = getDomain(session.config?.devServer?.domain);\n const port = await getPort({ port: [9890, 9891, 9892, 9893] });\n const sessionStats: TaskStats = {\n status: 'idle',\n\n remainingTasks: 0,\n totalTasks: 0,\n\n totalErrors: 0,\n totalWarnings: 0,\n };\n\n const allTasks = new Map<string, TaskDescription>();\n\n function reportStart(taskStart: TaskStartDescription): void {\n const previousResult = allTasks.get(taskStart.id);\n const now = new Date().getTime();\n\n if (!previousResult) {\n sessionStats.totalTasks++;\n }\n\n if (previousResult?.status === 'complete') {\n sessionStats.totalErrors -= previousResult.errors?.length || 0;\n sessionStats.totalWarnings -= previousResult.warnings?.length || 0;\n }\n\n sessionStats.remainingTasks++;\n sessionStats.status = 'pending';\n\n allTasks.set(taskStart.id, {\n ...taskStart,\n status: 'pending',\n startTime: now,\n });\n\n bus.publish(taskStatsSource, sessionStats);\n bus.publish(taskListSource, { tasks: Array.from(allTasks.values()) });\n }\n\n function reportEnd(taskEnd: TaskEndDescription): void {\n const previousResult = allTasks.get(taskEnd.id);\n const now = new Date().getTime();\n\n if (previousResult) {\n sessionStats.remainingTasks--;\n sessionStats.totalErrors += taskEnd.errors?.length || 0;\n sessionStats.totalWarnings += taskEnd.warnings?.length || 0;\n\n allTasks.set(taskEnd.id, {\n ...previousResult,\n ...taskEnd,\n status: 'complete',\n durationMilliseconds: now - previousResult.startTime,\n lastUpdated: now,\n });\n\n if (sessionStats.remainingTasks === 0) {\n sessionStats.status = 'idle';\n }\n\n bus.publish(taskStatsSource, sessionStats);\n bus.publish(taskListSource, { tasks: Array.from(allTasks.values()) });\n }\n }\n\n taskRunner.on('executeStarted', reportStart);\n taskRunner.on('executeCompleted', reportEnd);\n\n bus.publish([session.id, 'status'], sessionStats);\n\n // Create a node http(s) server.\n let server: http.Server | https.Server;\n const httpsConfig = session.config?.devServer?.https;\n const protocol = httpsConfig ? 'wss' : 'ws';\n\n if (httpsConfig) {\n const { key, cert, passphrase } = parseHttpsConfig(httpsConfig);\n\n if (!key || !cert) {\n console.error('Invalid https config in cloudpack.config.json. Make sure key and cert are valid.');\n\n throw new Error('Invalid https config.');\n }\n\n server = https\n .createServer(\n {\n key,\n cert,\n passphrase,\n },\n () => {\n /* no-op */\n },\n )\n .listen(port, host);\n } else {\n server = http.createServer().listen(port, host);\n }\n\n // Create a websocket server which listens for subscriptions and verb requests,\n // and broadcasts the data to all connected clients.\n const socketServer = new WebSocketServer({ server }, () => {\n // console.log(`ApiServer: Started on port ${port}`);\n }).on('connection', (socket: WebSocket) => {\n const disposables = new Map<number, () => void>();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function sendMessage(message: any) {\n socket.send(JSON.stringify(message, null, 2));\n }\n\n socket.send(\n JSON.stringify({\n type: 'sequence',\n sequence: session.sequence,\n }),\n );\n\n socket\n .on('message', (rawData) => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n const request = JSON.parse(rawData.toString()) as {\n type: string;\n requestId?: string;\n data: Record<string, unknown>;\n };\n\n const requestId = request.requestId || '';\n\n switch (request.type) {\n /**\n * Subscribe to a data subscription.\n */\n case 'subscribe': {\n const { path: subscriptionPath, id } = request.data;\n\n disposables.set(\n id as number,\n bus.subscribe(\n subscriptionPath as string[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n (data: any) => sendMessage({ type: 'notify', id, path: subscriptionPath, data }),\n ),\n );\n\n break;\n }\n\n /**\n * Unsubscribe from a data subscription.\n */\n case 'unsubscribe': {\n const id = request.data.id as number | undefined;\n if (id) {\n const dispose = disposables.get(id);\n\n if (dispose) {\n dispose();\n disposables.delete(id);\n }\n }\n\n break;\n }\n\n /**\n * Open a file in VSCode.\n */\n case 'openSource': {\n openCodeEditor({ input: request.data as OpenCodeEditorInput, ctx: {} }).catch(() => {\n // ignore\n });\n break;\n }\n\n /**\n * Open a file or folder in the OS's default file manager.\n */\n case 'open': {\n openFilePath({ input: request.data as OpenFilePathInput, ctx: { session } }).catch(() => {\n // ignore\n });\n break;\n }\n\n /**\n * Opens the cloudpack config in VSCode for the user to manually edit. If the file doesn't exist,\n * it will be created.\n */\n case 'editConfig': {\n editCloudpackConfig(session.appPath).catch(() => {\n /* no-op */\n });\n break;\n }\n\n /**\n * Adds an override to the cloudpack config.\n */\n case 'addOverride': {\n // TODO: Send filename from request data to findResolveMapEntry when chromium Issue 1371551 is fixed.\n (async () => {\n const { packageName, importPath } = request.data as AddPackageOverrideInput;\n await addPackageOverride({\n input: { packageName, importPath },\n ctx: { session, bus, packages, taskRunner },\n });\n })().catch(() => {\n // no-op\n });\n break;\n }\n\n case 'validateOverride': {\n // TODO: Get filename from request data when chromium Issue 1371551 is fixed.\n (async () => {\n const input = request.data as ValidatePackageOverrideInput;\n const fixable = await validateOverride(input, { session, packages });\n const result: ValidatePackageOverrideOutput = { fixable };\n sendMessage({ type: 'validateOverride', requestId, data: result });\n })().catch(() => {\n // no-op\n });\n break;\n }\n\n case 'restartAllTasks': {\n console.log('ApiServer: Restarting all tasks');\n\n // Clear entire local cache.\n // eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem\n fsExtra.emptyDirSync(getCachePath());\n\n // All tasks can be removed as notifyReload()\n // will cause the client to add the tasks again.\n allTasks.forEach((_, id) => {\n taskRunner.remove(id);\n });\n\n // Update session version.\n session.incrementSessionVersion();\n\n notifyReload();\n break;\n }\n\n case 'restartTask': {\n const { id, inputPath } = request.data as Record<string, string>;\n console.log(`ApiServer: Restarting task ${id}`);\n taskRunner.remove(id);\n session.incrementTargetVersion(inputPath);\n notifyReload();\n break;\n }\n\n case 'reportMetric': {\n reportMetric({ input: request.data as ReportMetricInput, ctx: { telemetryClient } });\n break;\n }\n\n case 'getSessionId': {\n sendMessage({ type: 'sessionId', requestId, data: { sessionId: session.id } });\n break;\n }\n }\n } catch (err) {\n console.error('ApiServer: error handling message');\n console.error('Error:', (err as Error).stack || err);\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n console.error('Message:', rawData.toString());\n }\n })\n .on('close', () => {\n for (const d of disposables.values()) {\n d();\n }\n });\n });\n\n const notifyReload = () => {\n session.sequence++;\n socketServer.clients.forEach((socket: WebSocket) => {\n if (socket.readyState === WebSocket.OPEN) {\n socket.send(\n JSON.stringify({\n type: 'reload',\n data: { sessionId: session.id },\n }),\n );\n }\n });\n };\n\n bus.subscribe(reloadCountSource, notifyReload);\n\n return {\n url: `${protocol}://${host}:${port}`,\n port,\n close: () =>\n new Promise<void>((resolve, reject) => {\n socketServer.clients.forEach((socket: WebSocket) => socket.terminate());\n socketServer.close((err) => (err ? reject(err) : resolve()));\n server.close();\n }),\n };\n}\n"]}