Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using internal Govuk Frontend more widely #2317

Merged
merged 2 commits into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 0 additions & 75 deletions __tests__/spec/sanity-checks.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-env jest */

// core dependencies
const assert = require('assert')
const path = require('path')

// npm dependencies
Expand Down Expand Up @@ -69,78 +68,4 @@ describe('The Prototype Kit', () => {
expect(response.type).toBe('text/html')
})
})

describe('plugins', () => {
it('should allow known assets to be loaded from node_modules', (done) => {
request(app)
.get('/plugin-assets/govuk-frontend/govuk/all.js')
.expect(200)
.expect('Content-Type', /application\/javascript; charset=UTF-8/)
.end((err, res) => {
if (err) {
done(err)
} else {
assert.strictEqual(
'' + res.text,
fse.readFileSync(path.join(projectDir, 'node_modules', 'govuk-frontend', 'govuk', 'all.js'), 'utf8')
)
done()
}
})
})

it('should allow known assets to be loaded from node_modules', (done) => {
request(app)
.get('/plugin-assets/govuk-frontend/govuk/assets/images/favicon.ico')
.expect(200)
.expect('Content-Type', /image\/x-icon/)
.end((err, res) => {
if (err) {
done(err)
} else {
assert.strictEqual(
'' + res.body,
fse.readFileSync(path.join(projectDir, 'node_modules', 'govuk-frontend', 'govuk', 'assets', 'images', 'favicon.ico'), 'utf8')
)
done()
}
})
})

it('should not expose everything', (done) => {
const consoleErrorMock = jest.spyOn(global.console, 'error').mockImplementation()

request(app)
.get('/govuk/assets/common.js')
.expect(404)
.end((err, res) => {
consoleErrorMock.mockRestore()
if (err) {
done(err)
} else {
done()
}
})
})

describe('misconfigured prototype kit - while updating kit developer did not copy over changes in /app folder', () => {
it('should still allow known assets to be loaded from node_modules', (done) => {
request(app)
.get('/plugin-assets/govuk-frontend/govuk/all.js')
.expect(200)
.expect('Content-Type', /application\/javascript; charset=UTF-8/)
.end((err, res) => {
if (err) {
done(err)
} else {
assert.strictEqual(
'' + res.text,
fse.readFileSync(path.join(projectDir, 'node_modules', 'govuk-frontend', 'govuk', 'all.js'), 'utf8')
)
done()
}
})
})
})
})
})
10 changes: 6 additions & 4 deletions lib/authentication.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

// core dependencies
const url = require('url')

Expand All @@ -14,8 +13,7 @@ const allowedPathsWhenUnauthenticated = [
'/plugin-assets/govuk-frontend/govuk/all.js',
// Keep /extension-assets path for backwards compatibility
// TODO: remove in v14
'/extension-assets/govuk-prototype-kit/lib/assets/images/unbranded.ico',
'/extension-assets/govuk-frontend/govuk/all.js']
'/extension-assets/govuk-prototype-kit/lib/assets/images/unbranded.ico']

