@communities-webruntime/services
Version:
If you would like to run Lightning Web Runtime without the CLI, we expose some of our programmatic APIs available in Node.js. If you're looking for the CLI documentation [you can find that here](https://www.npmjs.com/package/@communities-webruntime/cli).
96 lines • 3.38 kB
JavaScript
/**
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import 'colors';
import crypto from 'crypto';
import { assert } from '../utils/assert.js';
import folderHash from '../utils/observable-folder-hash.js';
// eslint-disable-next-line import/namespace
import * as fs from '../utils/filesystem.js';
import WebruntimeContext from './webruntime-context.js';
const { log } = console;
const state = {
currentContext: null,
};
const startContextCallbacks = [];
export class ContextService {
static async shutdown() {
await ContextService.endContext();
}
/**
* Start the Web Runtime context and compute the template version key
* based on the given configuration by computing a hash for srcDir
* and watching it for changes.
*
* @public
* @param {Object} config The template configuration
*/
static async startContext(config) {
assert(!state.currentContext, 'Context already started');
const context = (state.currentContext = new WebruntimeContext(config));
const sourcePath = context.srcDir;
return folderHash(sourcePath)
.then((observable) => {
state.folderHashSubscription = observable.subscribe({
next(hash) {
// include folder mtime so that the returned hash changes
// when the folder is touched, this is useful for tests
const { mtime } = fs.statSync(sourcePath); // eslint-disable-line import/namespace
const versionKey = crypto
.createHash('md5')
.update(hash + mtime)
.digest('hex')
.substring(0, 10);
if (!('versionKey' in context) || context.versionKey !== versionKey) {
log(`Created template version hash: ${versionKey}`.cyan);
context.versionKey = versionKey;
}
},
});
})
.then(() => {
// notify people waiting for the context
startContextCallbacks
.splice(0, startContextCallbacks.length)
.forEach((callback) => callback.call(null, context));
return context;
});
}
/**
* Returns the current context
* @public
*/
static getContext() {
if (state.currentContext != null) {
return state.currentContext;
}
throw new Error('Context not started');
}
/**
* Returns the current context
* @public
*/
static async waitForContext() {
if (state.currentContext) {
return ContextService.getContext();
}
return new Promise((resolve) => {
startContextCallbacks.push(resolve);
});
}
/**
* Ends the current context and stops watching srcDir for changes.
* @public
*/
static endContext() {
if (state.folderHashSubscription) {
state.folderHashSubscription.unsubscribe();
state.folderHashSubscription = null;
}
state.currentContext = null;
}
}
//# sourceMappingURL=context-service.js.map