@backstage/plugin-app-backend 0.3.42 → 0.3.43-next.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.
- package/CHANGELOG.md +12 -0
- package/alpha/package.json +3 -3
- package/dist/alpha.cjs.js +326 -0
- package/dist/alpha.cjs.js.map +1 -0
- package/dist/{index.beta.d.ts → alpha.d.ts} +21 -33
- package/dist/index.cjs.js +0 -34
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +5 -17
- package/package.json +25 -15
- package/dist/index.alpha.d.ts +0 -105
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @backstage/plugin-app-backend
|
|
2
2
|
|
|
3
|
+
## 0.3.43-next.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 928a12a9b3: Internal refactor of `/alpha` exports.
|
|
8
|
+
- Updated dependencies
|
|
9
|
+
- @backstage/backend-plugin-api@0.4.1-next.0
|
|
10
|
+
- @backstage/backend-common@0.18.3-next.0
|
|
11
|
+
- @backstage/config@1.0.6
|
|
12
|
+
- @backstage/config-loader@1.1.8
|
|
13
|
+
- @backstage/types@1.0.2
|
|
14
|
+
|
|
3
15
|
## 0.3.42
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
package/alpha/package.json
CHANGED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
6
|
+
var backendCommon = require('@backstage/backend-common');
|
|
7
|
+
var helmet = require('helmet');
|
|
8
|
+
var express = require('express');
|
|
9
|
+
var Router = require('express-promise-router');
|
|
10
|
+
var fs = require('fs-extra');
|
|
11
|
+
var path = require('path');
|
|
12
|
+
var configLoader = require('@backstage/config-loader');
|
|
13
|
+
var luxon = require('luxon');
|
|
14
|
+
var partition = require('lodash/partition');
|
|
15
|
+
var globby = require('globby');
|
|
16
|
+
|
|
17
|
+
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
18
|
+
|
|
19
|
+
var helmet__default = /*#__PURE__*/_interopDefaultLegacy(helmet);
|
|
20
|
+
var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
|
|
21
|
+
var Router__default = /*#__PURE__*/_interopDefaultLegacy(Router);
|
|
22
|
+
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
|
23
|
+
var partition__default = /*#__PURE__*/_interopDefaultLegacy(partition);
|
|
24
|
+
var globby__default = /*#__PURE__*/_interopDefaultLegacy(globby);
|
|
25
|
+
|
|
26
|
+
async function injectConfig(options) {
|
|
27
|
+
const { staticDir, logger, appConfigs } = options;
|
|
28
|
+
const files = await fs__default["default"].readdir(staticDir);
|
|
29
|
+
const jsFiles = files.filter((file) => file.endsWith(".js"));
|
|
30
|
+
const escapedData = JSON.stringify(appConfigs).replace(/("|'|\\)/g, "\\$1");
|
|
31
|
+
const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/"${escapedData}"/*__INJECTED_END__*/`;
|
|
32
|
+
for (const jsFile of jsFiles) {
|
|
33
|
+
const path$1 = path.resolve(staticDir, jsFile);
|
|
34
|
+
const content = await fs__default["default"].readFile(path$1, "utf8");
|
|
35
|
+
if (content.includes("__APP_INJECTED_RUNTIME_CONFIG__")) {
|
|
36
|
+
logger.info(`Injecting env config into ${jsFile}`);
|
|
37
|
+
const newContent = content.replace(
|
|
38
|
+
'"__APP_INJECTED_RUNTIME_CONFIG__"',
|
|
39
|
+
injected
|
|
40
|
+
);
|
|
41
|
+
await fs__default["default"].writeFile(path$1, newContent, "utf8");
|
|
42
|
+
return;
|
|
43
|
+
} else if (content.includes("__APP_INJECTED_CONFIG_MARKER__")) {
|
|
44
|
+
logger.info(`Replacing injected env config in ${jsFile}`);
|
|
45
|
+
const newContent = content.replace(
|
|
46
|
+
/\/\*__APP_INJECTED_CONFIG_MARKER__\*\/.*\/\*__INJECTED_END__\*\//,
|
|
47
|
+
injected
|
|
48
|
+
);
|
|
49
|
+
await fs__default["default"].writeFile(path$1, newContent, "utf8");
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
logger.info("Env config not injected");
|
|
54
|
+
}
|
|
55
|
+
async function readConfigs(options) {
|
|
56
|
+
const { env, appDistDir, config } = options;
|
|
57
|
+
const appConfigs = configLoader.readEnvConfig(env);
|
|
58
|
+
const schemaPath = path.resolve(appDistDir, ".config-schema.json");
|
|
59
|
+
if (await fs__default["default"].pathExists(schemaPath)) {
|
|
60
|
+
const serializedSchema = await fs__default["default"].readJson(schemaPath);
|
|
61
|
+
try {
|
|
62
|
+
const schema = await configLoader.loadConfigSchema({ serialized: serializedSchema });
|
|
63
|
+
const frontendConfigs = await schema.process(
|
|
64
|
+
[{ data: config.get(), context: "app" }],
|
|
65
|
+
{ visibility: ["frontend"], withDeprecatedKeys: true }
|
|
66
|
+
);
|
|
67
|
+
appConfigs.push(...frontendConfigs);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
`Invalid app bundle schema. If this error is unexpected you need to run \`yarn build\` in the app. If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. Caused by the following schema error, ${error}`
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return appConfigs;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
var __accessCheck = (obj, member, msg) => {
|
|
78
|
+
if (!member.has(obj))
|
|
79
|
+
throw TypeError("Cannot " + msg);
|
|
80
|
+
};
|
|
81
|
+
var __privateGet = (obj, member, getter) => {
|
|
82
|
+
__accessCheck(obj, member, "read from private field");
|
|
83
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
84
|
+
};
|
|
85
|
+
var __privateAdd = (obj, member, value) => {
|
|
86
|
+
if (member.has(obj))
|
|
87
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
88
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
89
|
+
};
|
|
90
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
91
|
+
__accessCheck(obj, member, "write to private field");
|
|
92
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
93
|
+
return value;
|
|
94
|
+
};
|
|
95
|
+
var _db, _logger;
|
|
96
|
+
const migrationsDir = backendCommon.resolvePackagePath(
|
|
97
|
+
"@backstage/plugin-app-backend",
|
|
98
|
+
"migrations"
|
|
99
|
+
);
|
|
100
|
+
const _StaticAssetsStore = class {
|
|
101
|
+
constructor(client, logger) {
|
|
102
|
+
__privateAdd(this, _db, void 0);
|
|
103
|
+
__privateAdd(this, _logger, void 0);
|
|
104
|
+
__privateSet(this, _db, client);
|
|
105
|
+
__privateSet(this, _logger, logger);
|
|
106
|
+
}
|
|
107
|
+
static async create(options) {
|
|
108
|
+
var _a;
|
|
109
|
+
const { database } = options;
|
|
110
|
+
const client = await database.getClient();
|
|
111
|
+
if (!((_a = database.migrations) == null ? void 0 : _a.skip)) {
|
|
112
|
+
await client.migrate.latest({
|
|
113
|
+
directory: migrationsDir
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return new _StaticAssetsStore(client, options.logger);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Store the provided assets.
|
|
120
|
+
*
|
|
121
|
+
* If an asset for a given path already exists the modification time will be
|
|
122
|
+
* updated, but the contents will not.
|
|
123
|
+
*/
|
|
124
|
+
async storeAssets(assets) {
|
|
125
|
+
const existingRows = await __privateGet(this, _db).call(this, "static_assets_cache").whereIn(
|
|
126
|
+
"path",
|
|
127
|
+
assets.map((a) => a.path)
|
|
128
|
+
);
|
|
129
|
+
const existingAssetPaths = new Set(existingRows.map((r) => r.path));
|
|
130
|
+
const [modified, added] = partition__default["default"](
|
|
131
|
+
assets,
|
|
132
|
+
(asset) => existingAssetPaths.has(asset.path)
|
|
133
|
+
);
|
|
134
|
+
__privateGet(this, _logger).info(
|
|
135
|
+
`Storing ${modified.length} updated assets and ${added.length} new assets`
|
|
136
|
+
);
|
|
137
|
+
await __privateGet(this, _db).call(this, "static_assets_cache").update({
|
|
138
|
+
last_modified_at: __privateGet(this, _db).fn.now()
|
|
139
|
+
}).whereIn(
|
|
140
|
+
"path",
|
|
141
|
+
modified.map((a) => a.path)
|
|
142
|
+
);
|
|
143
|
+
for (const asset of added) {
|
|
144
|
+
await __privateGet(this, _db).call(this, "static_assets_cache").insert({
|
|
145
|
+
path: asset.path,
|
|
146
|
+
content: await asset.content()
|
|
147
|
+
}).onConflict("path").ignore();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Retrieve an asset from the store with the given path.
|
|
152
|
+
*/
|
|
153
|
+
async getAsset(path) {
|
|
154
|
+
const [row] = await __privateGet(this, _db).call(this, "static_assets_cache").where({
|
|
155
|
+
path
|
|
156
|
+
});
|
|
157
|
+
if (!row) {
|
|
158
|
+
return void 0;
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
path: row.path,
|
|
162
|
+
content: row.content,
|
|
163
|
+
lastModifiedAt: typeof row.last_modified_at === "string" ? luxon.DateTime.fromSQL(row.last_modified_at, { zone: "UTC" }).toJSDate() : row.last_modified_at
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Delete any assets from the store whose modification time is older than the max age.
|
|
168
|
+
*/
|
|
169
|
+
async trimAssets(options) {
|
|
170
|
+
const { maxAgeSeconds } = options;
|
|
171
|
+
await __privateGet(this, _db).call(this, "static_assets_cache").where(
|
|
172
|
+
"last_modified_at",
|
|
173
|
+
"<=",
|
|
174
|
+
__privateGet(this, _db).client.config.client.includes("sqlite3") ? __privateGet(this, _db).raw(`datetime('now', ?)`, [`-${maxAgeSeconds} seconds`]) : __privateGet(this, _db).raw(`now() + interval '${-maxAgeSeconds} seconds'`)
|
|
175
|
+
).delete();
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
let StaticAssetsStore = _StaticAssetsStore;
|
|
179
|
+
_db = new WeakMap();
|
|
180
|
+
_logger = new WeakMap();
|
|
181
|
+
|
|
182
|
+
async function findStaticAssets(staticDir) {
|
|
183
|
+
const assetPaths = await globby__default["default"]("**/*", {
|
|
184
|
+
ignore: ["**/*.map"],
|
|
185
|
+
// Ignore source maps since they're quite large
|
|
186
|
+
cwd: staticDir,
|
|
187
|
+
dot: true
|
|
188
|
+
});
|
|
189
|
+
return assetPaths.map((path) => ({
|
|
190
|
+
path,
|
|
191
|
+
content: async () => fs__default["default"].readFile(backendCommon.resolveSafeChildPath(staticDir, path))
|
|
192
|
+
}));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const CACHE_CONTROL_NO_CACHE = "no-store, max-age=0";
|
|
196
|
+
const CACHE_CONTROL_MAX_CACHE = "public, max-age=1209600";
|
|
197
|
+
|
|
198
|
+
function createStaticAssetMiddleware(store) {
|
|
199
|
+
return (req, res, next) => {
|
|
200
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
201
|
+
next();
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
Promise.resolve(
|
|
205
|
+
(async () => {
|
|
206
|
+
const path$1 = req.path.startsWith("/") ? req.path.slice(1) : req.path;
|
|
207
|
+
const asset = await store.getAsset(path$1);
|
|
208
|
+
if (!asset) {
|
|
209
|
+
next();
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const ext = path.extname(asset.path);
|
|
213
|
+
if (ext) {
|
|
214
|
+
res.type(ext);
|
|
215
|
+
} else {
|
|
216
|
+
res.type("bin");
|
|
217
|
+
}
|
|
218
|
+
res.setHeader("Cache-Control", CACHE_CONTROL_MAX_CACHE);
|
|
219
|
+
res.setHeader("Last-Modified", asset.lastModifiedAt.toUTCString());
|
|
220
|
+
res.send(asset.content);
|
|
221
|
+
})()
|
|
222
|
+
).catch(next);
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function createRouter(options) {
|
|
227
|
+
const { config, logger, appPackageName, staticFallbackHandler } = options;
|
|
228
|
+
const appDistDir = backendCommon.resolvePackagePath(appPackageName, "dist");
|
|
229
|
+
const staticDir = path.resolve(appDistDir, "static");
|
|
230
|
+
if (!await fs__default["default"].pathExists(staticDir)) {
|
|
231
|
+
if (process.env.NODE_ENV === "production") {
|
|
232
|
+
logger.error(
|
|
233
|
+
`Can't serve static app content from ${staticDir}, directory doesn't exist`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
return Router__default["default"]();
|
|
237
|
+
}
|
|
238
|
+
logger.info(`Serving static app content from ${appDistDir}`);
|
|
239
|
+
if (!options.disableConfigInjection) {
|
|
240
|
+
const appConfigs = await readConfigs({
|
|
241
|
+
config,
|
|
242
|
+
appDistDir,
|
|
243
|
+
env: process.env
|
|
244
|
+
});
|
|
245
|
+
await injectConfig({ appConfigs, logger, staticDir });
|
|
246
|
+
}
|
|
247
|
+
const router = Router__default["default"]();
|
|
248
|
+
router.use(helmet__default["default"].frameguard({ action: "deny" }));
|
|
249
|
+
const staticRouter = Router__default["default"]();
|
|
250
|
+
staticRouter.use(
|
|
251
|
+
express__default["default"].static(path.resolve(appDistDir, "static"), {
|
|
252
|
+
setHeaders: (res) => {
|
|
253
|
+
res.setHeader("Cache-Control", CACHE_CONTROL_MAX_CACHE);
|
|
254
|
+
}
|
|
255
|
+
})
|
|
256
|
+
);
|
|
257
|
+
if (options.database) {
|
|
258
|
+
const store = await StaticAssetsStore.create({
|
|
259
|
+
logger,
|
|
260
|
+
database: options.database
|
|
261
|
+
});
|
|
262
|
+
const assets = await findStaticAssets(staticDir);
|
|
263
|
+
await store.storeAssets(assets);
|
|
264
|
+
await store.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });
|
|
265
|
+
staticRouter.use(createStaticAssetMiddleware(store));
|
|
266
|
+
}
|
|
267
|
+
if (staticFallbackHandler) {
|
|
268
|
+
staticRouter.use(staticFallbackHandler);
|
|
269
|
+
}
|
|
270
|
+
staticRouter.use(backendCommon.notFoundHandler());
|
|
271
|
+
router.use("/static", staticRouter);
|
|
272
|
+
router.use(
|
|
273
|
+
express__default["default"].static(appDistDir, {
|
|
274
|
+
setHeaders: (res, path) => {
|
|
275
|
+
if (express__default["default"].static.mime.lookup(path) === "text/html") {
|
|
276
|
+
res.setHeader("Cache-Control", CACHE_CONTROL_NO_CACHE);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
})
|
|
280
|
+
);
|
|
281
|
+
router.get("/*", (_req, res) => {
|
|
282
|
+
res.sendFile(path.resolve(appDistDir, "index.html"), {
|
|
283
|
+
headers: {
|
|
284
|
+
// The Cache-Control header instructs the browser to not cache the index.html since it might
|
|
285
|
+
// link to static assets from recently deployed versions.
|
|
286
|
+
"cache-control": CACHE_CONTROL_NO_CACHE
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
return router;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const appPlugin = backendPluginApi.createBackendPlugin((options) => ({
|
|
294
|
+
pluginId: "app",
|
|
295
|
+
register(env) {
|
|
296
|
+
env.registerInit({
|
|
297
|
+
deps: {
|
|
298
|
+
logger: backendPluginApi.coreServices.logger,
|
|
299
|
+
config: backendPluginApi.coreServices.config,
|
|
300
|
+
database: backendPluginApi.coreServices.database,
|
|
301
|
+
httpRouter: backendPluginApi.coreServices.httpRouter
|
|
302
|
+
},
|
|
303
|
+
async init({ logger, config, database, httpRouter }) {
|
|
304
|
+
const {
|
|
305
|
+
appPackageName,
|
|
306
|
+
staticFallbackHandler,
|
|
307
|
+
disableConfigInjection,
|
|
308
|
+
disableStaticFallbackCache
|
|
309
|
+
} = options;
|
|
310
|
+
const winstonLogger = backendCommon.loggerToWinstonLogger(logger);
|
|
311
|
+
const router = await createRouter({
|
|
312
|
+
logger: winstonLogger,
|
|
313
|
+
config,
|
|
314
|
+
database: disableStaticFallbackCache ? void 0 : database,
|
|
315
|
+
appPackageName: appPackageName != null ? appPackageName : "app",
|
|
316
|
+
staticFallbackHandler,
|
|
317
|
+
disableConfigInjection
|
|
318
|
+
});
|
|
319
|
+
httpRouter.use(router);
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
}));
|
|
324
|
+
|
|
325
|
+
exports.appPlugin = appPlugin;
|
|
326
|
+
//# sourceMappingURL=alpha.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"alpha.cjs.js","sources":["../src/lib/config.ts","../src/lib/assets/StaticAssetsStore.ts","../src/lib/assets/findStaticAssets.ts","../src/lib/headers.ts","../src/lib/assets/createStaticAssetMiddleware.ts","../src/service/router.ts","../src/service/appPlugin.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport { loadConfigSchema, readEnvConfig } from '@backstage/config-loader';\n\ntype InjectOptions = {\n appConfigs: AppConfig[];\n // Directory of the static JS files to search for file to inject\n staticDir: string;\n logger: Logger;\n};\n\n/**\n * Injects configs into the app bundle, replacing any existing injected config.\n */\nexport async function injectConfig(options: InjectOptions) {\n const { staticDir, logger, appConfigs } = options;\n\n const files = await fs.readdir(staticDir);\n const jsFiles = files.filter(file => file.endsWith('.js'));\n\n const escapedData = JSON.stringify(appConfigs).replace(/(\"|'|\\\\)/g, '\\\\$1');\n const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/\"${escapedData}\"/*__INJECTED_END__*/`;\n\n for (const jsFile of jsFiles) {\n const path = resolvePath(staticDir, jsFile);\n\n const content = await fs.readFile(path, 'utf8');\n if (content.includes('__APP_INJECTED_RUNTIME_CONFIG__')) {\n logger.info(`Injecting env config into ${jsFile}`);\n\n const newContent = content.replace(\n '\"__APP_INJECTED_RUNTIME_CONFIG__\"',\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n } else if (content.includes('__APP_INJECTED_CONFIG_MARKER__')) {\n logger.info(`Replacing injected env config in ${jsFile}`);\n\n const newContent = content.replace(\n /\\/\\*__APP_INJECTED_CONFIG_MARKER__\\*\\/.*\\/\\*__INJECTED_END__\\*\\//,\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n }\n }\n logger.info('Env config not injected');\n}\n\ntype ReadOptions = {\n env: { [name: string]: string | undefined };\n appDistDir: string;\n config: Config;\n};\n\n/**\n * Read config from environment and process the backend config using the\n * schema that is embedded in the frontend build.\n */\nexport async function readConfigs(options: ReadOptions): Promise<AppConfig[]> {\n const { env, appDistDir, config } = options;\n\n const appConfigs = readEnvConfig(env);\n\n const schemaPath = resolvePath(appDistDir, '.config-schema.json');\n if (await fs.pathExists(schemaPath)) {\n const serializedSchema = await fs.readJson(schemaPath);\n\n try {\n const schema = await loadConfigSchema({ serialized: serializedSchema });\n\n const frontendConfigs = await schema.process(\n [{ data: config.get() as JsonObject, context: 'app' }],\n { visibility: ['frontend'], withDeprecatedKeys: true },\n );\n appConfigs.push(...frontendConfigs);\n } catch (error) {\n throw new Error(\n 'Invalid app bundle schema. If this error is unexpected you need to run `yarn build` in the app. ' +\n `If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. ` +\n `Caused by the following schema error, ${error}`,\n );\n }\n }\n\n return appConfigs;\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Knex } from 'knex';\nimport { Logger } from 'winston';\nimport { DateTime } from 'luxon';\nimport partition from 'lodash/partition';\nimport { StaticAsset, StaticAssetInput, StaticAssetProvider } from './types';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-app-backend',\n 'migrations',\n);\n\ninterface StaticAssetRow {\n path: string;\n content: Buffer;\n last_modified_at: Date;\n}\n\n/** @internal */\nexport interface StaticAssetsStoreOptions {\n database: PluginDatabaseManager;\n logger: Logger;\n}\n\n/**\n * A storage for static assets that are assumed to be immutable.\n *\n * @internal\n */\nexport class StaticAssetsStore implements StaticAssetProvider {\n #db: Knex;\n #logger: Logger;\n\n static async create(options: StaticAssetsStoreOptions) {\n const { database } = options;\n const client = await database.getClient();\n\n if (!database.migrations?.skip) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new StaticAssetsStore(client, options.logger);\n }\n\n private constructor(client: Knex, logger: Logger) {\n this.#db = client;\n this.#logger = logger;\n }\n\n /**\n * Store the provided assets.\n *\n * If an asset for a given path already exists the modification time will be\n * updated, but the contents will not.\n */\n async storeAssets(assets: StaticAssetInput[]) {\n const existingRows = await this.#db<StaticAssetRow>(\n 'static_assets_cache',\n ).whereIn(\n 'path',\n assets.map(a => a.path),\n );\n const existingAssetPaths = new Set(existingRows.map(r => r.path));\n\n const [modified, added] = partition(assets, asset =>\n existingAssetPaths.has(asset.path),\n );\n\n this.#logger.info(\n `Storing ${modified.length} updated assets and ${added.length} new assets`,\n );\n\n await this.#db('static_assets_cache')\n .update({\n last_modified_at: this.#db.fn.now(),\n })\n .whereIn(\n 'path',\n modified.map(a => a.path),\n );\n\n for (const asset of added) {\n // We ignore conflicts with other nodes, it doesn't matter if someone else\n // added the same asset just before us.\n await this.#db('static_assets_cache')\n .insert({\n path: asset.path,\n content: await asset.content(),\n })\n .onConflict('path')\n .ignore();\n }\n }\n\n /**\n * Retrieve an asset from the store with the given path.\n */\n async getAsset(path: string): Promise<StaticAsset | undefined> {\n const [row] = await this.#db<StaticAssetRow>('static_assets_cache').where({\n path,\n });\n if (!row) {\n return undefined;\n }\n return {\n path: row.path,\n content: row.content,\n lastModifiedAt:\n typeof row.last_modified_at === 'string'\n ? DateTime.fromSQL(row.last_modified_at, { zone: 'UTC' }).toJSDate()\n : row.last_modified_at,\n };\n }\n\n /**\n * Delete any assets from the store whose modification time is older than the max age.\n */\n async trimAssets(options: { maxAgeSeconds: number }) {\n const { maxAgeSeconds } = options;\n await this.#db<StaticAssetRow>('static_assets_cache')\n .where(\n 'last_modified_at',\n '<=',\n this.#db.client.config.client.includes('sqlite3')\n ? this.#db.raw(`datetime('now', ?)`, [`-${maxAgeSeconds} seconds`])\n : this.#db.raw(`now() + interval '${-maxAgeSeconds} seconds'`),\n )\n .delete();\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport globby from 'globby';\nimport { StaticAssetInput } from './types';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\n\n/**\n * Finds all static assets within a directory\n *\n * @internal\n */\nexport async function findStaticAssets(\n staticDir: string,\n): Promise<StaticAssetInput[]> {\n const assetPaths = await globby('**/*', {\n ignore: ['**/*.map'], // Ignore source maps since they're quite large\n cwd: staticDir,\n dot: true,\n });\n\n return assetPaths.map(path => ({\n path,\n content: async () => fs.readFile(resolveSafeChildPath(staticDir, path)),\n }));\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const CACHE_CONTROL_NO_CACHE = 'no-store, max-age=0';\nexport const CACHE_CONTROL_MAX_CACHE = 'public, max-age=1209600'; // 14 days\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extname } from 'path';\nimport { RequestHandler } from 'express';\nimport { StaticAssetProvider } from './types';\nimport { CACHE_CONTROL_MAX_CACHE } from '../headers';\n\n/**\n * Creates a middleware that serves static assets from a static asset provider\n *\n * @internal\n */\nexport function createStaticAssetMiddleware(\n store: StaticAssetProvider,\n): RequestHandler {\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n next();\n return;\n }\n\n // Let's not assume we're in promise-router\n Promise.resolve(\n (async () => {\n // Drop leading slashes from the incoming path\n const path = req.path.startsWith('/') ? req.path.slice(1) : req.path;\n\n const asset = await store.getAsset(path);\n if (!asset) {\n next();\n return;\n }\n\n // Set the Content-Type header, falling back to octet-stream\n const ext = extname(asset.path);\n if (ext) {\n res.type(ext);\n } else {\n res.type('bin');\n }\n\n // Same as our express.static override\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n res.setHeader('Last-Modified', asset.lastModifiedAt.toUTCString());\n\n res.send(asset.content);\n })(),\n ).catch(next);\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n notFoundHandler,\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport helmet from 'helmet';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { injectConfig, readConfigs } from '../lib/config';\nimport {\n StaticAssetsStore,\n findStaticAssets,\n createStaticAssetMiddleware,\n} from '../lib/assets';\nimport {\n CACHE_CONTROL_MAX_CACHE,\n CACHE_CONTROL_NO_CACHE,\n} from '../lib/headers';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\n/** @public */\nexport interface RouterOptions {\n config: Config;\n logger: Logger;\n\n /**\n * If a database is provided it will be used to cache previously deployed static assets.\n *\n * This is a built-in alternative to using a `staticFallbackHandler`.\n */\n database?: PluginDatabaseManager;\n\n /**\n * The name of the app package that content should be served from. The same app package should be\n * added as a dependency to the backend package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package this would be set to 'app'.\n */\n appPackageName: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n *\n * Another option is to provide a `database` that will take care of storing the static assets instead.\n *\n * If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve\n * static assets first, and if they are not found, the `staticFallbackHandler` will be called.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n}\n\n/** @public */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { config, logger, appPackageName, staticFallbackHandler } = options;\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n if (process.env.NODE_ENV === 'production') {\n logger.error(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n }\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n if (!options.disableConfigInjection) {\n const appConfigs = await readConfigs({\n config,\n appDistDir,\n env: process.env,\n });\n\n await injectConfig({ appConfigs, logger, staticDir });\n }\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\n\n // Use a separate router for static content so that a fallback can be provided by backend\n const staticRouter = Router();\n staticRouter.use(\n express.static(resolvePath(appDistDir, 'static'), {\n setHeaders: res => {\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n },\n }),\n );\n\n if (options.database) {\n const store = await StaticAssetsStore.create({\n logger,\n database: options.database,\n });\n\n const assets = await findStaticAssets(staticDir);\n await store.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await store.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(store));\n }\n\n if (staticFallbackHandler) {\n staticRouter.use(staticFallbackHandler);\n }\n staticRouter.use(notFoundHandler());\n\n router.use('/static', staticRouter);\n router.use(\n express.static(appDistDir, {\n setHeaders: (res, path) => {\n // The Cache-Control header instructs the browser to not cache html files since it might\n // link to static assets from recently deployed versions.\n if (\n (express.static.mime as unknown as Mime).lookup(path) === 'text/html'\n ) {\n res.setHeader('Cache-Control', CACHE_CONTROL_NO_CACHE);\n }\n },\n }),\n );\n router.get('/*', (_req, res) => {\n res.sendFile(resolvePath(appDistDir, 'index.html'), {\n headers: {\n // The Cache-Control header instructs the browser to not cache the index.html since it might\n // link to static assets from recently deployed versions.\n 'cache-control': CACHE_CONTROL_NO_CACHE,\n },\n });\n });\n\n return router;\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport { createRouter } from './router';\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\n\n/** @alpha */\nexport type AppPluginOptions = {\n /**\n * The name of the app package (in most Backstage repositories, this is the\n * \"name\" field in `packages/app/package.json`) that content should be served\n * from. The same app package should be added as a dependency to the backend\n * package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package, this will default to 'app'.\n */\n appPackageName?: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n *\n * Another option is to provide a `database` that will take care of storing the static assets instead.\n *\n * If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve\n * static assets first, and if they are not found, the `staticFallbackHandler` will be called.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n\n /**\n * By default the app backend plugin will cache previously deployed static assets in the database.\n * If you disable this, it is recommended to set a `staticFallbackHandler` instead.\n */\n disableStaticFallbackCache?: boolean;\n};\n\n/**\n * The App plugin is responsible for serving the frontend app bundle and static assets.\n * @alpha\n */\nexport const appPlugin = createBackendPlugin((options: AppPluginOptions) => ({\n pluginId: 'app',\n register(env) {\n env.registerInit({\n deps: {\n logger: coreServices.logger,\n config: coreServices.config,\n database: coreServices.database,\n httpRouter: coreServices.httpRouter,\n },\n async init({ logger, config, database, httpRouter }) {\n const {\n appPackageName,\n staticFallbackHandler,\n disableConfigInjection,\n disableStaticFallbackCache,\n } = options;\n const winstonLogger = loggerToWinstonLogger(logger);\n\n const router = await createRouter({\n logger: winstonLogger,\n config,\n database: disableStaticFallbackCache ? undefined : database,\n appPackageName: appPackageName ?? 'app',\n staticFallbackHandler,\n disableConfigInjection,\n });\n httpRouter.use(router);\n },\n });\n },\n}));\n"],"names":["fs","path","resolvePath","readEnvConfig","loadConfigSchema","resolvePackagePath","partition","DateTime","globby","resolveSafeChildPath","extname","Router","helmet","express","notFoundHandler","createBackendPlugin","coreServices","loggerToWinstonLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,eAAsB,aAAa,OAAwB,EAAA;AACzD,EAAA,MAAM,EAAE,SAAA,EAAW,MAAQ,EAAA,UAAA,EAAe,GAAA,OAAA,CAAA;AAE1C,EAAA,MAAM,KAAQ,GAAA,MAAMA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,QAAM,MAAA,aAAA,GAAgBC,oCAAsB,MAAM,CAAA,CAAA;AAElD,QAAM,MAAA,MAAA,GAAS,MAAM,YAAa,CAAA;AAAA,UAChC,MAAQ,EAAA,aAAA;AAAA,UACR,MAAA;AAAA,UACA,QAAA,EAAU,6BAA6B,KAAY,CAAA,GAAA,QAAA;AAAA,UACnD,gBAAgB,cAAkB,IAAA,IAAA,GAAA,cAAA,GAAA,KAAA;AAAA,UAClC,qBAAA;AAAA,UACA,sBAAA;AAAA,SACD,CAAA,CAAA;AACD,QAAA,UAAA,CAAW,IAAI,MAAM,CAAA,CAAA;AAAA,OACvB;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAE,CAAA;;;;"}
|
|
@@ -1,39 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
* A Backstage backend plugin that serves the Backstage frontend app
|
|
3
|
-
*
|
|
4
|
-
* @packageDocumentation
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { BackendFeature } from '@backstage/backend-plugin-api';
|
|
8
|
-
import { Config } from '@backstage/config';
|
|
1
|
+
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
|
|
9
2
|
import express from 'express';
|
|
10
|
-
import { Logger } from 'winston';
|
|
11
|
-
import { PluginDatabaseManager } from '@backstage/backend-common';
|
|
12
|
-
|
|
13
|
-
/* Excluded from this release type: appPlugin */
|
|
14
3
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
/** @public */
|
|
18
|
-
export declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
19
|
-
|
|
20
|
-
/** @public */
|
|
21
|
-
export declare interface RouterOptions {
|
|
22
|
-
config: Config;
|
|
23
|
-
logger: Logger;
|
|
4
|
+
/** @alpha */
|
|
5
|
+
declare type AppPluginOptions = {
|
|
24
6
|
/**
|
|
25
|
-
*
|
|
7
|
+
* The name of the app package (in most Backstage repositories, this is the
|
|
8
|
+
* "name" field in `packages/app/package.json`) that content should be served
|
|
9
|
+
* from. The same app package should be added as a dependency to the backend
|
|
10
|
+
* package in order for it to be accessible at runtime.
|
|
26
11
|
*
|
|
27
|
-
*
|
|
12
|
+
* In a typical setup with a single app package, this will default to 'app'.
|
|
28
13
|
*/
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* The name of the app package that content should be served from. The same app package should be
|
|
32
|
-
* added as a dependency to the backend package in order for it to be accessible at runtime.
|
|
33
|
-
*
|
|
34
|
-
* In a typical setup with a single app package this would be set to 'app'.
|
|
35
|
-
*/
|
|
36
|
-
appPackageName: string;
|
|
14
|
+
appPackageName?: string;
|
|
37
15
|
/**
|
|
38
16
|
* A request handler to handle requests for static content that are not present in the app bundle.
|
|
39
17
|
*
|
|
@@ -57,6 +35,16 @@ export declare interface RouterOptions {
|
|
|
57
35
|
* This also disables configuration injection though `APP_CONFIG_` environment variables.
|
|
58
36
|
*/
|
|
59
37
|
disableConfigInjection?: boolean;
|
|
60
|
-
|
|
38
|
+
/**
|
|
39
|
+
* By default the app backend plugin will cache previously deployed static assets in the database.
|
|
40
|
+
* If you disable this, it is recommended to set a `staticFallbackHandler` instead.
|
|
41
|
+
*/
|
|
42
|
+
disableStaticFallbackCache?: boolean;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* The App plugin is responsible for serving the frontend app bundle and static assets.
|
|
46
|
+
* @alpha
|
|
47
|
+
*/
|
|
48
|
+
declare const appPlugin: (options: AppPluginOptions) => _backstage_backend_plugin_api.BackendFeature;
|
|
61
49
|
|
|
62
|
-
export { }
|
|
50
|
+
export { AppPluginOptions, appPlugin };
|
package/dist/index.cjs.js
CHANGED
|
@@ -12,7 +12,6 @@ var configLoader = require('@backstage/config-loader');
|
|
|
12
12
|
var luxon = require('luxon');
|
|
13
13
|
var partition = require('lodash/partition');
|
|
14
14
|
var globby = require('globby');
|
|
15
|
-
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
16
15
|
|
|
17
16
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
18
17
|
|
|
@@ -290,38 +289,5 @@ async function createRouter(options) {
|
|
|
290
289
|
return router;
|
|
291
290
|
}
|
|
292
291
|
|
|
293
|
-
const appPlugin = backendPluginApi.createBackendPlugin((options) => ({
|
|
294
|
-
pluginId: "app",
|
|
295
|
-
register(env) {
|
|
296
|
-
env.registerInit({
|
|
297
|
-
deps: {
|
|
298
|
-
logger: backendPluginApi.coreServices.logger,
|
|
299
|
-
config: backendPluginApi.coreServices.config,
|
|
300
|
-
database: backendPluginApi.coreServices.database,
|
|
301
|
-
httpRouter: backendPluginApi.coreServices.httpRouter
|
|
302
|
-
},
|
|
303
|
-
async init({ logger, config, database, httpRouter }) {
|
|
304
|
-
const {
|
|
305
|
-
appPackageName,
|
|
306
|
-
staticFallbackHandler,
|
|
307
|
-
disableConfigInjection,
|
|
308
|
-
disableStaticFallbackCache
|
|
309
|
-
} = options;
|
|
310
|
-
const winstonLogger = backendCommon.loggerToWinstonLogger(logger);
|
|
311
|
-
const router = await createRouter({
|
|
312
|
-
logger: winstonLogger,
|
|
313
|
-
config,
|
|
314
|
-
database: disableStaticFallbackCache ? void 0 : database,
|
|
315
|
-
appPackageName: appPackageName != null ? appPackageName : "app",
|
|
316
|
-
staticFallbackHandler,
|
|
317
|
-
disableConfigInjection
|
|
318
|
-
});
|
|
319
|
-
httpRouter.use(router);
|
|
320
|
-
}
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
}));
|
|
324
|
-
|
|
325
|
-
exports.appPlugin = appPlugin;
|
|
326
292
|
exports.createRouter = createRouter;
|
|
327
293
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/lib/config.ts","../src/lib/assets/StaticAssetsStore.ts","../src/lib/assets/findStaticAssets.ts","../src/lib/headers.ts","../src/lib/assets/createStaticAssetMiddleware.ts","../src/service/router.ts","../src/service/appPlugin.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport { loadConfigSchema, readEnvConfig } from '@backstage/config-loader';\n\ntype InjectOptions = {\n appConfigs: AppConfig[];\n // Directory of the static JS files to search for file to inject\n staticDir: string;\n logger: Logger;\n};\n\n/**\n * Injects configs into the app bundle, replacing any existing injected config.\n */\nexport async function injectConfig(options: InjectOptions) {\n const { staticDir, logger, appConfigs } = options;\n\n const files = await fs.readdir(staticDir);\n const jsFiles = files.filter(file => file.endsWith('.js'));\n\n const escapedData = JSON.stringify(appConfigs).replace(/(\"|'|\\\\)/g, '\\\\$1');\n const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/\"${escapedData}\"/*__INJECTED_END__*/`;\n\n for (const jsFile of jsFiles) {\n const path = resolvePath(staticDir, jsFile);\n\n const content = await fs.readFile(path, 'utf8');\n if (content.includes('__APP_INJECTED_RUNTIME_CONFIG__')) {\n logger.info(`Injecting env config into ${jsFile}`);\n\n const newContent = content.replace(\n '\"__APP_INJECTED_RUNTIME_CONFIG__\"',\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n } else if (content.includes('__APP_INJECTED_CONFIG_MARKER__')) {\n logger.info(`Replacing injected env config in ${jsFile}`);\n\n const newContent = content.replace(\n /\\/\\*__APP_INJECTED_CONFIG_MARKER__\\*\\/.*\\/\\*__INJECTED_END__\\*\\//,\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n }\n }\n logger.info('Env config not injected');\n}\n\ntype ReadOptions = {\n env: { [name: string]: string | undefined };\n appDistDir: string;\n config: Config;\n};\n\n/**\n * Read config from environment and process the backend config using the\n * schema that is embedded in the frontend build.\n */\nexport async function readConfigs(options: ReadOptions): Promise<AppConfig[]> {\n const { env, appDistDir, config } = options;\n\n const appConfigs = readEnvConfig(env);\n\n const schemaPath = resolvePath(appDistDir, '.config-schema.json');\n if (await fs.pathExists(schemaPath)) {\n const serializedSchema = await fs.readJson(schemaPath);\n\n try {\n const schema = await loadConfigSchema({ serialized: serializedSchema });\n\n const frontendConfigs = await schema.process(\n [{ data: config.get() as JsonObject, context: 'app' }],\n { visibility: ['frontend'], withDeprecatedKeys: true },\n );\n appConfigs.push(...frontendConfigs);\n } catch (error) {\n throw new Error(\n 'Invalid app bundle schema. If this error is unexpected you need to run `yarn build` in the app. ' +\n `If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. ` +\n `Caused by the following schema error, ${error}`,\n );\n }\n }\n\n return appConfigs;\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Knex } from 'knex';\nimport { Logger } from 'winston';\nimport { DateTime } from 'luxon';\nimport partition from 'lodash/partition';\nimport { StaticAsset, StaticAssetInput, StaticAssetProvider } from './types';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-app-backend',\n 'migrations',\n);\n\ninterface StaticAssetRow {\n path: string;\n content: Buffer;\n last_modified_at: Date;\n}\n\n/** @internal */\nexport interface StaticAssetsStoreOptions {\n database: PluginDatabaseManager;\n logger: Logger;\n}\n\n/**\n * A storage for static assets that are assumed to be immutable.\n *\n * @internal\n */\nexport class StaticAssetsStore implements StaticAssetProvider {\n #db: Knex;\n #logger: Logger;\n\n static async create(options: StaticAssetsStoreOptions) {\n const { database } = options;\n const client = await database.getClient();\n\n if (!database.migrations?.skip) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new StaticAssetsStore(client, options.logger);\n }\n\n private constructor(client: Knex, logger: Logger) {\n this.#db = client;\n this.#logger = logger;\n }\n\n /**\n * Store the provided assets.\n *\n * If an asset for a given path already exists the modification time will be\n * updated, but the contents will not.\n */\n async storeAssets(assets: StaticAssetInput[]) {\n const existingRows = await this.#db<StaticAssetRow>(\n 'static_assets_cache',\n ).whereIn(\n 'path',\n assets.map(a => a.path),\n );\n const existingAssetPaths = new Set(existingRows.map(r => r.path));\n\n const [modified, added] = partition(assets, asset =>\n existingAssetPaths.has(asset.path),\n );\n\n this.#logger.info(\n `Storing ${modified.length} updated assets and ${added.length} new assets`,\n );\n\n await this.#db('static_assets_cache')\n .update({\n last_modified_at: this.#db.fn.now(),\n })\n .whereIn(\n 'path',\n modified.map(a => a.path),\n );\n\n for (const asset of added) {\n // We ignore conflicts with other nodes, it doesn't matter if someone else\n // added the same asset just before us.\n await this.#db('static_assets_cache')\n .insert({\n path: asset.path,\n content: await asset.content(),\n })\n .onConflict('path')\n .ignore();\n }\n }\n\n /**\n * Retrieve an asset from the store with the given path.\n */\n async getAsset(path: string): Promise<StaticAsset | undefined> {\n const [row] = await this.#db<StaticAssetRow>('static_assets_cache').where({\n path,\n });\n if (!row) {\n return undefined;\n }\n return {\n path: row.path,\n content: row.content,\n lastModifiedAt:\n typeof row.last_modified_at === 'string'\n ? DateTime.fromSQL(row.last_modified_at, { zone: 'UTC' }).toJSDate()\n : row.last_modified_at,\n };\n }\n\n /**\n * Delete any assets from the store whose modification time is older than the max age.\n */\n async trimAssets(options: { maxAgeSeconds: number }) {\n const { maxAgeSeconds } = options;\n await this.#db<StaticAssetRow>('static_assets_cache')\n .where(\n 'last_modified_at',\n '<=',\n this.#db.client.config.client.includes('sqlite3')\n ? this.#db.raw(`datetime('now', ?)`, [`-${maxAgeSeconds} seconds`])\n : this.#db.raw(`now() + interval '${-maxAgeSeconds} seconds'`),\n )\n .delete();\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport globby from 'globby';\nimport { StaticAssetInput } from './types';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\n\n/**\n * Finds all static assets within a directory\n *\n * @internal\n */\nexport async function findStaticAssets(\n staticDir: string,\n): Promise<StaticAssetInput[]> {\n const assetPaths = await globby('**/*', {\n ignore: ['**/*.map'], // Ignore source maps since they're quite large\n cwd: staticDir,\n dot: true,\n });\n\n return assetPaths.map(path => ({\n path,\n content: async () => fs.readFile(resolveSafeChildPath(staticDir, path)),\n }));\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const CACHE_CONTROL_NO_CACHE = 'no-store, max-age=0';\nexport const CACHE_CONTROL_MAX_CACHE = 'public, max-age=1209600'; // 14 days\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extname } from 'path';\nimport { RequestHandler } from 'express';\nimport { StaticAssetProvider } from './types';\nimport { CACHE_CONTROL_MAX_CACHE } from '../headers';\n\n/**\n * Creates a middleware that serves static assets from a static asset provider\n *\n * @internal\n */\nexport function createStaticAssetMiddleware(\n store: StaticAssetProvider,\n): RequestHandler {\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n next();\n return;\n }\n\n // Let's not assume we're in promise-router\n Promise.resolve(\n (async () => {\n // Drop leading slashes from the incoming path\n const path = req.path.startsWith('/') ? req.path.slice(1) : req.path;\n\n const asset = await store.getAsset(path);\n if (!asset) {\n next();\n return;\n }\n\n // Set the Content-Type header, falling back to octet-stream\n const ext = extname(asset.path);\n if (ext) {\n res.type(ext);\n } else {\n res.type('bin');\n }\n\n // Same as our express.static override\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n res.setHeader('Last-Modified', asset.lastModifiedAt.toUTCString());\n\n res.send(asset.content);\n })(),\n ).catch(next);\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n notFoundHandler,\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport helmet from 'helmet';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { injectConfig, readConfigs } from '../lib/config';\nimport {\n StaticAssetsStore,\n findStaticAssets,\n createStaticAssetMiddleware,\n} from '../lib/assets';\nimport {\n CACHE_CONTROL_MAX_CACHE,\n CACHE_CONTROL_NO_CACHE,\n} from '../lib/headers';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\n/** @public */\nexport interface RouterOptions {\n config: Config;\n logger: Logger;\n\n /**\n * If a database is provided it will be used to cache previously deployed static assets.\n *\n * This is a built-in alternative to using a `staticFallbackHandler`.\n */\n database?: PluginDatabaseManager;\n\n /**\n * The name of the app package that content should be served from. The same app package should be\n * added as a dependency to the backend package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package this would be set to 'app'.\n */\n appPackageName: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n *\n * Another option is to provide a `database` that will take care of storing the static assets instead.\n *\n * If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve\n * static assets first, and if they are not found, the `staticFallbackHandler` will be called.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n}\n\n/** @public */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { config, logger, appPackageName, staticFallbackHandler } = options;\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n if (process.env.NODE_ENV === 'production') {\n logger.error(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n }\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n if (!options.disableConfigInjection) {\n const appConfigs = await readConfigs({\n config,\n appDistDir,\n env: process.env,\n });\n\n await injectConfig({ appConfigs, logger, staticDir });\n }\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\n\n // Use a separate router for static content so that a fallback can be provided by backend\n const staticRouter = Router();\n staticRouter.use(\n express.static(resolvePath(appDistDir, 'static'), {\n setHeaders: res => {\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n },\n }),\n );\n\n if (options.database) {\n const store = await StaticAssetsStore.create({\n logger,\n database: options.database,\n });\n\n const assets = await findStaticAssets(staticDir);\n await store.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await store.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(store));\n }\n\n if (staticFallbackHandler) {\n staticRouter.use(staticFallbackHandler);\n }\n staticRouter.use(notFoundHandler());\n\n router.use('/static', staticRouter);\n router.use(\n express.static(appDistDir, {\n setHeaders: (res, path) => {\n // The Cache-Control header instructs the browser to not cache html files since it might\n // link to static assets from recently deployed versions.\n if (\n (express.static.mime as unknown as Mime).lookup(path) === 'text/html'\n ) {\n res.setHeader('Cache-Control', CACHE_CONTROL_NO_CACHE);\n }\n },\n }),\n );\n router.get('/*', (_req, res) => {\n res.sendFile(resolvePath(appDistDir, 'index.html'), {\n headers: {\n // The Cache-Control header instructs the browser to not cache the index.html since it might\n // link to static assets from recently deployed versions.\n 'cache-control': CACHE_CONTROL_NO_CACHE,\n },\n });\n });\n\n return router;\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport { createRouter } from './router';\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\n\n/** @alpha */\nexport type AppPluginOptions = {\n /**\n * The name of the app package (in most Backstage repositories, this is the\n * \"name\" field in `packages/app/package.json`) that content should be served\n * from. The same app package should be added as a dependency to the backend\n * package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package, this will default to 'app'.\n */\n appPackageName?: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n *\n * Another option is to provide a `database` that will take care of storing the static assets instead.\n *\n * If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve\n * static assets first, and if they are not found, the `staticFallbackHandler` will be called.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n\n /**\n * By default the app backend plugin will cache previously deployed static assets in the database.\n * If you disable this, it is recommended to set a `staticFallbackHandler` instead.\n */\n disableStaticFallbackCache?: boolean;\n};\n\n/**\n * The App plugin is responsible for serving the frontend app bundle and static assets.\n * @alpha\n */\nexport const appPlugin = createBackendPlugin((options: AppPluginOptions) => ({\n pluginId: 'app',\n register(env) {\n env.registerInit({\n deps: {\n logger: coreServices.logger,\n config: coreServices.config,\n database: coreServices.database,\n httpRouter: coreServices.httpRouter,\n },\n async init({ logger, config, database, httpRouter }) {\n const {\n appPackageName,\n staticFallbackHandler,\n disableConfigInjection,\n disableStaticFallbackCache,\n } = options;\n const winstonLogger = loggerToWinstonLogger(logger);\n\n const router = await createRouter({\n logger: winstonLogger,\n config,\n database: disableStaticFallbackCache ? undefined : database,\n appPackageName: appPackageName ?? 'app',\n staticFallbackHandler,\n disableConfigInjection,\n });\n httpRouter.use(router);\n },\n });\n },\n}));\n"],"names":["fs","path","resolvePath","readEnvConfig","loadConfigSchema","resolvePackagePath","partition","DateTime","globby","resolveSafeChildPath","extname","Router","helmet","express","notFoundHandler","createBackendPlugin","coreServices","loggerToWinstonLogger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,eAAsB,aAAa,OAAwB,EAAA;AACzD,EAAA,MAAM,EAAE,SAAA,EAAW,MAAQ,EAAA,UAAA,EAAe,GAAA,OAAA,CAAA;AAE1C,EAAA,MAAM,KAAQ,GAAA,MAAMA,sBAAG,CAAA,OAAA,CAAQ,SAAS,CAAA,CAAA;AACxC,EAAA,MAAM,UAAU,KAAM,CAAA,MAAA,CAAO,UAAQ,IAAK,CAAA,QAAA,CAAS,KAAK,CAAC,CAAA,CAAA;AAEzD,EAAA,MAAM,cAAc,IAAK,CAAA,SAAA,CAAU,UAAU,CAAE,CAAA,OAAA,CAAQ,aAAa,MAAM,CAAA,CAAA;AAC1E,EAAA,MAAM,WAAW,CAAsC,mCAAA,EAAA,WAAA,CAAA,qBAAA,CAAA,CAAA;AAEvD,EAAA,KAAA,MAAW,UAAU,OAAS,EAAA;AAC5B,IAAM,MAAAC,MAAA,GAAOC,YAAY,CAAA,SAAA,EAAW,MAAM,CAAA,CAAA;AAE1C,IAAA,MAAM,OAAU,GAAA,MAAMF,sBAAG,CAAA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src/lib/assets/StaticAssetsStore.ts","../src/lib/assets/findStaticAssets.ts","../src/lib/headers.ts","../src/lib/assets/createStaticAssetMiddleware.ts","../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport { loadConfigSchema, readEnvConfig } from '@backstage/config-loader';\n\ntype InjectOptions = {\n appConfigs: AppConfig[];\n // Directory of the static JS files to search for file to inject\n staticDir: string;\n logger: Logger;\n};\n\n/**\n * Injects configs into the app bundle, replacing any existing injected config.\n */\nexport async function injectConfig(options: InjectOptions) {\n const { staticDir, logger, appConfigs } = options;\n\n const files = await fs.readdir(staticDir);\n const jsFiles = files.filter(file => file.endsWith('.js'));\n\n const escapedData = JSON.stringify(appConfigs).replace(/(\"|'|\\\\)/g, '\\\\$1');\n const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/\"${escapedData}\"/*__INJECTED_END__*/`;\n\n for (const jsFile of jsFiles) {\n const path = resolvePath(staticDir, jsFile);\n\n const content = await fs.readFile(path, 'utf8');\n if (content.includes('__APP_INJECTED_RUNTIME_CONFIG__')) {\n logger.info(`Injecting env config into ${jsFile}`);\n\n const newContent = content.replace(\n '\"__APP_INJECTED_RUNTIME_CONFIG__\"',\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n } else if (content.includes('__APP_INJECTED_CONFIG_MARKER__')) {\n logger.info(`Replacing injected env config in ${jsFile}`);\n\n const newContent = content.replace(\n /\\/\\*__APP_INJECTED_CONFIG_MARKER__\\*\\/.*\\/\\*__INJECTED_END__\\*\\//,\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n }\n }\n logger.info('Env config not injected');\n}\n\ntype ReadOptions = {\n env: { [name: string]: string | undefined };\n appDistDir: string;\n config: Config;\n};\n\n/**\n * Read config from environment and process the backend config using the\n * schema that is embedded in the frontend build.\n */\nexport async function readConfigs(options: ReadOptions): Promise<AppConfig[]> {\n const { env, appDistDir, config } = options;\n\n const appConfigs = readEnvConfig(env);\n\n const schemaPath = resolvePath(appDistDir, '.config-schema.json');\n if (await fs.pathExists(schemaPath)) {\n const serializedSchema = await fs.readJson(schemaPath);\n\n try {\n const schema = await loadConfigSchema({ serialized: serializedSchema });\n\n const frontendConfigs = await schema.process(\n [{ data: config.get() as JsonObject, context: 'app' }],\n { visibility: ['frontend'], withDeprecatedKeys: true },\n );\n appConfigs.push(...frontendConfigs);\n } catch (error) {\n throw new Error(\n 'Invalid app bundle schema. If this error is unexpected you need to run `yarn build` in the app. ' +\n `If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. ` +\n `Caused by the following schema error, ${error}`,\n );\n }\n }\n\n return appConfigs;\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Knex } from 'knex';\nimport { Logger } from 'winston';\nimport { DateTime } from 'luxon';\nimport partition from 'lodash/partition';\nimport { StaticAsset, StaticAssetInput, StaticAssetProvider } from './types';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-app-backend',\n 'migrations',\n);\n\ninterface StaticAssetRow {\n path: string;\n content: Buffer;\n last_modified_at: Date;\n}\n\n/** @internal */\nexport interface StaticAssetsStoreOptions {\n database: PluginDatabaseManager;\n logger: Logger;\n}\n\n/**\n * A storage for static assets that are assumed to be immutable.\n *\n * @internal\n */\nexport class StaticAssetsStore implements StaticAssetProvider {\n #db: Knex;\n #logger: Logger;\n\n static async create(options: StaticAssetsStoreOptions) {\n const { database } = options;\n const client = await database.getClient();\n\n if (!database.migrations?.skip) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new StaticAssetsStore(client, options.logger);\n }\n\n private constructor(client: Knex, logger: Logger) {\n this.#db = client;\n this.#logger = logger;\n }\n\n /**\n * Store the provided assets.\n *\n * If an asset for a given path already exists the modification time will be\n * updated, but the contents will not.\n */\n async storeAssets(assets: StaticAssetInput[]) {\n const existingRows = await this.#db<StaticAssetRow>(\n 'static_assets_cache',\n ).whereIn(\n 'path',\n assets.map(a => a.path),\n );\n const existingAssetPaths = new Set(existingRows.map(r => r.path));\n\n const [modified, added] = partition(assets, asset =>\n existingAssetPaths.has(asset.path),\n );\n\n this.#logger.info(\n `Storing ${modified.length} updated assets and ${added.length} new assets`,\n );\n\n await this.#db('static_assets_cache')\n .update({\n last_modified_at: this.#db.fn.now(),\n })\n .whereIn(\n 'path',\n modified.map(a => a.path),\n );\n\n for (const asset of added) {\n // We ignore conflicts with other nodes, it doesn't matter if someone else\n // added the same asset just before us.\n await this.#db('static_assets_cache')\n .insert({\n path: asset.path,\n content: await asset.content(),\n })\n .onConflict('path')\n .ignore();\n }\n }\n\n /**\n * Retrieve an asset from the store with the given path.\n */\n async getAsset(path: string): Promise<StaticAsset | undefined> {\n const [row] = await this.#db<StaticAssetRow>('static_assets_cache').where({\n path,\n });\n if (!row) {\n return undefined;\n }\n return {\n path: row.path,\n content: row.content,\n lastModifiedAt:\n typeof row.last_modified_at === 'string'\n ? DateTime.fromSQL(row.last_modified_at, { zone: 'UTC' }).toJSDate()\n : row.last_modified_at,\n };\n }\n\n /**\n * Delete any assets from the store whose modification time is older than the max age.\n */\n async trimAssets(options: { maxAgeSeconds: number }) {\n const { maxAgeSeconds } = options;\n await this.#db<StaticAssetRow>('static_assets_cache')\n .where(\n 'last_modified_at',\n '<=',\n this.#db.client.config.client.includes('sqlite3')\n ? this.#db.raw(`datetime('now', ?)`, [`-${maxAgeSeconds} seconds`])\n : this.#db.raw(`now() + interval '${-maxAgeSeconds} seconds'`),\n )\n .delete();\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport globby from 'globby';\nimport { StaticAssetInput } from './types';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\n\n/**\n * Finds all static assets within a directory\n *\n * @internal\n */\nexport async function findStaticAssets(\n staticDir: string,\n): Promise<StaticAssetInput[]> {\n const assetPaths = await globby('**/*', {\n ignore: ['**/*.map'], // Ignore source maps since they're quite large\n cwd: staticDir,\n dot: true,\n });\n\n return assetPaths.map(path => ({\n path,\n content: async () => fs.readFile(resolveSafeChildPath(staticDir, path)),\n }));\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const CACHE_CONTROL_NO_CACHE = 'no-store, max-age=0';\nexport const CACHE_CONTROL_MAX_CACHE = 'public, max-age=1209600'; // 14 days\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extname } from 'path';\nimport { RequestHandler } from 'express';\nimport { StaticAssetProvider } from './types';\nimport { CACHE_CONTROL_MAX_CACHE } from '../headers';\n\n/**\n * Creates a middleware that serves static assets from a static asset provider\n *\n * @internal\n */\nexport function createStaticAssetMiddleware(\n store: StaticAssetProvider,\n): RequestHandler {\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n next();\n return;\n }\n\n // Let's not assume we're in promise-router\n Promise.resolve(\n (async () => {\n // Drop leading slashes from the incoming path\n const path = req.path.startsWith('/') ? req.path.slice(1) : req.path;\n\n const asset = await store.getAsset(path);\n if (!asset) {\n next();\n return;\n }\n\n // Set the Content-Type header, falling back to octet-stream\n const ext = extname(asset.path);\n if (ext) {\n res.type(ext);\n } else {\n res.type('bin');\n }\n\n // Same as our express.static override\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n res.setHeader('Last-Modified', asset.lastModifiedAt.toUTCString());\n\n res.send(asset.content);\n })(),\n ).catch(next);\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n notFoundHandler,\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport helmet from 'helmet';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { injectConfig, readConfigs } from '../lib/config';\nimport {\n StaticAssetsStore,\n findStaticAssets,\n createStaticAssetMiddleware,\n} from '../lib/assets';\nimport {\n CACHE_CONTROL_MAX_CACHE,\n CACHE_CONTROL_NO_CACHE,\n} from '../lib/headers';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\n/** @public */\nexport interface RouterOptions {\n config: Config;\n logger: Logger;\n\n /**\n * If a database is provided it will be used to cache previously deployed static assets.\n *\n * This is a built-in alternative to using a `staticFallbackHandler`.\n */\n database?: PluginDatabaseManager;\n\n /**\n * The name of the app package that content should be served from. The same app package should be\n * added as a dependency to the backend package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package this would be set to 'app'.\n */\n appPackageName: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n *\n * Another option is to provide a `database` that will take care of storing the static assets instead.\n *\n * If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve\n * static assets first, and if they are not found, the `staticFallbackHandler` will be called.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n}\n\n/** @public */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { config, logger, appPackageName, staticFallbackHandler } = options;\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n if (process.env.NODE_ENV === 'production') {\n logger.error(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n }\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n if (!options.disableConfigInjection) {\n const appConfigs = await readConfigs({\n config,\n appDistDir,\n env: process.env,\n });\n\n await injectConfig({ appConfigs, logger, staticDir });\n }\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\n\n // Use a separate router for static content so that a fallback can be provided by backend\n const staticRouter = Router();\n staticRouter.use(\n express.static(resolvePath(appDistDir, 'static'), {\n setHeaders: res => {\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n },\n }),\n );\n\n if (options.database) {\n const store = await StaticAssetsStore.create({\n logger,\n database: options.database,\n });\n\n const assets = await findStaticAssets(staticDir);\n await store.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await store.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(store));\n }\n\n if (staticFallbackHandler) {\n staticRouter.use(staticFallbackHandler);\n }\n staticRouter.use(notFoundHandler());\n\n router.use('/static', staticRouter);\n router.use(\n express.static(appDistDir, {\n setHeaders: (res, path) => {\n // The Cache-Control header instructs the browser to not cache html files since it might\n // link to static assets from recently deployed versions.\n if (\n (express.static.mime as unknown as Mime).lookup(path) === 'text/html'\n ) {\n res.setHeader('Cache-Control', CACHE_CONTROL_NO_CACHE);\n }\n },\n }),\n );\n router.get('/*', (_req, res) => {\n res.sendFile(resolvePath(appDistDir, 'index.html'), {\n headers: {\n // The Cache-Control header instructs the browser to not cache the index.html since it might\n // link to static assets from recently deployed versions.\n 'cache-control': CACHE_CONTROL_NO_CACHE,\n },\n });\n });\n\n return router;\n}\n"],"names":["fs","path","resolvePath","readEnvConfig","loadConfigSchema","resolvePackagePath","partition","DateTime","globby","resolveSafeChildPath","extname","Router","helmet","express","notFoundHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiCA,eAAsB,aAAa,OAAwB,EAAA;AACzD,EAAA,MAAM,EAAE,SAAA,EAAW,MAAQ,EAAA,UAAA,EAAe,GAAA,OAAA,CAAA;AAE1C,EAAA,MAAM,KAAQ,GAAA,MAAMA,sBAAG,CAAA,OAAA,CAAQ,SAAS,CAAA,CAAA;AACxC,EAAA,MAAM,UAAU,KAAM,CAAA,MAAA,CAAO,UAAQ,IAAK,CAAA,QAAA,CAAS,KAAK,CAAC,CAAA,CAAA;AAEzD,EAAA,MAAM,cAAc,IAAK,CAAA,SAAA,CAAU,UAAU,CAAE,CAAA,OAAA,CAAQ,aAAa,MAAM,CAAA,CAAA;AAC1E,EAAA,MAAM,WAAW,CAAsC,mCAAA,EAAA,WAAA,CAAA,qBAAA,CAAA,CAAA;AAEvD,EAAA,KAAA,MAAW,UAAU,OAAS,EAAA;AAC5B,IAAM,MAAAC,MAAA,GAAOC,YAAY,CAAA,SAAA,EAAW,MAAM,CAAA,CAAA;AAE1C,IAAA,MAAM,OAAU,GAAA,MAAMF,sBAAG,CAAA,QAAA,CAASC,QAAM,MAAM,CAAA,CAAA;AAC9C,IAAI,IAAA,OAAA,CAAQ,QAAS,CAAA,iCAAiC,CAAG,EAAA;AACvD,MAAO,MAAA,CAAA,IAAA,CAAK,6BAA6B,MAAQ,CAAA,CAAA,CAAA,CAAA;AAEjD,MAAA,MAAM,aAAa,OAAQ,CAAA,OAAA;AAAA,QACzB,mCAAA;AAAA,QACA,QAAA;AAAA,OACF,CAAA;AACA,MAAA,MAAMD,sBAAG,CAAA,SAAA,CAAUC,MAAM,EAAA,UAAA,EAAY,MAAM,CAAA,CAAA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
|
-
import { BackendFeature } from '@backstage/backend-plugin-api';
|
|
1
|
+
import { PluginDatabaseManager } from '@backstage/backend-common';
|
|
8
2
|
import { Config } from '@backstage/config';
|
|
9
3
|
import express from 'express';
|
|
10
4
|
import { Logger } from 'winston';
|
|
11
|
-
import { PluginDatabaseManager } from '@backstage/backend-common';
|
|
12
|
-
|
|
13
|
-
/* Excluded from this release type: appPlugin */
|
|
14
|
-
|
|
15
|
-
/* Excluded from this release type: AppPluginOptions */
|
|
16
|
-
|
|
17
|
-
/** @public */
|
|
18
|
-
export declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
19
5
|
|
|
20
6
|
/** @public */
|
|
21
|
-
|
|
7
|
+
interface RouterOptions {
|
|
22
8
|
config: Config;
|
|
23
9
|
logger: Logger;
|
|
24
10
|
/**
|
|
@@ -58,5 +44,7 @@ export declare interface RouterOptions {
|
|
|
58
44
|
*/
|
|
59
45
|
disableConfigInjection?: boolean;
|
|
60
46
|
}
|
|
47
|
+
/** @public */
|
|
48
|
+
declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
61
49
|
|
|
62
|
-
export { }
|
|
50
|
+
export { RouterOptions, createRouter };
|
package/package.json
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-app-backend",
|
|
3
3
|
"description": "A Backstage backend plugin that serves the Backstage frontend app",
|
|
4
|
-
"version": "0.3.
|
|
5
|
-
"main": "dist/index.cjs.js",
|
|
6
|
-
"types": "dist/index.d.ts",
|
|
4
|
+
"version": "0.3.43-next.0",
|
|
5
|
+
"main": "./dist/index.cjs.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"publishConfig": {
|
|
9
|
-
"access": "public"
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
"
|
|
9
|
+
"access": "public"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"require": "./dist/index.cjs.js",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.cjs.js"
|
|
16
|
+
},
|
|
17
|
+
"./alpha": {
|
|
18
|
+
"require": "./dist/alpha.cjs.js",
|
|
19
|
+
"types": "./dist/alpha.d.ts",
|
|
20
|
+
"default": "./dist/alpha.cjs.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
13
23
|
},
|
|
14
24
|
"backstage": {
|
|
15
25
|
"role": "backend-plugin"
|
|
@@ -25,7 +35,7 @@
|
|
|
25
35
|
],
|
|
26
36
|
"scripts": {
|
|
27
37
|
"start": "backstage-cli package start",
|
|
28
|
-
"build": "backstage-cli package build
|
|
38
|
+
"build": "backstage-cli package build",
|
|
29
39
|
"lint": "backstage-cli package lint",
|
|
30
40
|
"test": "backstage-cli package test",
|
|
31
41
|
"prepack": "backstage-cli package prepack",
|
|
@@ -33,8 +43,8 @@
|
|
|
33
43
|
"clean": "backstage-cli package clean"
|
|
34
44
|
},
|
|
35
45
|
"dependencies": {
|
|
36
|
-
"@backstage/backend-common": "^0.18.
|
|
37
|
-
"@backstage/backend-plugin-api": "^0.4.0",
|
|
46
|
+
"@backstage/backend-common": "^0.18.3-next.0",
|
|
47
|
+
"@backstage/backend-plugin-api": "^0.4.1-next.0",
|
|
38
48
|
"@backstage/config": "^1.0.6",
|
|
39
49
|
"@backstage/config-loader": "^1.1.8",
|
|
40
50
|
"@backstage/types": "^1.0.2",
|
|
@@ -51,9 +61,9 @@
|
|
|
51
61
|
"yn": "^4.0.0"
|
|
52
62
|
},
|
|
53
63
|
"devDependencies": {
|
|
54
|
-
"@backstage/backend-app-api": "^0.4.0",
|
|
55
|
-
"@backstage/backend-test-utils": "^0.1.
|
|
56
|
-
"@backstage/cli": "^0.22.
|
|
64
|
+
"@backstage/backend-app-api": "^0.4.1-next.0",
|
|
65
|
+
"@backstage/backend-test-utils": "^0.1.35-next.0",
|
|
66
|
+
"@backstage/cli": "^0.22.4-next.0",
|
|
57
67
|
"@backstage/types": "^1.0.2",
|
|
58
68
|
"@types/supertest": "^2.0.8",
|
|
59
69
|
"mock-fs": "^5.1.0",
|
|
@@ -63,8 +73,8 @@
|
|
|
63
73
|
},
|
|
64
74
|
"files": [
|
|
65
75
|
"dist",
|
|
66
|
-
"alpha",
|
|
67
76
|
"migrations/**/*.{js,d.ts}",
|
|
68
|
-
"static"
|
|
77
|
+
"static",
|
|
78
|
+
"alpha"
|
|
69
79
|
]
|
|
70
80
|
}
|
package/dist/index.alpha.d.ts
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A Backstage backend plugin that serves the Backstage frontend app
|
|
3
|
-
*
|
|
4
|
-
* @packageDocumentation
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { BackendFeature } from '@backstage/backend-plugin-api';
|
|
8
|
-
import { Config } from '@backstage/config';
|
|
9
|
-
import express from 'express';
|
|
10
|
-
import { Logger } from 'winston';
|
|
11
|
-
import { PluginDatabaseManager } from '@backstage/backend-common';
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* The App plugin is responsible for serving the frontend app bundle and static assets.
|
|
15
|
-
* @alpha
|
|
16
|
-
*/
|
|
17
|
-
export declare const appPlugin: (options: AppPluginOptions) => BackendFeature;
|
|
18
|
-
|
|
19
|
-
/** @alpha */
|
|
20
|
-
export declare type AppPluginOptions = {
|
|
21
|
-
/**
|
|
22
|
-
* The name of the app package (in most Backstage repositories, this is the
|
|
23
|
-
* "name" field in `packages/app/package.json`) that content should be served
|
|
24
|
-
* from. The same app package should be added as a dependency to the backend
|
|
25
|
-
* package in order for it to be accessible at runtime.
|
|
26
|
-
*
|
|
27
|
-
* In a typical setup with a single app package, this will default to 'app'.
|
|
28
|
-
*/
|
|
29
|
-
appPackageName?: string;
|
|
30
|
-
/**
|
|
31
|
-
* A request handler to handle requests for static content that are not present in the app bundle.
|
|
32
|
-
*
|
|
33
|
-
* This can be used to avoid issues with clients on older deployment versions trying to access lazy
|
|
34
|
-
* loaded content that is no longer present. Typically the requests would fall back to a long-term
|
|
35
|
-
* object store where all recently deployed versions of the app are present.
|
|
36
|
-
*
|
|
37
|
-
* Another option is to provide a `database` that will take care of storing the static assets instead.
|
|
38
|
-
*
|
|
39
|
-
* If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve
|
|
40
|
-
* static assets first, and if they are not found, the `staticFallbackHandler` will be called.
|
|
41
|
-
*/
|
|
42
|
-
staticFallbackHandler?: express.Handler;
|
|
43
|
-
/**
|
|
44
|
-
* Disables the configuration injection. This can be useful if you're running in an environment
|
|
45
|
-
* with a read-only filesystem, or for some other reason don't want configuration to be injected.
|
|
46
|
-
*
|
|
47
|
-
* Note that this will cause the configuration used when building the app bundle to be used, unless
|
|
48
|
-
* a separate configuration loading strategy is set up.
|
|
49
|
-
*
|
|
50
|
-
* This also disables configuration injection though `APP_CONFIG_` environment variables.
|
|
51
|
-
*/
|
|
52
|
-
disableConfigInjection?: boolean;
|
|
53
|
-
/**
|
|
54
|
-
* By default the app backend plugin will cache previously deployed static assets in the database.
|
|
55
|
-
* If you disable this, it is recommended to set a `staticFallbackHandler` instead.
|
|
56
|
-
*/
|
|
57
|
-
disableStaticFallbackCache?: boolean;
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
/** @public */
|
|
61
|
-
export declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
62
|
-
|
|
63
|
-
/** @public */
|
|
64
|
-
export declare interface RouterOptions {
|
|
65
|
-
config: Config;
|
|
66
|
-
logger: Logger;
|
|
67
|
-
/**
|
|
68
|
-
* If a database is provided it will be used to cache previously deployed static assets.
|
|
69
|
-
*
|
|
70
|
-
* This is a built-in alternative to using a `staticFallbackHandler`.
|
|
71
|
-
*/
|
|
72
|
-
database?: PluginDatabaseManager;
|
|
73
|
-
/**
|
|
74
|
-
* The name of the app package that content should be served from. The same app package should be
|
|
75
|
-
* added as a dependency to the backend package in order for it to be accessible at runtime.
|
|
76
|
-
*
|
|
77
|
-
* In a typical setup with a single app package this would be set to 'app'.
|
|
78
|
-
*/
|
|
79
|
-
appPackageName: string;
|
|
80
|
-
/**
|
|
81
|
-
* A request handler to handle requests for static content that are not present in the app bundle.
|
|
82
|
-
*
|
|
83
|
-
* This can be used to avoid issues with clients on older deployment versions trying to access lazy
|
|
84
|
-
* loaded content that is no longer present. Typically the requests would fall back to a long-term
|
|
85
|
-
* object store where all recently deployed versions of the app are present.
|
|
86
|
-
*
|
|
87
|
-
* Another option is to provide a `database` that will take care of storing the static assets instead.
|
|
88
|
-
*
|
|
89
|
-
* If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve
|
|
90
|
-
* static assets first, and if they are not found, the `staticFallbackHandler` will be called.
|
|
91
|
-
*/
|
|
92
|
-
staticFallbackHandler?: express.Handler;
|
|
93
|
-
/**
|
|
94
|
-
* Disables the configuration injection. This can be useful if you're running in an environment
|
|
95
|
-
* with a read-only filesystem, or for some other reason don't want configuration to be injected.
|
|
96
|
-
*
|
|
97
|
-
* Note that this will cause the configuration used when building the app bundle to be used, unless
|
|
98
|
-
* a separate configuration loading strategy is set up.
|
|
99
|
-
*
|
|
100
|
-
* This also disables configuration injection though `APP_CONFIG_` environment variables.
|
|
101
|
-
*/
|
|
102
|
-
disableConfigInjection?: boolean;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
export { }
|