function authentication () {
if (!shouldUseAuth()) {
Expand All @@ -38,7 +36,11 @@ function authentication () {
const password = encryptPassword(config.getConfig().password)

return (req, res, next) => {
if (allowedPathsWhenUnauthenticated.includes(req.path)) {
if (allowedPathsWhenUnauthenticated.includes(req.path) ||
req.path.startsWith('/manage-prototype/dependencies') ||
req.path.startsWith('/plugin-assets/govuk-prototype-kit') ||
req.path === '/public/stylesheets/manage-prototype.css'
) {
next()
} else if (isAuthenticated(password, req)) {
next()
Expand Down
15 changes: 3 additions & 12 deletions lib/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@ const {
publicCssDir,
shadowNunjucksDir,
backupNunjucksDir,
appViewsDir,
packageDir
appViewsDir
} = require('./utils/paths')
const { recursiveDirectoryContentsSync } = require('./utils')
const { recursiveDirectoryContentsSync, getInternalGovukFrontendDir } = require('./utils')
const { startPerformanceTimer, endPerformanceTimer } = require('./utils/performance')
const { verboseLog } = require('./utils/verboseLogger')
const { hasRestartedAfterError } = require('./sync-changes')
Expand Down Expand Up @@ -84,21 +83,13 @@ function ensureTempDirExists (dir = tmpDir) {
fse.writeFileSync(path.join(tmpDir, '.gitignore'), '*')
}

function getInternalGovUkFrontendDir () {
let internalGovUkFrontendDir = path.join(packageDir, 'node_modules', 'govuk-frontend')
if (!fse.pathExistsSync(internalGovUkFrontendDir)) {
internalGovUkFrontendDir = path.join(projectDir, 'node_modules', 'govuk-frontend')
}
return internalGovUkFrontendDir
}

function sassInclude (filePath) {
return `@import "${filePath.split(path.sep).join('/')}";`
}

function sassKitFrontendDependency () {
const timer = startPerformanceTimer()
const internalGovUkFrontendDir = getInternalGovUkFrontendDir()
const internalGovUkFrontendDir = getInternalGovukFrontendDir()
const internalGovUkFrontendConfig = fse.readJsonSync(path.join(internalGovUkFrontendDir, 'govuk-prototype-kit.config.json'))
const fileContents = internalGovUkFrontendConfig.sass
.map(sassPath => path.join(internalGovUkFrontendDir, sassPath))
Expand Down
23 changes: 18 additions & 5 deletions lib/errorServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const { verboseLog } = require('./utils/verboseLogger')
const syncChanges = require('./sync-changes')
const { flagError } = require('./sync-changes')
const { packageDir } = require('./utils/paths')
const { getInternalGovukFrontendDir } = require('./utils')

function runErrorServer (error) {
flagError(error)
Expand Down Expand Up @@ -52,11 +53,23 @@ function runErrorServer (error) {
}
if (req.url.startsWith('/plugin-assets')) {
res.setHeader('Content-Type', fileExtensionsToMimeTypes[req.url.split('.').at(-1)] || 'text/plain')
const urlParts = req.url.split('/')
urlParts.shift()
urlParts[0] = 'node_modules'
const filePath = path.join(process.cwd(), ...urlParts)
res.end(fs.readFileSync(filePath))
const urlParts = req.url.split('/').slice(2)
const pluginName = urlParts.shift()
let filePath
if (pluginName === 'govuk-frontend') {
filePath = path.join(getInternalGovukFrontendDir(), ...urlParts)
} else {
filePath = path.join(process.cwd(), 'node_modules', pluginName, ...urlParts)
}
try {
const contents = fs.readFileSync(filePath)
res.writeHead(200)
res.end(contents)
} catch (e) {
console.log('Couldn\'t load url in error server: ', req.url)
res.writeHead(500)
res.end('500 Server Error')
}
return
}

Expand Down
7 changes: 5 additions & 2 deletions lib/manage-prototype-handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ function postPasswordHandler (req, res) {
// Middleware to ensure the routes specified below will render the manage-prototype-not-available
// view when the prototype is not running in development
function developmentOnlyMiddleware (req, res, next) {
if (config.getConfig().isDevelopment) {
if (config.getConfig().isDevelopment || req.url.startsWith('/dependencies/govuk-frontend')) {
next()
} else {
res.render(getManagementView('manage-prototype-not-available.njk'))
Expand All @@ -131,7 +131,10 @@ function developmentOnlyMiddleware (req, res, next) {

// Middleware to ensure pages load when plugin cache has been initially loaded
async function pluginCacheMiddleware (req, res, next) {
await waitForPackagesCache()
await Promise.race([
waitForPackagesCache(),
new Promise((resolve) => setTimeout(resolve, 1000))
])
next()
}

Expand Down
3 changes: 2 additions & 1 deletion lib/manage-prototype-handlers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ describe('manage-prototype-handlers', () => {
query: {},
params: {},
route: {},
originalUrl: '/current-url'
originalUrl: '/current-url',
url: '/current-url'
}
res = {
render: jest.fn(),
Expand Down
14 changes: 8 additions & 6 deletions lib/manage-prototype-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,6 @@ const path = require('path')
const { getInternalGovukFrontendDir } = require('./utils')

const router = require('../index').requests.setupRouter(contextPath)
const redirectingRouter = require('../index').requests.setupRouter('/manage-prototype')

redirectingRouter.use((req, res) => {
res.redirect(req.originalUrl.replace('/manage-prototype', contextPath))
})

router.get('/csrf-token', getCsrfTokenHandler)

Expand Down Expand Up @@ -84,7 +79,14 @@ router.post('/plugins/:mode', postPluginsModeMiddleware)

router.post('/plugins/:mode', csrfProtection, postPluginsModeHandler)

router.use('/dependencies/govuk-frontend/govuk/assets', express.static(path.join(getInternalGovukFrontendDir(), 'govuk', 'assets')))
const partialGovukFrontendUrls = [
'govuk/assets',
'govuk/all.js',
'govuk-prototype-kit/init.js'
]
partialGovukFrontendUrls.forEach(url => {
router.use(`/dependencies/govuk-frontend/${url}`, express.static(path.join(getInternalGovukFrontendDir(), url)))
})

setKitRestarted(true)

Expand Down
2 changes: 1 addition & 1 deletion lib/nunjucks/views/error-handling/page-not-found.njk
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% extends "govuk-prototype-kit/layouts/govuk-branded.njk" %}
{% extends "views/manage-prototype/layout.njk" %}

{% block pageTitle %}
Page not found – {{ serviceName }} – GOV.UK Prototype Kit
Expand Down
7 changes: 6 additions & 1 deletion lib/nunjucks/views/manage-prototype/layout.njk
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@
{% include "views/manage-prototype/stylesheets.njk" %}
{% endblock %}

{% block beforeContent %}
{% block scripts %}
{% include "views/manage-prototype/scripts.njk" %}
{% block pageScripts %}{% endblock %}
{% endblock %}

{% block beforeContent %}
<nav id="govuk-prototype-kit-manage-prototype-navigation" class="govuk-prototype-kit-manage-prototype-navigation js-govuk-prototype-kit-manage-prototype-navigation govuk-clearfix" role="navigation"
aria-labelledby="govuk-prototype-kit-manage-prototype-navigation-heading">
<h2 class="govuk-visually-hidden" id="govuk-prototype-kit-manage-prototype-navigation-heading">Menu</h2>
Expand Down
28 changes: 17 additions & 11 deletions lib/nunjucks/views/manage-prototype/password.njk
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% extends "govuk-prototype-kit/layouts/unbranded.njk" %}
{% extends "views/manage-prototype/layout.njk" %}

{% from "govuk/components/error-summary/macro.njk" import govukErrorSummary %}
{% from "govuk/components/input/macro.njk" import govukInput %}
Expand All @@ -14,19 +14,25 @@
Sign in - GOV.UK Prototype Kit
{% endblock %}

{% block head %}
<link href="/public/stylesheets/unbranded.css" media="all" rel="stylesheet" type="text/css" />
{% endblock %}

{% block scripts %}
<!-- We only need Frontend js in order to focus the error summary -->
<script src="/plugin-assets/govuk-frontend/govuk/all.js"></script>
<script>
window.GOVUKFrontend.initAll()
</script>
{% block header %}{% endblock %}
{% block footer %}{% endblock %}
{% block beforeContent %}{% endblock %}
{% block stylesheets %}
{{ super() }}
<style>
.govuk-heading-xl,
.govuk-label,
.govuk-button,
.govuk-error-summary__title,
.govuk-error-summary__body,
.govuk-error-summary__list a,
.govuk-error-message {
font-family: sans-serif;
}
</style>
{% endblock %}


{% block content %}

<form method="post" action="/manage-prototype/password">
Expand Down
3 changes: 3 additions & 0 deletions lib/nunjucks/views/manage-prototype/scripts.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<script src="/manage-prototype/dependencies/govuk-frontend/govuk/all.js"></script>
<script src="/manage-prototype/dependencies/govuk-frontend/govuk-prototype-kit/init.js"></script>
<script src="/plugin-assets/govuk-prototype-kit/lib/assets/javascripts/kit.js"></script>