@defra/forms-engine-plugin 4.0.42 → 4.0.43
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/.public/javascripts/shared.min.js +1 -1
- package/.public/javascripts/shared.min.js.map +1 -1
- package/.server/client/javascripts/location-map.js +8 -4
- package/.server/client/javascripts/location-map.js.map +1 -1
- package/.server/server/plugins/engine/configureEnginePlugin.d.ts +1 -1
- package/.server/server/plugins/engine/configureEnginePlugin.js +4 -2
- package/.server/server/plugins/engine/configureEnginePlugin.js.map +1 -1
- package/.server/server/plugins/engine/options.js +2 -1
- package/.server/server/plugins/engine/options.js.map +1 -1
- package/.server/server/plugins/engine/plugin.js +6 -4
- package/.server/server/plugins/engine/plugin.js.map +1 -1
- package/.server/server/plugins/engine/types.d.ts +1 -0
- package/.server/server/plugins/engine/types.js.map +1 -1
- package/.server/server/plugins/map/routes/get-os-token.d.ts +6 -0
- package/.server/server/plugins/map/routes/get-os-token.js +41 -0
- package/.server/server/plugins/map/routes/get-os-token.js.map +1 -0
- package/.server/server/plugins/map/routes/get-os-token.test.js +49 -0
- package/.server/server/plugins/map/routes/get-os-token.test.js.map +1 -0
- package/.server/server/plugins/map/routes/index.d.ts +1 -11
- package/.server/server/plugins/map/routes/index.js +60 -16
- package/.server/server/plugins/map/routes/index.js.map +1 -1
- package/.server/server/plugins/map/types.d.ts +1 -0
- package/.server/server/plugins/map/types.js +1 -0
- package/.server/server/plugins/map/types.js.map +1 -1
- package/.server/server/types.d.ts +1 -0
- package/.server/server/types.js.map +1 -1
- package/package.json +1 -1
- package/src/client/javascripts/location-map.js +12 -4
- package/src/server/plugins/engine/configureEnginePlugin.ts +4 -2
- package/src/server/plugins/engine/options.js +2 -1
- package/src/server/plugins/engine/plugin.ts +6 -4
- package/src/server/plugins/engine/types.ts +1 -0
- package/src/server/plugins/map/routes/get-os-token.js +41 -0
- package/src/server/plugins/map/routes/get-os-token.test.js +55 -0
- package/src/server/plugins/map/routes/index.js +70 -24
- package/src/server/plugins/map/types.js +1 -0
- package/src/server/types.ts +1 -0
|
@@ -144,10 +144,14 @@ export function makeTileRequestTransformer(apiPath) {
|
|
|
144
144
|
* @param {string} resourceType - the resource type
|
|
145
145
|
*/
|
|
146
146
|
return function transformTileRequest(url, resourceType) {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
147
|
+
if (url.startsWith('https://api.os.uk')) {
|
|
148
|
+
if (resourceType === 'Tile') {
|
|
149
|
+
return {
|
|
150
|
+
url: url.replace('https://api.os.uk/maps/vector/v1/vts', `${window.location.origin}${apiPath}`),
|
|
151
|
+
headers: {}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
if (resourceType !== 'Style') {
|
|
151
155
|
return {
|
|
152
156
|
url: `${apiPath}/map-proxy?url=${encodeURIComponent(url)}`,
|
|
153
157
|
headers: {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"location-map.js","names":["OsGridRef","LatLon","latLongToEastingNorthing","lat","long","point","toOsGrid","eastingNorthingToLatLong","easting","northing","latLong","toLatLon","latitude","longitude","latLongToOsGridRef","toString","osGridRefToLatLong","osGridRef","parse","DEFAULT_LAT","DEFAULT_LONG","defaultConfig","zoom","center","COMPANY_SYMBOL_CODE","LOCATION_FIELD_SELECTOR","EVENTS","interactMarkerChange","defaultData","VTS_OUTDOOR_URL","VTS_DARK_URL","VTS_BLACK_AND_WHITE_URL","formSubmitFactory","buttons","onFormSubmit","e","submitter","HTMLButtonElement","includes","preventDefault","initMaps","config","assetPath","apiPath","data","locations","document","querySelectorAll","length","form","querySelector","Array","from","addEventListener","forEach","location","index","processLocation","makeTileRequestTransformer","transformTileRequest","url","resourceType","startsWith","urlObj","URL","searchParams","has","encodeURIComponent","headers","spritesPath","path","substring","HTMLDivElement","locationInputs","locationType","dataset","locationtype","supportedLocations","mapContainer","createElement","mapId","setAttribute","initConfig","getInitMapConfig","after","map","interactPlugin","createMap","on","onMapReady","bindLatLongField","bindEastingNorthingField","bindOsGridRefField","Error","addPanel","showLabel","label","mobile","slot","initiallyOpen","dismissable","modal","tablet","desktop","html","enable","mapsConfig","logoAltText","defra","window","dataLayers","markerColor","outdoor","dark","interactionMode","multiSelect","InteractiveMap","mapProvider","maplibreProvider","reverseGeocodeProvider","openNamesProvider","behaviour","minZoom","maxZoom","containerHeight","enableZoomControls","transformRequest","plugins","mapStylesPlugin","mapStyles","id","thumbnail","logo","attribution","String","fromCodePoint","Date","getFullYear","backgroundColor","mapColorScheme","appColorScheme","searchPlugin","osNamesURL","width","showMarker","scaleBarPlugin","units","locationField","getInitLatLongMapConfig","getInitEastingNorthingMapConfig","getInitOsGridRefMapConfig","validateLatLong","strLat","strLong","trim","Number","valid","latMin","latMax","longMin","longMax","latInBounds","longInBounds","value","validateEastingNorthing","strEasting","strNorthing","eastingMin","eastingMax","northingMin","northingMax","validateOsGridRef","pattern","match","exec","getLatLongInputs","inputs","latInput","longInput","getEastingNorthingInputs","eastingInput","northingInput","getOsGridRefInput","input","getInitMapCenterConfig","markers","coords","result","undefined","latlong","osGridRefInput","onInteractMarkerChange","maxPrecision","toFixed","onUpdateInputs","centerMap","onUpdateInput","addMarker","flyTo","essential"],"sources":["../../../src/client/javascripts/location-map.js"],"sourcesContent":["// @ts-expect-error - no types\nimport OsGridRef, { LatLon } from 'geodesy/osgridref.js'\n\n/**\n * Converts lat long to easting and northing\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {{ easting: number, northing: number }}\n */\nfunction latLongToEastingNorthing({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid()\n}\n\n/**\n * Converts easting and northing to lat long\n * @param {object} param\n * @param {number} param.easting\n * @param {number} param.northing\n * @returns {{ lat: number, long: number }}\n */\nfunction eastingNorthingToLatLong({ easting, northing }) {\n const point = new OsGridRef(easting, northing)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Converts lat long to an ordnance survey grid reference\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {string}\n */\nfunction latLongToOsGridRef({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n}\n\n/**\n * Converts an ordnance survey grid reference to lat long\n * @param {string} osGridRef\n * @returns {{ lat: number, long: number }}\n */\nfunction osGridRefToLatLong(osGridRef) {\n const point = OsGridRef.parse(osGridRef)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n// Center of UK\nconst DEFAULT_LAT = 53.825564\nconst DEFAULT_LONG = -2.421975\n\n/** @type {InteractiveMapInitConfig} */\nconst defaultConfig = {\n zoom: '6',\n center: [DEFAULT_LONG, DEFAULT_LAT]\n}\n\nconst COMPANY_SYMBOL_CODE = 169\nconst LOCATION_FIELD_SELECTOR = 'input.govuk-input'\nconst EVENTS = {\n interactMarkerChange: 'interact:markerchange'\n}\n\nconst defaultData = {\n VTS_OUTDOOR_URL: '/api/maps/vts/OS_VTS_3857_Outdoor.json',\n VTS_DARK_URL: '/api/maps/vts/OS_VTS_3857_Dark.json',\n VTS_BLACK_AND_WHITE_URL: '/api/maps/vts/OS_VTS_3857_Black_and_White.json'\n}\n\n/**\n * Make a form submit handler that only allows submissions from allowed buttons\n * @param {HTMLButtonElement[]} buttons - the form buttons to allow submissions\n */\nexport function formSubmitFactory(buttons) {\n /**\n * The submit handler\n * @param {SubmitEvent} e\n */\n const onFormSubmit = function (e) {\n if (\n !(e.submitter instanceof HTMLButtonElement) ||\n !buttons.includes(e.submitter)\n ) {\n e.preventDefault()\n }\n }\n\n return onFormSubmit\n}\n\n/**\n * Initialise location maps\n * @param {Partial<MapsEnvironmentConfig>} config - the map configuration\n */\nexport function initMaps(config = {}) {\n const {\n assetPath = '/assets',\n apiPath = '/form/api',\n data = defaultData\n } = config\n const locations = document.querySelectorAll('.app-location-field')\n\n // TODO: Fix this in `interactive-map`\n // If there are location components on the page fix up the main form submit\n // handler so it doesn't fire when using the integrated map search feature\n if (locations.length) {\n const form = document.querySelector('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n locations.forEach((location, index) => {\n processLocation({ assetPath, apiPath, data }, location, index)\n })\n}\n\n/**\n * OS API request proxy factory\n * @param {string} apiPath - the root API path\n */\nexport function makeTileRequestTransformer(apiPath) {\n /**\n * Proxy OS API requests via our server\n * @param {string} url - the request URL\n * @param {string} resourceType - the resource type\n */\n return function transformTileRequest(url, resourceType) {\n // Only proxy OS API requests that don't already have a key\n if (resourceType !== 'Style' && url.startsWith('https://api.os.uk')) {\n const urlObj = new URL(url)\n if (!urlObj.searchParams.has('key')) {\n return {\n url: `${apiPath}/map-proxy?url=${encodeURIComponent(url)}`,\n headers: {}\n }\n }\n }\n\n const spritesPath =\n 'https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main'\n\n // Proxy sprite requests\n if (url.startsWith(spritesPath)) {\n const path = url.substring(spritesPath.length)\n return {\n url: `${apiPath}/maps/vts${path}`,\n headers: {}\n }\n }\n\n return { url, headers: {} }\n }\n}\n\n/**\n * Processes a location field to add map capability\n * @param {MapsEnvironmentConfig} config - the location field element\n * @param {Element} location - the location field element\n * @param {*} index - the 0-based index\n */\nfunction processLocation(config, location, index) {\n if (!(location instanceof HTMLDivElement)) {\n return\n }\n\n const locationInputs = location.querySelector('.app-location-field-inputs')\n if (!(locationInputs instanceof HTMLDivElement)) {\n return\n }\n const locationType = location.dataset.locationtype\n\n // Check for support\n const supportedLocations = [\n 'latlongfield',\n 'eastingnorthingfield',\n 'osgridreffield'\n ]\n if (!locationType || !supportedLocations.includes(locationType)) {\n return\n }\n\n const mapContainer = document.createElement('div')\n const mapId = `map_${index}`\n\n mapContainer.setAttribute('id', mapId)\n mapContainer.setAttribute('class', 'map-container')\n\n const initConfig = getInitMapConfig(location) ?? defaultConfig\n\n locationInputs.after(mapContainer)\n\n const { map, interactPlugin } = createMap(mapId, initConfig, config)\n\n map.on(\n 'map:ready',\n /**\n * Callback function which fires when the map is ready\n * @param {object} e - the event\n * @param {MapLibreMap} e.map - the map provider instance\n */\n function onMapReady(e) {\n switch (locationType) {\n case 'latlongfield':\n bindLatLongField(location, map, e.map)\n break\n case 'eastingnorthingfield':\n bindEastingNorthingField(location, map, e.map)\n break\n case 'osgridreffield':\n bindOsGridRefField(location, map, e.map)\n break\n default:\n throw new Error('Not implemented')\n }\n\n // Add info panel\n map.addPanel('info', {\n showLabel: true,\n label: 'How to use the map',\n mobile: {\n slot: 'bottom',\n initiallyOpen: true,\n dismissable: true,\n modal: false\n },\n tablet: {\n slot: 'bottom',\n initiallyOpen: true,\n dismissable: true,\n modal: false\n },\n desktop: {\n slot: 'bottom',\n initiallyOpen: true,\n dismissable: true,\n modal: false\n },\n html: 'If using a map click on a point to update the location.<br><br>If using a keyboard, navigate to the point, centering the crosshair at the location and press enter.'\n })\n\n // Enable the interact plugin\n interactPlugin.enable()\n }\n )\n}\n\n/**\n * Create a Defra map instance\n * @param {string} mapId - the map id\n * @param {InteractiveMapInitConfig} initConfig - the map initial configuration\n * @param {MapsEnvironmentConfig} mapsConfig - the map environment params\n */\nfunction createMap(mapId, initConfig, mapsConfig) {\n const { assetPath, apiPath, data = defaultData } = mapsConfig\n const logoAltText = 'Ordnance survey logo'\n\n // @ts-expect-error - Defra namespace currently comes from UMD support files\n const defra = window.defra\n\n const interactPlugin = defra.interactPlugin({\n dataLayers: [],\n markerColor: { outdoor: '#ff0000', dark: '#00ff00' },\n interactionMode: 'marker',\n multiSelect: false\n })\n\n /** @type {InteractiveMap} */\n const map = new defra.InteractiveMap(mapId, {\n ...initConfig,\n mapProvider: defra.maplibreProvider(),\n reverseGeocodeProvider: defra.openNamesProvider({\n url: `${apiPath}/reverse-geocode-proxy?easting={easting}&northing={northing}`\n }),\n behaviour: 'inline',\n minZoom: 6,\n maxZoom: 18,\n containerHeight: '400px',\n enableZoomControls: true,\n transformRequest: makeTileRequestTransformer(apiPath),\n plugins: [\n defra.mapStylesPlugin({\n mapStyles: [\n {\n id: 'outdoor',\n label: 'Outdoor',\n url: data.VTS_OUTDOOR_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/outdoor-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`,\n backgroundColor: '#f5f5f0'\n },\n {\n id: 'dark',\n label: 'Dark',\n url: data.VTS_DARK_URL,\n mapColorScheme: 'dark',\n appColorScheme: 'dark',\n thumbnail: `${assetPath}/interactive-map/assets/images/dark-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-white.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'black-and-white',\n label: 'Black/White',\n url: data.VTS_BLACK_AND_WHITE_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/black-and-white-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-black.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n }\n ]\n }),\n interactPlugin,\n defra.searchPlugin({\n osNamesURL: `${apiPath}/geocode-proxy?query={query}`,\n width: '300px',\n showMarker: false\n }),\n defra.scaleBarPlugin({\n units: 'metric'\n })\n ]\n })\n\n return { map, interactPlugin }\n}\n\n/**\n * Gets initial map config for a location field\n * @param {HTMLDivElement} locationField - the location field element\n */\nfunction getInitMapConfig(locationField) {\n const locationType = locationField.dataset.locationtype\n\n switch (locationType) {\n case 'latlongfield':\n return getInitLatLongMapConfig(locationField)\n case 'eastingnorthingfield':\n return getInitEastingNorthingMapConfig(locationField)\n case 'osgridreffield':\n return getInitOsGridRefMapConfig(locationField)\n default:\n throw new Error('Not implemented')\n }\n}\n\n/**\n * Validates lat and long is numeric and within UK bounds\n * @param {string} strLat - the latitude string\n * @param {string} strLong - the longitude string\n * @returns {{ valid: false } | { valid: true, value: { lat: number, long: number } }}\n */\nfunction validateLatLong(strLat, strLong) {\n const lat = strLat.trim() && Number(strLat.trim())\n const long = strLong.trim() && Number(strLong.trim())\n\n if (!lat || !long) {\n return { valid: false }\n }\n\n const latMin = 49.85\n const latMax = 60.859\n const longMin = -13.687\n const longMax = 1.767\n\n const latInBounds = lat >= latMin && lat <= latMax\n const longInBounds = long >= longMin && long <= longMax\n\n if (!latInBounds || !longInBounds) {\n return { valid: false }\n }\n\n return { valid: true, value: { lat, long } }\n}\n\n/**\n * Validates easting and northing is numeric and within UK bounds\n * @param {string} strEasting - the easting string\n * @param {string} strNorthing - the northing string\n * @returns {{ valid: false } | { valid: true, value: { easting: number, northing: number } }}\n */\nfunction validateEastingNorthing(strEasting, strNorthing) {\n const easting = strEasting.trim() && Number(strEasting.trim())\n const northing = strNorthing.trim() && Number(strNorthing.trim())\n\n if (!easting || !northing) {\n return { valid: false }\n }\n\n const eastingMin = 0\n const eastingMax = 700000\n const northingMin = 0\n const northingMax = 1300000\n\n const latInBounds = easting >= eastingMin && easting <= eastingMax\n const longInBounds = northing >= northingMin && northing <= northingMax\n\n if (!latInBounds || !longInBounds) {\n return { valid: false }\n }\n\n return { valid: true, value: { easting, northing } }\n}\n\n/**\n * Validates OS grid reference is correct\n * @param {string} osGridRef - the OsGridRef\n * @returns {{ valid: false } | { valid: true, value: string }}\n */\nfunction validateOsGridRef(osGridRef) {\n if (!osGridRef) {\n return { valid: false }\n }\n\n const pattern =\n /^((([sS]|[nN])[a-hA-Hj-zJ-Z])|(([tT]|[oO])[abfglmqrvwABFGLMQRVW])|([hH][l-zL-Z])|([jJ][lmqrvwLMQRVW]))\\s?(([0-9]{3})\\s?([0-9]{3})|([0-9]{4})\\s?([0-9]{4})|([0-9]{5})\\s?([0-9]{5}))$/\n\n const match = pattern.exec(osGridRef)\n\n if (match === null) {\n return { valid: false }\n }\n\n return { valid: true, value: match[0] }\n}\n\n/**\n * Gets the inputs for a latlong location field\n * @param {HTMLDivElement} locationField - the latlong location field element\n */\nfunction getLatLongInputs(locationField) {\n const inputs = locationField.querySelectorAll(LOCATION_FIELD_SELECTOR)\n\n if (inputs.length !== 2) {\n throw new Error('Expected 2 inputs for lat and long')\n }\n\n const latInput = /** @type {HTMLInputElement} */ (inputs[0])\n const longInput = /** @type {HTMLInputElement} */ (inputs[1])\n\n return { latInput, longInput }\n}\n\n/**\n * Gets the inputs for a easting/northing location field\n * @param {HTMLDivElement} locationField - the eastingnorthing location field element\n */\nfunction getEastingNorthingInputs(locationField) {\n const inputs = locationField.querySelectorAll(LOCATION_FIELD_SELECTOR)\n\n if (inputs.length !== 2) {\n throw new Error('Expected 2 inputs for easting and northing')\n }\n\n const eastingInput = /** @type {HTMLInputElement} */ (inputs[0])\n const northingInput = /** @type {HTMLInputElement} */ (inputs[1])\n\n return { eastingInput, northingInput }\n}\n\n/**\n * Gets the input for a OS grid reference location field\n * @param {HTMLDivElement} locationField - the osgridref location field element\n */\nfunction getOsGridRefInput(locationField) {\n const input = locationField.querySelector(LOCATION_FIELD_SELECTOR)\n\n if (input === null) {\n throw new Error('Expected 1 input for osgridref')\n }\n\n return /** @type {HTMLInputElement} */ (input)\n}\n\n/**\n * Get the initial map config for a center point\n * @param {MapCenter} center - the point\n */\nfunction getInitMapCenterConfig(center) {\n return {\n zoom: '16',\n center,\n markers: [\n {\n id: 'location',\n coords: center\n }\n ]\n }\n}\n\n/**\n * Gets initial map config for a latlong location field\n * @param {HTMLDivElement} locationField - the latlong location field element\n * @returns {InteractiveMapInitConfig | undefined}\n */\nfunction getInitLatLongMapConfig(locationField) {\n const { latInput, longInput } = getLatLongInputs(locationField)\n const result = validateLatLong(latInput.value, longInput.value)\n\n if (!result.valid) {\n return undefined\n }\n\n /** @type {MapCenter} */\n const center = [result.value.long, result.value.lat]\n\n return getInitMapCenterConfig(center)\n}\n\n/**\n * Gets initial map config for a easting/northing location field\n * @param {HTMLDivElement} locationField - the eastingnorthing location field element\n * @returns {InteractiveMapInitConfig | undefined}\n */\nfunction getInitEastingNorthingMapConfig(locationField) {\n const { eastingInput, northingInput } =\n getEastingNorthingInputs(locationField)\n const result = validateEastingNorthing(\n eastingInput.value,\n northingInput.value\n )\n\n if (!result.valid) {\n return undefined\n }\n\n const latlong = eastingNorthingToLatLong(result.value)\n\n /** @type {MapCenter} */\n const center = [latlong.long, latlong.lat]\n\n return getInitMapCenterConfig(center)\n}\n\n/**\n * Gets initial map config for an OS grid reference location field\n * @param {HTMLDivElement} locationField - the osgridref location field element\n * @returns {InteractiveMapInitConfig | undefined}\n */\nfunction getInitOsGridRefMapConfig(locationField) {\n const osGridRefInput = getOsGridRefInput(locationField)\n const result = validateOsGridRef(osGridRefInput.value)\n\n if (!result.valid) {\n return undefined\n }\n\n const latlong = osGridRefToLatLong(result.value)\n\n /** @type {MapCenter} */\n const center = [latlong.long, latlong.lat]\n\n return getInitMapCenterConfig(center)\n}\n\n/**\n * Bind a latlong field to the map\n * @param {HTMLDivElement} locationField - the latlong location field\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n */\nfunction bindLatLongField(locationField, map, mapProvider) {\n const { latInput, longInput } = getLatLongInputs(locationField)\n\n map.on(\n EVENTS.interactMarkerChange,\n /**\n * Callback function which fires when the map marker changes\n * @param {object} e - the event\n * @param {[number, number]} e.coords - the map marker coordinates\n */\n function onInteractMarkerChange(e) {\n const maxPrecision = 7\n latInput.value = e.coords[1].toFixed(maxPrecision)\n longInput.value = e.coords[0].toFixed(maxPrecision)\n }\n )\n\n /**\n * Lat & long input change event listener\n * Update the map view location when the inputs are changed\n */\n function onUpdateInputs() {\n const result = validateLatLong(latInput.value, longInput.value)\n\n if (result.valid) {\n /** @type {MapCenter} */\n const center = [result.value.long, result.value.lat]\n\n centerMap(map, mapProvider, center)\n }\n }\n\n latInput.addEventListener('change', onUpdateInputs, false)\n longInput.addEventListener('change', onUpdateInputs, false)\n}\n\n/**\n * Bind an eastingnorthing field to the map\n * @param {HTMLDivElement} locationField - the eastingnorthing location field\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n */\nfunction bindEastingNorthingField(locationField, map, mapProvider) {\n const { eastingInput, northingInput } =\n getEastingNorthingInputs(locationField)\n\n map.on(\n EVENTS.interactMarkerChange,\n /**\n * Callback function which fires when the map marker changes\n * @param {object} e - the event\n * @param {[number, number]} e.coords - the map marker coordinates\n */\n function onInteractMarkerChange(e) {\n const maxPrecision = 0\n const point = latLongToEastingNorthing({\n lat: e.coords[1],\n long: e.coords[0]\n })\n\n eastingInput.value = point.easting.toFixed(maxPrecision)\n northingInput.value = point.northing.toFixed(maxPrecision)\n }\n )\n\n /**\n * Easting & northing input change event listener\n * Update the map view location when the inputs are changed\n */\n function onUpdateInputs() {\n const result = validateEastingNorthing(\n eastingInput.value,\n northingInput.value\n )\n\n if (result.valid) {\n const latlong = eastingNorthingToLatLong(result.value)\n\n /** @type {MapCenter} */\n const center = [latlong.long, latlong.lat]\n\n centerMap(map, mapProvider, center)\n }\n }\n\n eastingInput.addEventListener('change', onUpdateInputs, false)\n northingInput.addEventListener('change', onUpdateInputs, false)\n}\n\n/**\n * Bind an OS grid reference field to the map\n * @param {HTMLDivElement} locationField - the osgridref location field\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n */\nfunction bindOsGridRefField(locationField, map, mapProvider) {\n const osGridRefInput = getOsGridRefInput(locationField)\n\n map.on(\n EVENTS.interactMarkerChange,\n /**\n * Callback function which fires when the map marker changes\n * @param {object} e - the event\n * @param {[number, number]} e.coords - the map marker coordinates\n */\n function onInteractMarkerChange(e) {\n const point = latLongToOsGridRef({\n lat: e.coords[1],\n long: e.coords[0]\n })\n\n osGridRefInput.value = point\n }\n )\n\n /**\n * OS grid reference input change event listener\n * Update the map view location when the input is changed\n */\n function onUpdateInput() {\n const result = validateOsGridRef(osGridRefInput.value)\n\n if (result.valid) {\n const latlong = osGridRefToLatLong(result.value)\n\n /** @type {MapCenter} */\n const center = [latlong.long, latlong.lat]\n\n centerMap(map, mapProvider, center)\n }\n }\n\n osGridRefInput.addEventListener('change', onUpdateInput, false)\n}\n\n/**\n * Updates the marker position and moves the map view port the new location\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n * @param {MapCenter} center - the point\n */\nfunction centerMap(map, mapProvider, center) {\n // Move the 'location' marker to the new point\n map.addMarker('location', center)\n\n // Pan & zoom the map to the new valid location\n mapProvider.flyTo({\n center,\n zoom: 14,\n essential: true\n })\n}\n\n/**\n * @typedef {object} InteractiveMap - an instance of a InteractiveMap\n * @property {Function} on - register callback listeners to map events\n * @property {Function} addPanel - adds a new panel to the map\n * @property {Function} addMarker - adds/updates a marker\n */\n\n/**\n * @typedef {object} MapLibreMap\n * @property {Function} flyTo - pans/zooms to a new location\n */\n\n/**\n * @typedef {[number, number]} MapCenter - Map center point as [long, lat]\n */\n\n/**\n * @typedef {object} InteractiveMapInitConfig - additional config that can be provided to InteractiveMap\n * @property {string} zoom - the zoom level of the map\n * @property {MapCenter} center - the center point of the map\n * @property {{ id: string, coords: MapCenter}[]} [markers] - the markers to add to the map\n */\n\n/**\n * @typedef {object} TileData\n * @property {string} VTS_OUTDOOR_URL - the outdoor tile URL\n * @property {string} VTS_DARK_URL - the dark tile URL\n * @property {string} VTS_BLACK_AND_WHITE_URL - the black and white tile URL\n */\n\n/**\n * @typedef {object} MapsEnvironmentConfig\n * @property {string} assetPath - the root asset path\n * @property {string} apiPath - the root API path\n * @property {TileData} data - the tile data config\n */\n"],"mappings":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A;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"location-map.js","names":["OsGridRef","LatLon","latLongToEastingNorthing","lat","long","point","toOsGrid","eastingNorthingToLatLong","easting","northing","latLong","toLatLon","latitude","longitude","latLongToOsGridRef","toString","osGridRefToLatLong","osGridRef","parse","DEFAULT_LAT","DEFAULT_LONG","defaultConfig","zoom","center","COMPANY_SYMBOL_CODE","LOCATION_FIELD_SELECTOR","EVENTS","interactMarkerChange","defaultData","VTS_OUTDOOR_URL","VTS_DARK_URL","VTS_BLACK_AND_WHITE_URL","formSubmitFactory","buttons","onFormSubmit","e","submitter","HTMLButtonElement","includes","preventDefault","initMaps","config","assetPath","apiPath","data","locations","document","querySelectorAll","length","form","querySelector","Array","from","addEventListener","forEach","location","index","processLocation","makeTileRequestTransformer","transformTileRequest","url","resourceType","startsWith","replace","window","origin","headers","encodeURIComponent","spritesPath","path","substring","HTMLDivElement","locationInputs","locationType","dataset","locationtype","supportedLocations","mapContainer","createElement","mapId","setAttribute","initConfig","getInitMapConfig","after","map","interactPlugin","createMap","on","onMapReady","bindLatLongField","bindEastingNorthingField","bindOsGridRefField","Error","addPanel","showLabel","label","mobile","slot","initiallyOpen","dismissable","modal","tablet","desktop","html","enable","mapsConfig","logoAltText","defra","dataLayers","markerColor","outdoor","dark","interactionMode","multiSelect","InteractiveMap","mapProvider","maplibreProvider","reverseGeocodeProvider","openNamesProvider","behaviour","minZoom","maxZoom","containerHeight","enableZoomControls","transformRequest","plugins","mapStylesPlugin","mapStyles","id","thumbnail","logo","attribution","String","fromCodePoint","Date","getFullYear","backgroundColor","mapColorScheme","appColorScheme","searchPlugin","osNamesURL","width","showMarker","scaleBarPlugin","units","locationField","getInitLatLongMapConfig","getInitEastingNorthingMapConfig","getInitOsGridRefMapConfig","validateLatLong","strLat","strLong","trim","Number","valid","latMin","latMax","longMin","longMax","latInBounds","longInBounds","value","validateEastingNorthing","strEasting","strNorthing","eastingMin","eastingMax","northingMin","northingMax","validateOsGridRef","pattern","match","exec","getLatLongInputs","inputs","latInput","longInput","getEastingNorthingInputs","eastingInput","northingInput","getOsGridRefInput","input","getInitMapCenterConfig","markers","coords","result","undefined","latlong","osGridRefInput","onInteractMarkerChange","maxPrecision","toFixed","onUpdateInputs","centerMap","onUpdateInput","addMarker","flyTo","essential"],"sources":["../../../src/client/javascripts/location-map.js"],"sourcesContent":["// @ts-expect-error - no types\nimport OsGridRef, { LatLon } from 'geodesy/osgridref.js'\n\n/**\n * Converts lat long to easting and northing\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {{ easting: number, northing: number }}\n */\nfunction latLongToEastingNorthing({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid()\n}\n\n/**\n * Converts easting and northing to lat long\n * @param {object} param\n * @param {number} param.easting\n * @param {number} param.northing\n * @returns {{ lat: number, long: number }}\n */\nfunction eastingNorthingToLatLong({ easting, northing }) {\n const point = new OsGridRef(easting, northing)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Converts lat long to an ordnance survey grid reference\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {string}\n */\nfunction latLongToOsGridRef({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n}\n\n/**\n * Converts an ordnance survey grid reference to lat long\n * @param {string} osGridRef\n * @returns {{ lat: number, long: number }}\n */\nfunction osGridRefToLatLong(osGridRef) {\n const point = OsGridRef.parse(osGridRef)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n// Center of UK\nconst DEFAULT_LAT = 53.825564\nconst DEFAULT_LONG = -2.421975\n\n/** @type {InteractiveMapInitConfig} */\nconst defaultConfig = {\n zoom: '6',\n center: [DEFAULT_LONG, DEFAULT_LAT]\n}\n\nconst COMPANY_SYMBOL_CODE = 169\nconst LOCATION_FIELD_SELECTOR = 'input.govuk-input'\nconst EVENTS = {\n interactMarkerChange: 'interact:markerchange'\n}\n\nconst defaultData = {\n VTS_OUTDOOR_URL: '/api/maps/vts/OS_VTS_3857_Outdoor.json',\n VTS_DARK_URL: '/api/maps/vts/OS_VTS_3857_Dark.json',\n VTS_BLACK_AND_WHITE_URL: '/api/maps/vts/OS_VTS_3857_Black_and_White.json'\n}\n\n/**\n * Make a form submit handler that only allows submissions from allowed buttons\n * @param {HTMLButtonElement[]} buttons - the form buttons to allow submissions\n */\nexport function formSubmitFactory(buttons) {\n /**\n * The submit handler\n * @param {SubmitEvent} e\n */\n const onFormSubmit = function (e) {\n if (\n !(e.submitter instanceof HTMLButtonElement) ||\n !buttons.includes(e.submitter)\n ) {\n e.preventDefault()\n }\n }\n\n return onFormSubmit\n}\n\n/**\n * Initialise location maps\n * @param {Partial<MapsEnvironmentConfig>} config - the map configuration\n */\nexport function initMaps(config = {}) {\n const {\n assetPath = '/assets',\n apiPath = '/form/api',\n data = defaultData\n } = config\n const locations = document.querySelectorAll('.app-location-field')\n\n // TODO: Fix this in `interactive-map`\n // If there are location components on the page fix up the main form submit\n // handler so it doesn't fire when using the integrated map search feature\n if (locations.length) {\n const form = document.querySelector('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n locations.forEach((location, index) => {\n processLocation({ assetPath, apiPath, data }, location, index)\n })\n}\n\n/**\n * OS API request proxy factory\n * @param {string} apiPath - the root API path\n */\nexport function makeTileRequestTransformer(apiPath) {\n /**\n * Proxy OS API requests via our server\n * @param {string} url - the request URL\n * @param {string} resourceType - the resource type\n */\n return function transformTileRequest(url, resourceType) {\n if (url.startsWith('https://api.os.uk')) {\n if (resourceType === 'Tile') {\n return {\n url: url.replace(\n 'https://api.os.uk/maps/vector/v1/vts',\n `${window.location.origin}${apiPath}`\n ),\n headers: {}\n }\n }\n\n if (resourceType !== 'Style') {\n return {\n url: `${apiPath}/map-proxy?url=${encodeURIComponent(url)}`,\n headers: {}\n }\n }\n }\n\n const spritesPath =\n 'https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main'\n\n // Proxy sprite requests\n if (url.startsWith(spritesPath)) {\n const path = url.substring(spritesPath.length)\n return {\n url: `${apiPath}/maps/vts${path}`,\n headers: {}\n }\n }\n\n return { url, headers: {} }\n }\n}\n\n/**\n * Processes a location field to add map capability\n * @param {MapsEnvironmentConfig} config - the location field element\n * @param {Element} location - the location field element\n * @param {*} index - the 0-based index\n */\nfunction processLocation(config, location, index) {\n if (!(location instanceof HTMLDivElement)) {\n return\n }\n\n const locationInputs = location.querySelector('.app-location-field-inputs')\n if (!(locationInputs instanceof HTMLDivElement)) {\n return\n }\n const locationType = location.dataset.locationtype\n\n // Check for support\n const supportedLocations = [\n 'latlongfield',\n 'eastingnorthingfield',\n 'osgridreffield'\n ]\n if (!locationType || !supportedLocations.includes(locationType)) {\n return\n }\n\n const mapContainer = document.createElement('div')\n const mapId = `map_${index}`\n\n mapContainer.setAttribute('id', mapId)\n mapContainer.setAttribute('class', 'map-container')\n\n const initConfig = getInitMapConfig(location) ?? defaultConfig\n\n locationInputs.after(mapContainer)\n\n const { map, interactPlugin } = createMap(mapId, initConfig, config)\n\n map.on(\n 'map:ready',\n /**\n * Callback function which fires when the map is ready\n * @param {object} e - the event\n * @param {MapLibreMap} e.map - the map provider instance\n */\n function onMapReady(e) {\n switch (locationType) {\n case 'latlongfield':\n bindLatLongField(location, map, e.map)\n break\n case 'eastingnorthingfield':\n bindEastingNorthingField(location, map, e.map)\n break\n case 'osgridreffield':\n bindOsGridRefField(location, map, e.map)\n break\n default:\n throw new Error('Not implemented')\n }\n\n // Add info panel\n map.addPanel('info', {\n showLabel: true,\n label: 'How to use the map',\n mobile: {\n slot: 'bottom',\n initiallyOpen: true,\n dismissable: true,\n modal: false\n },\n tablet: {\n slot: 'bottom',\n initiallyOpen: true,\n dismissable: true,\n modal: false\n },\n desktop: {\n slot: 'bottom',\n initiallyOpen: true,\n dismissable: true,\n modal: false\n },\n html: 'If using a map click on a point to update the location.<br><br>If using a keyboard, navigate to the point, centering the crosshair at the location and press enter.'\n })\n\n // Enable the interact plugin\n interactPlugin.enable()\n }\n )\n}\n\n/**\n * Create a Defra map instance\n * @param {string} mapId - the map id\n * @param {InteractiveMapInitConfig} initConfig - the map initial configuration\n * @param {MapsEnvironmentConfig} mapsConfig - the map environment params\n */\nfunction createMap(mapId, initConfig, mapsConfig) {\n const { assetPath, apiPath, data = defaultData } = mapsConfig\n const logoAltText = 'Ordnance survey logo'\n\n // @ts-expect-error - Defra namespace currently comes from UMD support files\n const defra = window.defra\n\n const interactPlugin = defra.interactPlugin({\n dataLayers: [],\n markerColor: { outdoor: '#ff0000', dark: '#00ff00' },\n interactionMode: 'marker',\n multiSelect: false\n })\n\n /** @type {InteractiveMap} */\n const map = new defra.InteractiveMap(mapId, {\n ...initConfig,\n mapProvider: defra.maplibreProvider(),\n reverseGeocodeProvider: defra.openNamesProvider({\n url: `${apiPath}/reverse-geocode-proxy?easting={easting}&northing={northing}`\n }),\n behaviour: 'inline',\n minZoom: 6,\n maxZoom: 18,\n containerHeight: '400px',\n enableZoomControls: true,\n transformRequest: makeTileRequestTransformer(apiPath),\n plugins: [\n defra.mapStylesPlugin({\n mapStyles: [\n {\n id: 'outdoor',\n label: 'Outdoor',\n url: data.VTS_OUTDOOR_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/outdoor-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`,\n backgroundColor: '#f5f5f0'\n },\n {\n id: 'dark',\n label: 'Dark',\n url: data.VTS_DARK_URL,\n mapColorScheme: 'dark',\n appColorScheme: 'dark',\n thumbnail: `${assetPath}/interactive-map/assets/images/dark-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-white.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'black-and-white',\n label: 'Black/White',\n url: data.VTS_BLACK_AND_WHITE_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/black-and-white-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-black.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n }\n ]\n }),\n interactPlugin,\n defra.searchPlugin({\n osNamesURL: `${apiPath}/geocode-proxy?query={query}`,\n width: '300px',\n showMarker: false\n }),\n defra.scaleBarPlugin({\n units: 'metric'\n })\n ]\n })\n\n return { map, interactPlugin }\n}\n\n/**\n * Gets initial map config for a location field\n * @param {HTMLDivElement} locationField - the location field element\n */\nfunction getInitMapConfig(locationField) {\n const locationType = locationField.dataset.locationtype\n\n switch (locationType) {\n case 'latlongfield':\n return getInitLatLongMapConfig(locationField)\n case 'eastingnorthingfield':\n return getInitEastingNorthingMapConfig(locationField)\n case 'osgridreffield':\n return getInitOsGridRefMapConfig(locationField)\n default:\n throw new Error('Not implemented')\n }\n}\n\n/**\n * Validates lat and long is numeric and within UK bounds\n * @param {string} strLat - the latitude string\n * @param {string} strLong - the longitude string\n * @returns {{ valid: false } | { valid: true, value: { lat: number, long: number } }}\n */\nfunction validateLatLong(strLat, strLong) {\n const lat = strLat.trim() && Number(strLat.trim())\n const long = strLong.trim() && Number(strLong.trim())\n\n if (!lat || !long) {\n return { valid: false }\n }\n\n const latMin = 49.85\n const latMax = 60.859\n const longMin = -13.687\n const longMax = 1.767\n\n const latInBounds = lat >= latMin && lat <= latMax\n const longInBounds = long >= longMin && long <= longMax\n\n if (!latInBounds || !longInBounds) {\n return { valid: false }\n }\n\n return { valid: true, value: { lat, long } }\n}\n\n/**\n * Validates easting and northing is numeric and within UK bounds\n * @param {string} strEasting - the easting string\n * @param {string} strNorthing - the northing string\n * @returns {{ valid: false } | { valid: true, value: { easting: number, northing: number } }}\n */\nfunction validateEastingNorthing(strEasting, strNorthing) {\n const easting = strEasting.trim() && Number(strEasting.trim())\n const northing = strNorthing.trim() && Number(strNorthing.trim())\n\n if (!easting || !northing) {\n return { valid: false }\n }\n\n const eastingMin = 0\n const eastingMax = 700000\n const northingMin = 0\n const northingMax = 1300000\n\n const latInBounds = easting >= eastingMin && easting <= eastingMax\n const longInBounds = northing >= northingMin && northing <= northingMax\n\n if (!latInBounds || !longInBounds) {\n return { valid: false }\n }\n\n return { valid: true, value: { easting, northing } }\n}\n\n/**\n * Validates OS grid reference is correct\n * @param {string} osGridRef - the OsGridRef\n * @returns {{ valid: false } | { valid: true, value: string }}\n */\nfunction validateOsGridRef(osGridRef) {\n if (!osGridRef) {\n return { valid: false }\n }\n\n const pattern =\n /^((([sS]|[nN])[a-hA-Hj-zJ-Z])|(([tT]|[oO])[abfglmqrvwABFGLMQRVW])|([hH][l-zL-Z])|([jJ][lmqrvwLMQRVW]))\\s?(([0-9]{3})\\s?([0-9]{3})|([0-9]{4})\\s?([0-9]{4})|([0-9]{5})\\s?([0-9]{5}))$/\n\n const match = pattern.exec(osGridRef)\n\n if (match === null) {\n return { valid: false }\n }\n\n return { valid: true, value: match[0] }\n}\n\n/**\n * Gets the inputs for a latlong location field\n * @param {HTMLDivElement} locationField - the latlong location field element\n */\nfunction getLatLongInputs(locationField) {\n const inputs = locationField.querySelectorAll(LOCATION_FIELD_SELECTOR)\n\n if (inputs.length !== 2) {\n throw new Error('Expected 2 inputs for lat and long')\n }\n\n const latInput = /** @type {HTMLInputElement} */ (inputs[0])\n const longInput = /** @type {HTMLInputElement} */ (inputs[1])\n\n return { latInput, longInput }\n}\n\n/**\n * Gets the inputs for a easting/northing location field\n * @param {HTMLDivElement} locationField - the eastingnorthing location field element\n */\nfunction getEastingNorthingInputs(locationField) {\n const inputs = locationField.querySelectorAll(LOCATION_FIELD_SELECTOR)\n\n if (inputs.length !== 2) {\n throw new Error('Expected 2 inputs for easting and northing')\n }\n\n const eastingInput = /** @type {HTMLInputElement} */ (inputs[0])\n const northingInput = /** @type {HTMLInputElement} */ (inputs[1])\n\n return { eastingInput, northingInput }\n}\n\n/**\n * Gets the input for a OS grid reference location field\n * @param {HTMLDivElement} locationField - the osgridref location field element\n */\nfunction getOsGridRefInput(locationField) {\n const input = locationField.querySelector(LOCATION_FIELD_SELECTOR)\n\n if (input === null) {\n throw new Error('Expected 1 input for osgridref')\n }\n\n return /** @type {HTMLInputElement} */ (input)\n}\n\n/**\n * Get the initial map config for a center point\n * @param {MapCenter} center - the point\n */\nfunction getInitMapCenterConfig(center) {\n return {\n zoom: '16',\n center,\n markers: [\n {\n id: 'location',\n coords: center\n }\n ]\n }\n}\n\n/**\n * Gets initial map config for a latlong location field\n * @param {HTMLDivElement} locationField - the latlong location field element\n * @returns {InteractiveMapInitConfig | undefined}\n */\nfunction getInitLatLongMapConfig(locationField) {\n const { latInput, longInput } = getLatLongInputs(locationField)\n const result = validateLatLong(latInput.value, longInput.value)\n\n if (!result.valid) {\n return undefined\n }\n\n /** @type {MapCenter} */\n const center = [result.value.long, result.value.lat]\n\n return getInitMapCenterConfig(center)\n}\n\n/**\n * Gets initial map config for a easting/northing location field\n * @param {HTMLDivElement} locationField - the eastingnorthing location field element\n * @returns {InteractiveMapInitConfig | undefined}\n */\nfunction getInitEastingNorthingMapConfig(locationField) {\n const { eastingInput, northingInput } =\n getEastingNorthingInputs(locationField)\n const result = validateEastingNorthing(\n eastingInput.value,\n northingInput.value\n )\n\n if (!result.valid) {\n return undefined\n }\n\n const latlong = eastingNorthingToLatLong(result.value)\n\n /** @type {MapCenter} */\n const center = [latlong.long, latlong.lat]\n\n return getInitMapCenterConfig(center)\n}\n\n/**\n * Gets initial map config for an OS grid reference location field\n * @param {HTMLDivElement} locationField - the osgridref location field element\n * @returns {InteractiveMapInitConfig | undefined}\n */\nfunction getInitOsGridRefMapConfig(locationField) {\n const osGridRefInput = getOsGridRefInput(locationField)\n const result = validateOsGridRef(osGridRefInput.value)\n\n if (!result.valid) {\n return undefined\n }\n\n const latlong = osGridRefToLatLong(result.value)\n\n /** @type {MapCenter} */\n const center = [latlong.long, latlong.lat]\n\n return getInitMapCenterConfig(center)\n}\n\n/**\n * Bind a latlong field to the map\n * @param {HTMLDivElement} locationField - the latlong location field\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n */\nfunction bindLatLongField(locationField, map, mapProvider) {\n const { latInput, longInput } = getLatLongInputs(locationField)\n\n map.on(\n EVENTS.interactMarkerChange,\n /**\n * Callback function which fires when the map marker changes\n * @param {object} e - the event\n * @param {[number, number]} e.coords - the map marker coordinates\n */\n function onInteractMarkerChange(e) {\n const maxPrecision = 7\n latInput.value = e.coords[1].toFixed(maxPrecision)\n longInput.value = e.coords[0].toFixed(maxPrecision)\n }\n )\n\n /**\n * Lat & long input change event listener\n * Update the map view location when the inputs are changed\n */\n function onUpdateInputs() {\n const result = validateLatLong(latInput.value, longInput.value)\n\n if (result.valid) {\n /** @type {MapCenter} */\n const center = [result.value.long, result.value.lat]\n\n centerMap(map, mapProvider, center)\n }\n }\n\n latInput.addEventListener('change', onUpdateInputs, false)\n longInput.addEventListener('change', onUpdateInputs, false)\n}\n\n/**\n * Bind an eastingnorthing field to the map\n * @param {HTMLDivElement} locationField - the eastingnorthing location field\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n */\nfunction bindEastingNorthingField(locationField, map, mapProvider) {\n const { eastingInput, northingInput } =\n getEastingNorthingInputs(locationField)\n\n map.on(\n EVENTS.interactMarkerChange,\n /**\n * Callback function which fires when the map marker changes\n * @param {object} e - the event\n * @param {[number, number]} e.coords - the map marker coordinates\n */\n function onInteractMarkerChange(e) {\n const maxPrecision = 0\n const point = latLongToEastingNorthing({\n lat: e.coords[1],\n long: e.coords[0]\n })\n\n eastingInput.value = point.easting.toFixed(maxPrecision)\n northingInput.value = point.northing.toFixed(maxPrecision)\n }\n )\n\n /**\n * Easting & northing input change event listener\n * Update the map view location when the inputs are changed\n */\n function onUpdateInputs() {\n const result = validateEastingNorthing(\n eastingInput.value,\n northingInput.value\n )\n\n if (result.valid) {\n const latlong = eastingNorthingToLatLong(result.value)\n\n /** @type {MapCenter} */\n const center = [latlong.long, latlong.lat]\n\n centerMap(map, mapProvider, center)\n }\n }\n\n eastingInput.addEventListener('change', onUpdateInputs, false)\n northingInput.addEventListener('change', onUpdateInputs, false)\n}\n\n/**\n * Bind an OS grid reference field to the map\n * @param {HTMLDivElement} locationField - the osgridref location field\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n */\nfunction bindOsGridRefField(locationField, map, mapProvider) {\n const osGridRefInput = getOsGridRefInput(locationField)\n\n map.on(\n EVENTS.interactMarkerChange,\n /**\n * Callback function which fires when the map marker changes\n * @param {object} e - the event\n * @param {[number, number]} e.coords - the map marker coordinates\n */\n function onInteractMarkerChange(e) {\n const point = latLongToOsGridRef({\n lat: e.coords[1],\n long: e.coords[0]\n })\n\n osGridRefInput.value = point\n }\n )\n\n /**\n * OS grid reference input change event listener\n * Update the map view location when the input is changed\n */\n function onUpdateInput() {\n const result = validateOsGridRef(osGridRefInput.value)\n\n if (result.valid) {\n const latlong = osGridRefToLatLong(result.value)\n\n /** @type {MapCenter} */\n const center = [latlong.long, latlong.lat]\n\n centerMap(map, mapProvider, center)\n }\n }\n\n osGridRefInput.addEventListener('change', onUpdateInput, false)\n}\n\n/**\n * Updates the marker position and moves the map view port the new location\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n * @param {MapCenter} center - the point\n */\nfunction centerMap(map, mapProvider, center) {\n // Move the 'location' marker to the new point\n map.addMarker('location', center)\n\n // Pan & zoom the map to the new valid location\n mapProvider.flyTo({\n center,\n zoom: 14,\n essential: true\n })\n}\n\n/**\n * @typedef {object} InteractiveMap - an instance of a InteractiveMap\n * @property {Function} on - register callback listeners to map events\n * @property {Function} addPanel - adds a new panel to the map\n * @property {Function} addMarker - adds/updates a marker\n */\n\n/**\n * @typedef {object} MapLibreMap\n * @property {Function} flyTo - pans/zooms to a new location\n */\n\n/**\n * @typedef {[number, number]} MapCenter - Map center point as [long, lat]\n */\n\n/**\n * @typedef {object} InteractiveMapInitConfig - additional config that can be provided to InteractiveMap\n * @property {string} zoom - the zoom level of the map\n * @property {MapCenter} center - the center point of the map\n * @property {{ id: string, coords: MapCenter}[]} [markers] - the markers to add to the map\n */\n\n/**\n * @typedef {object} TileData\n * @property {string} VTS_OUTDOOR_URL - the outdoor tile URL\n * @property {string} VTS_DARK_URL - the dark tile URL\n * @property {string} VTS_BLACK_AND_WHITE_URL - the black and white tile URL\n */\n\n/**\n * @typedef {object} MapsEnvironmentConfig\n * @property {string} assetPath - the root asset path\n * @property {string} apiPath - the root API path\n * @property {TileData} data - the tile data config\n */\n"],"mappings":"AAAA;AACA,OAAOA,SAAS,IAAIC,MAAM,QAAQ,sBAAsB;;AAExD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,wBAAwBA,CAAC;EAAEC,GAAG;EAAEC;AAAK,CAAC,EAAE;EAC/C,MAAMC,KAAK,GAAG,IAAIJ,MAAM,CAACE,GAAG,EAAEC,IAAI,CAAC;EAEnC,OAAOC,KAAK,CAACC,QAAQ,CAAC,CAAC;AACzB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,wBAAwBA,CAAC;EAAEC,OAAO;EAAEC;AAAS,CAAC,EAAE;EACvD,MAAMJ,KAAK,GAAG,IAAIL,SAAS,CAACQ,OAAO,EAAEC,QAAQ,CAAC;EAC9C,MA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,CAAC;;EAED;AACF;AACA;AACA;EACE,SAAS6L,aAAaA,CAAA,EAAG;IACvB,MAAMT,MAAM,GAAGhB,iBAAiB,CAACmB,cAAc,CAAC3B,KAAK,CAAC;IAEtD,IAAIwB,MAAM,CAAC/B,KAAK,EAAE;MAChB,MAAMiC,OAAO,GAAG3K,kBAAkB,CAACyK,MAAM,CAACxB,KAAK,CAAC;;MAEhD;MACA,MAAM1I,MAAM,GAAG,CAACoK,OAAO,CAACvL,IAAI,EAAEuL,OAAO,CAACxL,GAAG,CAAC;MAE1C8L,SAAS,CAAC7G,GAAG,EAAE+B,WAAW,EAAE5F,MAAM,CAAC;IACrC;EACF;EAEAqK,cAAc,CAACvI,gBAAgB,CAAC,QAAQ,EAAE6I,aAAa,EAAE,KAAK,CAAC;AACjE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAASD,SAASA,CAAC7G,GAAG,EAAE+B,WAAW,EAAE5F,MAAM,EAAE;EAC3C;EACA6D,GAAG,CAAC+G,SAAS,CAAC,UAAU,EAAE5K,MAAM,CAAC;;EAEjC;EACA4F,WAAW,CAACiF,KAAK,CAAC;IAChB7K,MAAM;IACND,IAAI,EAAE,EAAE;IACR+K,SAAS,EAAE;EACb,CAAC,CAAC;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]}
|
|
@@ -3,7 +3,7 @@ import { plugin } from '~/src/server/plugins/engine/plugin.js';
|
|
|
3
3
|
import { type PluginOptions } from '~/src/server/plugins/engine/types.js';
|
|
4
4
|
import { type CacheService } from '~/src/server/services/cacheService.js';
|
|
5
5
|
import { type RouteConfig } from '~/src/server/types.js';
|
|
6
|
-
export declare const configureEnginePlugin: ({ formFileName, formFilePath, services, controllers, preparePageEventRequestOptions, onRequest, saveAndExit, ordnanceSurveyApiKey }?: RouteConfig, cache?: CacheService) => Promise<{
|
|
6
|
+
export declare const configureEnginePlugin: ({ formFileName, formFilePath, services, controllers, preparePageEventRequestOptions, onRequest, saveAndExit, ordnanceSurveyApiKey, ordnanceSurveyApiSecret }?: RouteConfig, cache?: CacheService) => Promise<{
|
|
7
7
|
plugin: typeof plugin;
|
|
8
8
|
options: PluginOptions;
|
|
9
9
|
}>;
|
|
@@ -14,7 +14,8 @@ export const configureEnginePlugin = async ({
|
|
|
14
14
|
preparePageEventRequestOptions,
|
|
15
15
|
onRequest,
|
|
16
16
|
saveAndExit,
|
|
17
|
-
ordnanceSurveyApiKey
|
|
17
|
+
ordnanceSurveyApiKey,
|
|
18
|
+
ordnanceSurveyApiSecret
|
|
18
19
|
} = {}, cache) => {
|
|
19
20
|
let model;
|
|
20
21
|
if (formFileName && formFilePath) {
|
|
@@ -49,7 +50,8 @@ export const configureEnginePlugin = async ({
|
|
|
49
50
|
baseUrl: 'http://localhost:3009',
|
|
50
51
|
// always runs locally
|
|
51
52
|
saveAndExit,
|
|
52
|
-
ordnanceSurveyApiKey
|
|
53
|
+
ordnanceSurveyApiKey,
|
|
54
|
+
ordnanceSurveyApiSecret
|
|
53
55
|
}
|
|
54
56
|
};
|
|
55
57
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configureEnginePlugin.js","names":["join","parse","FORM_PREFIX","FormModel","plugin","defaultServices","formsService","findPackageRoot","devtoolContext","configureEnginePlugin","formFileName","formFilePath","services","controllers","preparePageEventRequestOptions","onRequest","saveAndExit","ordnanceSurveyApiKey","cache","model","definition","getForm","name","initialBasePath","basePath","options","nunjucks","baseLayoutPath","paths","viewContext","baseUrl","importPath","ext","attributes","type","formImport","with","default"],"sources":["../../../../src/server/plugins/engine/configureEnginePlugin.ts"],"sourcesContent":["import { join, parse } from 'node:path'\n\nimport { type FormDefinition } from '@defra/forms-model'\n\nimport { FORM_PREFIX } from '~/src/server/constants.js'\nimport { FormModel } from '~/src/server/plugins/engine/models/FormModel.js'\nimport { plugin } from '~/src/server/plugins/engine/plugin.js'\nimport * as defaultServices from '~/src/server/plugins/engine/services/index.js'\nimport { formsService } from '~/src/server/plugins/engine/services/localFormsService.js'\nimport { type PluginOptions } from '~/src/server/plugins/engine/types.js'\nimport { findPackageRoot } from '~/src/server/plugins/engine/vision.js'\nimport { devtoolContext } from '~/src/server/plugins/nunjucks/context.js'\nimport { type CacheService } from '~/src/server/services/cacheService.js'\nimport { type RouteConfig } from '~/src/server/types.js'\n\nexport const configureEnginePlugin = async (\n {\n formFileName,\n formFilePath,\n services,\n controllers,\n preparePageEventRequestOptions,\n onRequest,\n saveAndExit,\n ordnanceSurveyApiKey\n }: RouteConfig = {},\n cache?: CacheService\n): Promise<{\n plugin: typeof plugin\n options: PluginOptions\n}> => {\n let model: FormModel | undefined\n\n if (formFileName && formFilePath) {\n const definition = await getForm(join(formFilePath, formFileName))\n const { name } = parse(formFileName)\n\n const initialBasePath = `${FORM_PREFIX}${name}`\n\n model = new FormModel(\n definition,\n { basePath: initialBasePath, ordnanceSurveyApiKey },\n services,\n controllers\n )\n }\n\n return {\n plugin,\n options: {\n model,\n services: services ?? {\n // services for testing, else use the disk loader option for running this service locally\n ...defaultServices,\n formsService: await formsService()\n },\n controllers,\n cache: cache ?? 'session',\n nunjucks: {\n baseLayoutPath: 'dxt-devtool-baselayout.html',\n paths: [join(findPackageRoot(), 'src/server/devserver')] // custom layout to make it really clear this is not the same as the runner\n },\n viewContext: devtoolContext,\n preparePageEventRequestOptions,\n onRequest,\n baseUrl: 'http://localhost:3009', // always runs locally\n saveAndExit,\n ordnanceSurveyApiKey\n }\n }\n}\n\nexport async function getForm(importPath: string) {\n const { ext } = parse(importPath)\n\n const attributes: ImportAttributes = {\n type: ext === '.json' ? 'json' : 'module'\n }\n\n const formImport = import(importPath, { with: attributes }) as Promise<{\n default: FormDefinition\n }>\n\n const { default: definition } = await formImport\n return definition\n}\n"],"mappings":"AAAA,SAASA,IAAI,EAAEC,KAAK,QAAQ,WAAW;AAIvC,SAASC,WAAW;AACpB,SAASC,SAAS;AAClB,SAASC,MAAM;AACf,OAAO,KAAKC,eAAe;AAC3B,SAASC,YAAY;AAErB,SAASC,eAAe;AACxB,SAASC,cAAc;AAIvB,OAAO,MAAMC,qBAAqB,GAAG,MAAAA,CACnC;EACEC,YAAY;EACZC,YAAY;EACZC,QAAQ;EACRC,WAAW;EACXC,8BAA8B;EAC9BC,SAAS;EACTC,WAAW;EACXC;AACW,CAAC,GAAG,CAAC,CAAC,EACnBC,KAAoB,KAIhB;EACJ,IAAIC,KAA4B;EAEhC,
|
|
1
|
+
{"version":3,"file":"configureEnginePlugin.js","names":["join","parse","FORM_PREFIX","FormModel","plugin","defaultServices","formsService","findPackageRoot","devtoolContext","configureEnginePlugin","formFileName","formFilePath","services","controllers","preparePageEventRequestOptions","onRequest","saveAndExit","ordnanceSurveyApiKey","ordnanceSurveyApiSecret","cache","model","definition","getForm","name","initialBasePath","basePath","options","nunjucks","baseLayoutPath","paths","viewContext","baseUrl","importPath","ext","attributes","type","formImport","with","default"],"sources":["../../../../src/server/plugins/engine/configureEnginePlugin.ts"],"sourcesContent":["import { join, parse } from 'node:path'\n\nimport { type FormDefinition } from '@defra/forms-model'\n\nimport { FORM_PREFIX } from '~/src/server/constants.js'\nimport { FormModel } from '~/src/server/plugins/engine/models/FormModel.js'\nimport { plugin } from '~/src/server/plugins/engine/plugin.js'\nimport * as defaultServices from '~/src/server/plugins/engine/services/index.js'\nimport { formsService } from '~/src/server/plugins/engine/services/localFormsService.js'\nimport { type PluginOptions } from '~/src/server/plugins/engine/types.js'\nimport { findPackageRoot } from '~/src/server/plugins/engine/vision.js'\nimport { devtoolContext } from '~/src/server/plugins/nunjucks/context.js'\nimport { type CacheService } from '~/src/server/services/cacheService.js'\nimport { type RouteConfig } from '~/src/server/types.js'\n\nexport const configureEnginePlugin = async (\n {\n formFileName,\n formFilePath,\n services,\n controllers,\n preparePageEventRequestOptions,\n onRequest,\n saveAndExit,\n ordnanceSurveyApiKey,\n ordnanceSurveyApiSecret\n }: RouteConfig = {},\n cache?: CacheService\n): Promise<{\n plugin: typeof plugin\n options: PluginOptions\n}> => {\n let model: FormModel | undefined\n\n if (formFileName && formFilePath) {\n const definition = await getForm(join(formFilePath, formFileName))\n const { name } = parse(formFileName)\n\n const initialBasePath = `${FORM_PREFIX}${name}`\n\n model = new FormModel(\n definition,\n { basePath: initialBasePath, ordnanceSurveyApiKey },\n services,\n controllers\n )\n }\n\n return {\n plugin,\n options: {\n model,\n services: services ?? {\n // services for testing, else use the disk loader option for running this service locally\n ...defaultServices,\n formsService: await formsService()\n },\n controllers,\n cache: cache ?? 'session',\n nunjucks: {\n baseLayoutPath: 'dxt-devtool-baselayout.html',\n paths: [join(findPackageRoot(), 'src/server/devserver')] // custom layout to make it really clear this is not the same as the runner\n },\n viewContext: devtoolContext,\n preparePageEventRequestOptions,\n onRequest,\n baseUrl: 'http://localhost:3009', // always runs locally\n saveAndExit,\n ordnanceSurveyApiKey,\n ordnanceSurveyApiSecret\n }\n }\n}\n\nexport async function getForm(importPath: string) {\n const { ext } = parse(importPath)\n\n const attributes: ImportAttributes = {\n type: ext === '.json' ? 'json' : 'module'\n }\n\n const formImport = import(importPath, { with: attributes }) as Promise<{\n default: FormDefinition\n }>\n\n const { default: definition } = await formImport\n return definition\n}\n"],"mappings":"AAAA,SAASA,IAAI,EAAEC,KAAK,QAAQ,WAAW;AAIvC,SAASC,WAAW;AACpB,SAASC,SAAS;AAClB,SAASC,MAAM;AACf,OAAO,KAAKC,eAAe;AAC3B,SAASC,YAAY;AAErB,SAASC,eAAe;AACxB,SAASC,cAAc;AAIvB,OAAO,MAAMC,qBAAqB,GAAG,MAAAA,CACnC;EACEC,YAAY;EACZC,YAAY;EACZC,QAAQ;EACRC,WAAW;EACXC,8BAA8B;EAC9BC,SAAS;EACTC,WAAW;EACXC,oBAAoB;EACpBC;AACW,CAAC,GAAG,CAAC,CAAC,EAC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AAC,CAExD;EAEF,MAAM;IAAEI,OAAO,EAAEjB;EAAW,CAAC,GAAG,MAAMe,UAAU;EAChD,OAAOf,UAAU;AACnB","ignoreList":[]}
|
|
@@ -20,7 +20,8 @@ const pluginRegistrationOptionsSchema = Joi.object({
|
|
|
20
20
|
onRequest: Joi.function().optional(),
|
|
21
21
|
baseUrl: Joi.string().uri().required(),
|
|
22
22
|
saveAndExit: Joi.function().optional(),
|
|
23
|
-
ordnanceSurveyApiKey: Joi.string().optional()
|
|
23
|
+
ordnanceSurveyApiKey: Joi.string().optional(),
|
|
24
|
+
ordnanceSurveyApiSecret: Joi.string().optional()
|
|
24
25
|
});
|
|
25
26
|
|
|
26
27
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":["getErrorMessage","Joi","createLogger","CacheService","logger","pluginRegistrationOptionsSchema","object","model","optional","services","controllers","pattern","string","any","cache","alternatives","try","instance","globals","filters","pluginPath","nunjucks","baseLayoutPath","required","paths","array","items","viewContext","function","preparePageEventRequestOptions","onRequest","baseUrl","uri","saveAndExit","ordnanceSurveyApiKey","validatePluginOptions","options","result","validate","abortEarly","error","Error","value"],"sources":["../../../../src/server/plugins/engine/options.js"],"sourcesContent":["import { getErrorMessage } from '@defra/forms-model'\nimport Joi from 'joi'\n\nimport { createLogger } from '~/src/server/common/helpers/logging/logger.js'\nimport { CacheService } from '~/src/server/services/index.js'\n\nconst logger = createLogger()\n\nconst pluginRegistrationOptionsSchema = Joi.object({\n model: Joi.object().optional(),\n services: Joi.object().optional(),\n controllers: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n cache: Joi.alternatives().try(\n Joi.object().instance(CacheService),\n Joi.string()\n ),\n globals: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n filters: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n pluginPath: Joi.string().optional(),\n nunjucks: Joi.object({\n baseLayoutPath: Joi.string().required(),\n paths: Joi.array().items(Joi.string()).required()\n }).required(),\n viewContext: Joi.function().required(),\n preparePageEventRequestOptions: Joi.function().optional(),\n onRequest: Joi.function().optional(),\n baseUrl: Joi.string().uri().required(),\n saveAndExit: Joi.function().optional(),\n ordnanceSurveyApiKey: Joi.string().optional()\n})\n\n/**\n * Validates the plugin options against the schema and returns the validated value.\n * @param {PluginOptions} options\n * @returns {PluginOptions}\n */\nexport function validatePluginOptions(options) {\n const result = pluginRegistrationOptionsSchema.validate(options, {\n abortEarly: false\n })\n\n if (result.error) {\n logger.error(\n result.error,\n `Missing required properties in plugin options: ${getErrorMessage(result.error)}`\n )\n throw new Error('Invalid plugin options', result.error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return result.value\n}\n\n/**\n * @import { PluginOptions } from '~/src/server/plugins/engine/types.js'\n */\n"],"mappings":"AAAA,SAASA,eAAe,QAAQ,oBAAoB;AACpD,OAAOC,GAAG,MAAM,KAAK;AAErB,SAASC,YAAY;AACrB,SAASC,YAAY;AAErB,MAAMC,MAAM,GAAGF,YAAY,CAAC,CAAC;AAE7B,MAAMG,+BAA+B,GAAGJ,GAAG,CAACK,MAAM,CAAC;EACjDC,KAAK,EAAEN,GAAG,CAACK,MAAM,CAAC,CAAC,CAACE,QAAQ,CAAC,CAAC;EAC9BC,QAAQ,EAAER,GAAG,CAACK,MAAM,CAAC,CAAC,CAACE,QAAQ,CAAC,CAAC;EACjCE,WAAW,EAAET,GAAG,CAACK,MAAM,CAAC,CAAC,CAACK,OAAO,CAACV,GAAG,CAACW,MAAM,CAAC,CAAC,EAAEX,GAAG,CAACY,GAAG,CAAC,CAAC,CAAC,CAACL,QAAQ,CAAC,CAAC;EACrEM,KAAK,EAAEb,GAAG,CAACc,YAAY,CAAC,CAAC,CAACC,GAAG,CAC3Bf,GAAG,CAACK,MAAM,CAAC,CAAC,CAACW,QAAQ,CAACd,YAAY,CAAC,EACnCF,GAAG,CAACW,MAAM,CAAC,CACb,CAAC;EACDM,OAAO,EAAEjB,GAAG,CAACK,MAAM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CacheService","logger","pluginRegistrationOptionsSchema","object","model","optional","services","controllers","pattern","string","any","cache","alternatives","try","instance","globals","filters","pluginPath","nunjucks","baseLayoutPath","required","paths","array","items","viewContext","function","preparePageEventRequestOptions","onRequest","baseUrl","uri","saveAndExit","ordnanceSurveyApiKey","ordnanceSurveyApiSecret","validatePluginOptions","options","result","validate","abortEarly","error","Error","value"],"sources":["../../../../src/server/plugins/engine/options.js"],"sourcesContent":["import { getErrorMessage } from '@defra/forms-model'\nimport Joi from 'joi'\n\nimport { createLogger } from '~/src/server/common/helpers/logging/logger.js'\nimport { CacheService } from '~/src/server/services/index.js'\n\nconst logger = createLogger()\n\nconst pluginRegistrationOptionsSchema = Joi.object({\n model: Joi.object().optional(),\n services: Joi.object().optional(),\n controllers: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n cache: Joi.alternatives().try(\n Joi.object().instance(CacheService),\n Joi.string()\n ),\n globals: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n filters: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n pluginPath: Joi.string().optional(),\n nunjucks: Joi.object({\n baseLayoutPath: Joi.string().required(),\n paths: Joi.array().items(Joi.string()).required()\n }).required(),\n viewContext: Joi.function().required(),\n preparePageEventRequestOptions: Joi.function().optional(),\n onRequest: Joi.function().optional(),\n baseUrl: Joi.string().uri().required(),\n saveAndExit: Joi.function().optional(),\n ordnanceSurveyApiKey: Joi.string().optional(),\n ordnanceSurveyApiSecret: Joi.string().optional()\n})\n\n/**\n * Validates the plugin options against the schema and returns the validated value.\n * @param {PluginOptions} options\n * @returns {PluginOptions}\n */\nexport function validatePluginOptions(options) {\n const result = pluginRegistrationOptionsSchema.validate(options, {\n abortEarly: false\n })\n\n if (result.error) {\n logger.error(\n result.error,\n `Missing required properties in plugin options: ${getErrorMessage(result.error)}`\n )\n throw new Error('Invalid plugin options', result.error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return result.value\n}\n\n/**\n * @import { PluginOptions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EAEA;EACA,OAAOH,MAAM,CAACK,KAAK;AACrB;;AAEA;AACA;AACA","ignoreList":[]}
|
|
@@ -22,7 +22,8 @@ export const plugin = {
|
|
|
22
22
|
viewContext,
|
|
23
23
|
preparePageEventRequestOptions,
|
|
24
24
|
onRequest,
|
|
25
|
-
ordnanceSurveyApiKey
|
|
25
|
+
ordnanceSurveyApiKey,
|
|
26
|
+
ordnanceSurveyApiSecret
|
|
26
27
|
} = options;
|
|
27
28
|
const cacheService = typeof cache === 'string' ? new CacheService({
|
|
28
29
|
server,
|
|
@@ -40,12 +41,13 @@ export const plugin = {
|
|
|
40
41
|
});
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
// Register the maps plugin only if we have an OS api key
|
|
44
|
-
if (ordnanceSurveyApiKey) {
|
|
44
|
+
// Register the maps plugin only if we have an OS api key & secret
|
|
45
|
+
if (ordnanceSurveyApiKey && ordnanceSurveyApiSecret) {
|
|
45
46
|
await server.register({
|
|
46
47
|
plugin: mapPlugin,
|
|
47
48
|
options: {
|
|
48
|
-
ordnanceSurveyApiKey
|
|
49
|
+
ordnanceSurveyApiKey,
|
|
50
|
+
ordnanceSurveyApiSecret
|
|
49
51
|
}
|
|
50
52
|
});
|
|
51
53
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","names":["validatePluginOptions","getRoutes","getFileUploadStatusRoutes","makeLoadFormPreHandler","getQuestionRoutes","getRepeaterItemDeleteRoutes","getRepeaterSummaryRoutes","registerVision","mapPlugin","postcodeLookupPlugin","CacheService","plugin","name","dependencies","multiple","register","server","options","model","cache","saveAndExit","nunjucks","nunjucksOptions","viewContext","preparePageEventRequestOptions","onRequest","ordnanceSurveyApiKey","cacheService","cacheName","expose","baseLayoutPath","app","itemCache","Map","models","loadFormPreHandler","getRouteOptions","pre","method","postRouteOptions","payload","parse","routes","route"],"sources":["../../../../src/server/plugins/engine/plugin.ts"],"sourcesContent":["import {\n type Lifecycle,\n type Plugin,\n type RouteOptions,\n type Server,\n type ServerRoute\n} from '@hapi/hapi'\n\nimport { type FormModel } from '~/src/server/plugins/engine/models/index.js'\nimport { validatePluginOptions } from '~/src/server/plugins/engine/options.js'\nimport { getRoutes as getFileUploadStatusRoutes } from '~/src/server/plugins/engine/routes/file-upload.js'\nimport { makeLoadFormPreHandler } from '~/src/server/plugins/engine/routes/index.js'\nimport { getRoutes as getQuestionRoutes } from '~/src/server/plugins/engine/routes/questions.js'\nimport { getRoutes as getRepeaterItemDeleteRoutes } from '~/src/server/plugins/engine/routes/repeaters/item-delete.js'\nimport { getRoutes as getRepeaterSummaryRoutes } from '~/src/server/plugins/engine/routes/repeaters/summary.js'\nimport { type PluginOptions } from '~/src/server/plugins/engine/types.js'\nimport { registerVision } from '~/src/server/plugins/engine/vision.js'\nimport { mapPlugin } from '~/src/server/plugins/map/index.js'\nimport { postcodeLookupPlugin } from '~/src/server/plugins/postcode-lookup/index.js'\nimport {\n type FormRequestPayloadRefs,\n type FormRequestRefs\n} from '~/src/server/routes/types.js'\nimport { CacheService } from '~/src/server/services/index.js'\n\nexport const plugin = {\n name: '@defra/forms-engine-plugin',\n dependencies: ['@hapi/crumb', '@hapi/yar', 'hapi-pino'],\n multiple: true,\n async register(server: Server, options: PluginOptions) {\n options = validatePluginOptions(options)\n\n const {\n model,\n cache,\n saveAndExit,\n nunjucks: nunjucksOptions,\n viewContext,\n preparePageEventRequestOptions,\n onRequest,\n ordnanceSurveyApiKey\n } = options\n\n const cacheService =\n typeof cache === 'string'\n ? new CacheService({ server, cacheName: cache })\n : cache\n\n await registerVision(server, options)\n\n // Register the postcode lookup plugin only if we have an OS api key\n if (ordnanceSurveyApiKey) {\n await server.register({\n plugin: postcodeLookupPlugin,\n options: {\n ordnanceSurveyApiKey\n }\n })\n }\n\n // Register the maps plugin only if we have an OS api key\n if (ordnanceSurveyApiKey) {\n await server.register({\n plugin: mapPlugin,\n options: {\n ordnanceSurveyApiKey\n }\n })\n }\n\n server.expose('baseLayoutPath', nunjucksOptions.baseLayoutPath)\n server.expose('viewContext', viewContext)\n server.expose('cacheService', cacheService)\n server.expose('saveAndExit', saveAndExit)\n\n server.app.model = model\n\n // In-memory cache of FormModel items, exposed\n // (for testing purposes) through `server.app.models`\n const itemCache = new Map<string, { model: FormModel; updatedAt: Date }>()\n server.app.models = itemCache\n\n const loadFormPreHandler = makeLoadFormPreHandler(server, options)\n\n const getRouteOptions: RouteOptions<FormRequestRefs> = {\n pre: [\n {\n method:\n loadFormPreHandler as unknown as Lifecycle.Method<FormRequestRefs>\n }\n ]\n }\n\n const postRouteOptions: RouteOptions<FormRequestPayloadRefs> = {\n payload: {\n parse: true\n },\n pre: [\n {\n method:\n loadFormPreHandler as unknown as Lifecycle.Method<FormRequestPayloadRefs>\n }\n ]\n }\n\n const routes = [\n ...getQuestionRoutes(\n getRouteOptions,\n postRouteOptions,\n preparePageEventRequestOptions,\n onRequest\n ),\n ...getRepeaterSummaryRoutes(getRouteOptions, postRouteOptions, onRequest),\n ...getRepeaterItemDeleteRoutes(\n getRouteOptions,\n postRouteOptions,\n onRequest\n ),\n ...getFileUploadStatusRoutes()\n ]\n\n server.route(routes as unknown as ServerRoute[]) // TODO\n }\n} satisfies Plugin<PluginOptions>\n"],"mappings":"AASA,SAASA,qBAAqB;AAC9B,SAASC,SAAS,IAAIC,yBAAyB;AAC/C,SAASC,sBAAsB;AAC/B,SAASF,SAAS,IAAIG,iBAAiB;AACvC,SAASH,SAAS,IAAII,2BAA2B;AACjD,SAASJ,SAAS,IAAIK,wBAAwB;AAE9C,SAASC,cAAc;AACvB,SAASC,SAAS;AAClB,SAASC,oBAAoB;AAK7B,SAASC,YAAY;AAErB,OAAO,MAAMC,MAAM,GAAG;EACpBC,IAAI,EAAE,4BAA4B;EAClCC,YAAY,EAAE,CAAC,aAAa,EAAE,WAAW,EAAE,WAAW,CAAC;EACvDC,QAAQ,EAAE,IAAI;EACd,MAAMC,QAAQA,CAACC,MAAc,EAAEC,OAAsB,EAAE;IACrDA,OAAO,GAAGjB,qBAAqB,CAACiB,OAAO,CAAC;IAExC,MAAM;MACJC,KAAK;MACLC,KAAK;MACLC,WAAW;MACXC,QAAQ,EAAEC,eAAe;MACzBC,WAAW;MACXC,8BAA8B;MAC9BC,SAAS;MACTC;IACF,CAAC,
|
|
1
|
+
{"version":3,"file":"plugin.js","names":["validatePluginOptions","getRoutes","getFileUploadStatusRoutes","makeLoadFormPreHandler","getQuestionRoutes","getRepeaterItemDeleteRoutes","getRepeaterSummaryRoutes","registerVision","mapPlugin","postcodeLookupPlugin","CacheService","plugin","name","dependencies","multiple","register","server","options","model","cache","saveAndExit","nunjucks","nunjucksOptions","viewContext","preparePageEventRequestOptions","onRequest","ordnanceSurveyApiKey","ordnanceSurveyApiSecret","cacheService","cacheName","expose","baseLayoutPath","app","itemCache","Map","models","loadFormPreHandler","getRouteOptions","pre","method","postRouteOptions","payload","parse","routes","route"],"sources":["../../../../src/server/plugins/engine/plugin.ts"],"sourcesContent":["import {\n type Lifecycle,\n type Plugin,\n type RouteOptions,\n type Server,\n type ServerRoute\n} from '@hapi/hapi'\n\nimport { type FormModel } from '~/src/server/plugins/engine/models/index.js'\nimport { validatePluginOptions } from '~/src/server/plugins/engine/options.js'\nimport { getRoutes as getFileUploadStatusRoutes } from '~/src/server/plugins/engine/routes/file-upload.js'\nimport { makeLoadFormPreHandler } from '~/src/server/plugins/engine/routes/index.js'\nimport { getRoutes as getQuestionRoutes } from '~/src/server/plugins/engine/routes/questions.js'\nimport { getRoutes as getRepeaterItemDeleteRoutes } from '~/src/server/plugins/engine/routes/repeaters/item-delete.js'\nimport { getRoutes as getRepeaterSummaryRoutes } from '~/src/server/plugins/engine/routes/repeaters/summary.js'\nimport { type PluginOptions } from '~/src/server/plugins/engine/types.js'\nimport { registerVision } from '~/src/server/plugins/engine/vision.js'\nimport { mapPlugin } from '~/src/server/plugins/map/index.js'\nimport { postcodeLookupPlugin } from '~/src/server/plugins/postcode-lookup/index.js'\nimport {\n type FormRequestPayloadRefs,\n type FormRequestRefs\n} from '~/src/server/routes/types.js'\nimport { CacheService } from '~/src/server/services/index.js'\n\nexport const plugin = {\n name: '@defra/forms-engine-plugin',\n dependencies: ['@hapi/crumb', '@hapi/yar', 'hapi-pino'],\n multiple: true,\n async register(server: Server, options: PluginOptions) {\n options = validatePluginOptions(options)\n\n const {\n model,\n cache,\n saveAndExit,\n nunjucks: nunjucksOptions,\n viewContext,\n preparePageEventRequestOptions,\n onRequest,\n ordnanceSurveyApiKey,\n ordnanceSurveyApiSecret\n } = options\n\n const cacheService =\n typeof cache === 'string'\n ? new CacheService({ server, cacheName: cache })\n : cache\n\n await registerVision(server, options)\n\n // Register the postcode lookup plugin only if we have an OS api key\n if (ordnanceSurveyApiKey) {\n await server.register({\n plugin: postcodeLookupPlugin,\n options: {\n ordnanceSurveyApiKey\n }\n })\n }\n\n // Register the maps plugin only if we have an OS api key & secret\n if (ordnanceSurveyApiKey && ordnanceSurveyApiSecret) {\n await server.register({\n plugin: mapPlugin,\n options: {\n ordnanceSurveyApiKey,\n ordnanceSurveyApiSecret\n }\n })\n }\n\n server.expose('baseLayoutPath', nunjucksOptions.baseLayoutPath)\n server.expose('viewContext', viewContext)\n server.expose('cacheService', cacheService)\n server.expose('saveAndExit', saveAndExit)\n\n server.app.model = model\n\n // In-memory cache of FormModel items, exposed\n // (for testing purposes) through `server.app.models`\n const itemCache = new Map<string, { model: FormModel; updatedAt: Date }>()\n server.app.models = itemCache\n\n const loadFormPreHandler = makeLoadFormPreHandler(server, options)\n\n const getRouteOptions: RouteOptions<FormRequestRefs> = {\n pre: [\n {\n method:\n loadFormPreHandler as unknown as Lifecycle.Method<FormRequestRefs>\n }\n ]\n }\n\n const postRouteOptions: RouteOptions<FormRequestPayloadRefs> = {\n payload: {\n parse: true\n },\n pre: [\n {\n method:\n loadFormPreHandler as unknown as Lifecycle.Method<FormRequestPayloadRefs>\n }\n ]\n }\n\n const routes = [\n ...getQuestionRoutes(\n getRouteOptions,\n postRouteOptions,\n preparePageEventRequestOptions,\n onRequest\n ),\n ...getRepeaterSummaryRoutes(getRouteOptions, postRouteOptions, onRequest),\n ...getRepeaterItemDeleteRoutes(\n getRouteOptions,\n postRouteOptions,\n onRequest\n ),\n ...getFileUploadStatusRoutes()\n ]\n\n server.route(routes as unknown as ServerRoute[]) // TODO\n }\n} satisfies Plugin<PluginOptions>\n"],"mappings":"AASA,SAASA,qBAAqB;AAC9B,SAASC,SAAS,IAAIC,yBAAyB;AAC/C,SAASC,sBAAsB;AAC/B,SAASF,SAAS,IAAIG,iBAAiB;AACvC,SAASH,SAAS,IAAII,2BAA2B;AACjD,SAASJ,SAAS,IAAIK,wBAAwB;AAE9C,SAASC,cAAc;AACvB,SAASC,SAAS;AAClB,SAASC,oBAAoB;AAK7B,SAASC,YAAY;AAErB,OAAO,MAAMC,MAAM,GAAG;EACpBC,IAAI,EAAE,4BAA4B;EAClCC,YAAY,EAAE,CAAC,aAAa,EAAE,WAAW,EAAE,WAAW,CAAC;EACvDC,QAAQ,EAAE,IAAI;EACd,MAAMC,QAAQA,CAACC,MAAc,EAAEC,OAAsB,EAAE;IACrDA,OAAO,GAAGjB,qBAAqB,CAACiB,OAAO,CAAC;IAExC,MAAM;MACJC,KAAK;MACLC,KAAK;MACLC,WAAW;MACXC,QAAQ,EAAEC,eAAe;MACzBC,WAAW;MACXC,8BAA8B;MAC9BC,SAAS;MACTC,oBAAoB;MACpBC;IACF,CAAC,GAAGV,OAAO;IAEX,MAAMW,YAAY,GAChB,OAAOT,KAAK,KAAK,QAAQ,GACrB,IAAIT,YAAY,CAAC;MAAEM,MAAM;MAAEa,SAAS,EAAEV;IAAM,CAAC,CAAC,GAC9CA,KAAK;IAEX,MAAMZ,cAAc,CAACS,MAAM,EAAEC,OAAO,CAAC;;IAErC;IACA,IAAIS,oBAAoB,EAAE;MACxB,MAAMV,MAAM,CAACD,QAAQ,CAAC;QACpBJ,MAAM,EAAEF,oBAAoB;QAC5BQ,OAAO,EAAE;UACPS;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,MAAM,CAAC4B,KAAK,CAACD,MAAkC,CAAC,EAAC;EACnD;AACF,CAAiC","ignoreList":[]}
|
|
@@ -303,6 +303,7 @@ export interface PluginOptions {
|
|
|
303
303
|
onRequest?: OnRequestCallback;
|
|
304
304
|
baseUrl: string;
|
|
305
305
|
ordnanceSurveyApiKey?: string;
|
|
306
|
+
ordnanceSurveyApiSecret?: string;
|
|
306
307
|
}
|
|
307
308
|
export interface FormAdapterSubmissionMessageMeta {
|
|
308
309
|
schemaVersion: FormAdapterSubmissionSchemaVersion;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":["FileStatus","UploadStatus"],"sources":["../../../../src/server/plugins/engine/types.ts"],"sourcesContent":["import {\n type ComponentDef,\n type Event,\n type FormVersionMetadata,\n type Item,\n type List,\n type Page,\n type UkAddressFieldComponent\n} from '@defra/forms-model'\nimport {\n type PluginProperties,\n type Request,\n type ResponseObject\n} from '@hapi/hapi'\nimport { type JoiExpression, type ValidationErrorItem } from 'joi'\n\nimport { FormComponent } from '~/src/server/plugins/engine/components/FormComponent.js'\nimport { type UkAddressState } from '~/src/server/plugins/engine/components/UkAddressField.js'\nimport { type Component } from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { type FileUploadField } from '~/src/server/plugins/engine/components/index.js'\nimport {\n type BackLink,\n type ComponentText,\n type ComponentViewModel,\n type DatePartsState,\n type EastingNorthingState,\n type LatLongState,\n type MonthYearState\n} from '~/src/server/plugins/engine/components/types.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/index.js'\nimport { type DetailItemField } from '~/src/server/plugins/engine/models/types.js'\nimport { type PageController } from '~/src/server/plugins/engine/pageControllers/PageController.js'\nimport { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport { type QuestionPageController } from '~/src/server/plugins/engine/pageControllers/index.js'\nimport {\n type FileStatus,\n type FormAdapterSubmissionSchemaVersion,\n type UploadStatus\n} from '~/src/server/plugins/engine/types/enums.js'\nimport { type ViewContext } from '~/src/server/plugins/nunjucks/types.js'\nimport {\n type FormAction,\n type FormRequest,\n type FormRequestPayload,\n type FormResponseToolkit,\n type FormStatus\n} from '~/src/server/routes/types.js'\nimport { type CacheService } from '~/src/server/services/cacheService.js'\nimport { type RequestOptions } from '~/src/server/services/httpService.js'\nimport { type Services } from '~/src/server/types.js'\n\nexport type AnyFormRequest = FormRequest | FormRequestPayload\nexport type AnyRequest = Request | AnyFormRequest\n\n/**\n * Form submission state stores the following in Redis:\n * Props containing user's submitted values as `{ [inputId]: value }` or as `{ [sectionName]: { [inputName]: value } }`\n * a) . e.g:\n * ```ts\n * {\n * _C9PRHmsgt: 'Ben',\n * WfLk9McjzX: 'Music',\n * IK7jkUFCBL: 'Royal Academy of Music'\n * }\n * ```\n *\n * b)\n * ```ts\n * {\n * checkBeforeYouStart: { ukPassport: true },\n * applicantDetails: {\n * numberOfApplicants: 1,\n * phoneNumber: '77777777',\n * emailAddress: 'aaa@aaa.com'\n * },\n * applicantOneDetails: {\n * firstName: 'a',\n * middleName: 'a',\n * lastName: 'a',\n * address: { addressLine1: 'a', addressLine2: 'a', town: 'a', postcode: 'a' }\n * }\n * }\n * ```\n */\n\n/**\n * Form submission state\n */\nexport type FormSubmissionState = {\n upload?: Record<string, TempFileState>\n} & FormState\n\nexport interface FormSubmissionError\n extends Pick<ValidationErrorItem, 'context' | 'path'> {\n href: string // e.g: '#dateField__day'\n name: string // e.g: 'dateField__day'\n text: string // e.g: 'Date field must be a real date'\n}\n\nexport interface FormConfirmationState {\n confirmed?: true\n formId?: string\n referenceNumber?: string\n}\n\nexport interface FormPayloadParams {\n action?: FormAction\n confirm?: true\n crumb?: string\n itemId?: string\n}\n\n/**\n * Form POST for question pages\n * (after Joi has converted value types)\n */\nexport type FormPayload = FormPayloadParams & Partial<Record<string, FormValue>>\n\nexport type FormValue =\n | Item['value']\n | Item['value'][]\n | UploadState\n | RepeatListState\n | undefined\n\nexport type FormState = Partial<Record<string, FormStateValue>>\nexport type FormStateValue = Exclude<FormValue, undefined> | null\n\nexport interface FormValidationResult<\n ValueType extends FormPayload | FormSubmissionState\n> {\n value: ValueType\n errors: FormSubmissionError[] | undefined\n}\n\nexport interface FormContext {\n /**\n * Evaluation form state only (filtered by visited paths),\n * with values formatted for condition evaluation using\n * {@link FormComponent.getContextValueFromState}\n */\n evaluationState: FormState\n\n /**\n * Relevant form state only (filtered by visited paths)\n */\n relevantState: FormState\n\n /**\n * Relevant pages only (filtered by visited paths)\n */\n relevantPages: PageControllerClass[]\n\n /**\n * Form submission payload (single page)\n */\n payload: FormPayload\n\n /**\n * Form submission state (entire form)\n */\n state: FormSubmissionState\n\n /**\n * Validation errors (entire form)\n */\n errors?: FormSubmissionError[]\n\n /**\n * Visited paths evaluated from form state\n */\n paths: string[]\n\n /**\n * Preview URL direct access is allowed\n */\n isForceAccess: boolean\n\n /**\n * Miscellaneous extra data from event responses\n */\n data: object\n\n pageDefMap: Map<string, Page>\n listDefMap: Map<string, List>\n componentDefMap: Map<string, ComponentDef>\n pageMap: Map<string, PageControllerClass>\n componentMap: Map<string, Component>\n referenceNumber: string\n submittedVersionNumber?: number\n}\n\nexport type FormContextRequest = (\n | {\n method: 'get'\n payload?: undefined\n }\n | {\n method: 'post'\n payload: FormPayload\n }\n | {\n method: FormRequest['method']\n payload?: object | undefined\n }\n) &\n Pick<\n FormRequest,\n 'app' | 'method' | 'params' | 'path' | 'query' | 'url' | 'server'\n >\n\nexport interface UploadInitiateResponse {\n uploadId: string\n uploadUrl: string\n statusUrl: string\n}\n\nexport {\n FileStatus,\n UploadStatus\n} from '~/src/server/plugins/engine/types/enums.js'\n\nexport type UploadState = FileState[]\n\nexport type FileUpload = {\n fileId: string\n filename: string\n contentLength: number\n} & (\n | {\n fileStatus: FileStatus.complete | FileStatus.rejected | FileStatus.pending\n errorMessage?: string\n }\n | {\n fileStatus: FileStatus.complete\n errorMessage?: undefined\n }\n)\n\nexport interface FileUploadMetadata {\n retrievalKey: string\n}\n\nexport type UploadStatusResponse =\n | {\n uploadStatus: UploadStatus.initiated\n metadata: FileUploadMetadata\n form: { file?: undefined }\n }\n | {\n uploadStatus: UploadStatus.pending | UploadStatus.ready\n metadata: FileUploadMetadata\n form: { file: FileUpload }\n numberOfRejectedFiles?: number\n }\n | {\n uploadStatus: UploadStatus.ready\n metadata: FileUploadMetadata\n form: { file: FileUpload }\n numberOfRejectedFiles: 0\n }\n\nexport type UploadStatusFileResponse = Exclude<\n UploadStatusResponse,\n { uploadStatus: UploadStatus.initiated }\n>\n\nexport interface FileState {\n uploadId: string\n status: UploadStatusFileResponse\n}\n\nexport interface TempFileState {\n upload?: UploadInitiateResponse\n files: UploadState\n}\n\nexport interface RepeatItemState extends FormPayload {\n itemId: string\n}\n\nexport type RepeatListState = RepeatItemState[]\n\nexport interface CheckAnswers {\n title?: ComponentText\n summaryList: SummaryList\n}\n\nexport interface SummaryList {\n classes?: string\n rows: SummaryListRow[]\n}\n\nexport interface SummaryListRow {\n key: ComponentText\n value: ComponentText\n actions?: { items: SummaryListAction[] }\n}\n\nexport type SummaryListAction = ComponentText & {\n href: string\n visuallyHiddenText: string\n}\n\nexport interface PageViewModelBase extends Partial<ViewContext> {\n page: PageController\n name?: string\n pageTitle: string\n sectionTitle?: string\n showTitle: boolean\n isStartPage: boolean\n backLink?: BackLink\n feedbackLink?: string\n serviceUrl: string\n phaseTag?: string\n}\n\nexport interface ItemDeletePageViewModel extends PageViewModelBase {\n context: FormContext\n itemTitle: string\n confirmation?: ComponentText\n buttonConfirm: ComponentText\n buttonCancel: ComponentText\n}\n\nexport interface FormPageViewModel extends PageViewModelBase {\n components: ComponentViewModel[]\n context: FormContext\n errors?: FormSubmissionError[]\n hasMissingNotificationEmail?: boolean\n allowSaveAndExit: boolean\n}\n\nexport interface RepeaterSummaryPageViewModel extends PageViewModelBase {\n context: FormContext\n errors?: FormSubmissionError[]\n checkAnswers: CheckAnswers[]\n repeatTitle: string\n allowSaveAndExit: boolean\n}\n\nexport interface FeaturedFormPageViewModel extends FormPageViewModel {\n formAction?: string\n formComponent: ComponentViewModel\n componentsBefore: ComponentViewModel[]\n uploadId: string | undefined\n proxyUrl: string | null\n}\n\nexport type PageViewModel =\n | PageViewModelBase\n | ItemDeletePageViewModel\n | FormPageViewModel\n | RepeaterSummaryPageViewModel\n | FeaturedFormPageViewModel\n\nexport type GlobalFunction = (value: unknown) => unknown\nexport type FilterFunction = (value: unknown) => unknown\nexport interface ErrorMessageTemplate {\n type: string\n template: JoiExpression\n}\n\nexport interface ErrorMessageTemplateList {\n baseErrors: ErrorMessageTemplate[]\n advancedSettingsErrors: ErrorMessageTemplate[]\n}\n\nexport type PreparePageEventRequestOptions = (\n options: RequestOptions,\n event: Event,\n page: PageControllerClass,\n context: FormContext\n) => void\n\nexport type OnRequestCallback = (\n request: AnyFormRequest,\n h: FormResponseToolkit,\n context: FormContext\n) =>\n | ResponseObject\n | FormResponseToolkit['continue']\n | Promise<ResponseObject | FormResponseToolkit['continue']>\n\nexport type SaveAndExitHandler = (\n request: FormRequestPayload,\n h: FormResponseToolkit,\n context: FormContext\n) => ResponseObject\n\nexport interface ExternalArgs {\n component: ComponentDef\n controller: QuestionPageController\n sourceUrl: string\n actionArgs: Record<string, string>\n}\n\nexport interface PostcodeLookupExternalArgs extends ExternalArgs {\n component: UkAddressFieldComponent\n actionArgs: { step: string }\n}\n\nexport interface ExternalStateAppendage {\n component: string\n data: FormStateValue | FormState\n}\n\nexport interface PluginOptions {\n model?: FormModel\n services?: Services\n controllers?: Record<string, typeof PageController>\n cache?: CacheService | string\n globals?: Record<string, GlobalFunction>\n filters?: Record<string, FilterFunction>\n saveAndExit?: SaveAndExitHandler\n pluginPath?: string\n nunjucks: {\n baseLayoutPath: string\n paths: string[]\n }\n viewContext: PluginProperties['forms-engine-plugin']['viewContext']\n preparePageEventRequestOptions?: PreparePageEventRequestOptions\n onRequest?: OnRequestCallback\n baseUrl: string // base URL of the application, protocol and hostname e.g. \"https://myapp.com\"\n ordnanceSurveyApiKey?: string\n}\n\nexport interface FormAdapterSubmissionMessageMeta {\n schemaVersion: FormAdapterSubmissionSchemaVersion\n timestamp: Date\n referenceNumber: string\n formName: string\n formId: string\n formSlug: string\n status: FormStatus\n isPreview: boolean\n notificationEmail: string\n versionMetadata?: FormVersionMetadata\n custom?: Record<string, unknown>\n}\n\nexport type FormAdapterSubmissionMessageMetaSerialised = Omit<\n FormAdapterSubmissionMessageMeta,\n 'schemaVersion' | 'timestamp' | 'status'\n> & {\n schemaVersion: number\n status: string\n timestamp: string\n}\nexport interface FormAdapterFile {\n fileName: string\n fileId: string\n userDownloadLink: string\n}\n\nexport interface FormAdapterSubmissionMessageResult {\n files: {\n main: string\n repeaters: Record<string, string>\n }\n}\n\n/**\n * A detail item specifically for files\n */\nexport type FileUploadFieldDetailitem = Omit<DetailItemField, 'field'> & {\n field: FileUploadField\n}\nexport type RichFormValue =\n | FormValue\n | FormPayload\n | DatePartsState\n | MonthYearState\n | UkAddressState\n | EastingNorthingState\n | LatLongState\n\nexport interface FormAdapterSubmissionMessageData {\n main: Record<string, RichFormValue | null>\n repeaters: Record<string, Record<string, RichFormValue>[]>\n files: Record<string, FormAdapterFile[]>\n}\n\nexport interface FormAdapterSubmissionMessagePayload {\n meta: FormAdapterSubmissionMessageMeta\n data: FormAdapterSubmissionMessageData\n result: FormAdapterSubmissionMessageResult\n}\n\nexport interface FormAdapterSubmissionMessage\n extends FormAdapterSubmissionMessagePayload {\n messageId: string\n recordCreatedAt: Date\n}\n\nexport interface FormAdapterSubmissionService {\n handleFormSubmission: (\n submissionMessage: FormAdapterSubmissionMessage\n ) => unknown\n}\n"],"mappings":"AAsDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAyBA;AACA;AACA;AACA;;AAsGA,SACEA,UAAU,EACVC,YAAY;;AAmPd;AACA;AACA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"types.js","names":["FileStatus","UploadStatus"],"sources":["../../../../src/server/plugins/engine/types.ts"],"sourcesContent":["import {\n type ComponentDef,\n type Event,\n type FormVersionMetadata,\n type Item,\n type List,\n type Page,\n type UkAddressFieldComponent\n} from '@defra/forms-model'\nimport {\n type PluginProperties,\n type Request,\n type ResponseObject\n} from '@hapi/hapi'\nimport { type JoiExpression, type ValidationErrorItem } from 'joi'\n\nimport { FormComponent } from '~/src/server/plugins/engine/components/FormComponent.js'\nimport { type UkAddressState } from '~/src/server/plugins/engine/components/UkAddressField.js'\nimport { type Component } from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { type FileUploadField } from '~/src/server/plugins/engine/components/index.js'\nimport {\n type BackLink,\n type ComponentText,\n type ComponentViewModel,\n type DatePartsState,\n type EastingNorthingState,\n type LatLongState,\n type MonthYearState\n} from '~/src/server/plugins/engine/components/types.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/index.js'\nimport { type DetailItemField } from '~/src/server/plugins/engine/models/types.js'\nimport { type PageController } from '~/src/server/plugins/engine/pageControllers/PageController.js'\nimport { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport { type QuestionPageController } from '~/src/server/plugins/engine/pageControllers/index.js'\nimport {\n type FileStatus,\n type FormAdapterSubmissionSchemaVersion,\n type UploadStatus\n} from '~/src/server/plugins/engine/types/enums.js'\nimport { type ViewContext } from '~/src/server/plugins/nunjucks/types.js'\nimport {\n type FormAction,\n type FormRequest,\n type FormRequestPayload,\n type FormResponseToolkit,\n type FormStatus\n} from '~/src/server/routes/types.js'\nimport { type CacheService } from '~/src/server/services/cacheService.js'\nimport { type RequestOptions } from '~/src/server/services/httpService.js'\nimport { type Services } from '~/src/server/types.js'\n\nexport type AnyFormRequest = FormRequest | FormRequestPayload\nexport type AnyRequest = Request | AnyFormRequest\n\n/**\n * Form submission state stores the following in Redis:\n * Props containing user's submitted values as `{ [inputId]: value }` or as `{ [sectionName]: { [inputName]: value } }`\n * a) . e.g:\n * ```ts\n * {\n * _C9PRHmsgt: 'Ben',\n * WfLk9McjzX: 'Music',\n * IK7jkUFCBL: 'Royal Academy of Music'\n * }\n * ```\n *\n * b)\n * ```ts\n * {\n * checkBeforeYouStart: { ukPassport: true },\n * applicantDetails: {\n * numberOfApplicants: 1,\n * phoneNumber: '77777777',\n * emailAddress: 'aaa@aaa.com'\n * },\n * applicantOneDetails: {\n * firstName: 'a',\n * middleName: 'a',\n * lastName: 'a',\n * address: { addressLine1: 'a', addressLine2: 'a', town: 'a', postcode: 'a' }\n * }\n * }\n * ```\n */\n\n/**\n * Form submission state\n */\nexport type FormSubmissionState = {\n upload?: Record<string, TempFileState>\n} & FormState\n\nexport interface FormSubmissionError\n extends Pick<ValidationErrorItem, 'context' | 'path'> {\n href: string // e.g: '#dateField__day'\n name: string // e.g: 'dateField__day'\n text: string // e.g: 'Date field must be a real date'\n}\n\nexport interface FormConfirmationState {\n confirmed?: true\n formId?: string\n referenceNumber?: string\n}\n\nexport interface FormPayloadParams {\n action?: FormAction\n confirm?: true\n crumb?: string\n itemId?: string\n}\n\n/**\n * Form POST for question pages\n * (after Joi has converted value types)\n */\nexport type FormPayload = FormPayloadParams & Partial<Record<string, FormValue>>\n\nexport type FormValue =\n | Item['value']\n | Item['value'][]\n | UploadState\n | RepeatListState\n | undefined\n\nexport type FormState = Partial<Record<string, FormStateValue>>\nexport type FormStateValue = Exclude<FormValue, undefined> | null\n\nexport interface FormValidationResult<\n ValueType extends FormPayload | FormSubmissionState\n> {\n value: ValueType\n errors: FormSubmissionError[] | undefined\n}\n\nexport interface FormContext {\n /**\n * Evaluation form state only (filtered by visited paths),\n * with values formatted for condition evaluation using\n * {@link FormComponent.getContextValueFromState}\n */\n evaluationState: FormState\n\n /**\n * Relevant form state only (filtered by visited paths)\n */\n relevantState: FormState\n\n /**\n * Relevant pages only (filtered by visited paths)\n */\n relevantPages: PageControllerClass[]\n\n /**\n * Form submission payload (single page)\n */\n payload: FormPayload\n\n /**\n * Form submission state (entire form)\n */\n state: FormSubmissionState\n\n /**\n * Validation errors (entire form)\n */\n errors?: FormSubmissionError[]\n\n /**\n * Visited paths evaluated from form state\n */\n paths: string[]\n\n /**\n * Preview URL direct access is allowed\n */\n isForceAccess: boolean\n\n /**\n * Miscellaneous extra data from event responses\n */\n data: object\n\n pageDefMap: Map<string, Page>\n listDefMap: Map<string, List>\n componentDefMap: Map<string, ComponentDef>\n pageMap: Map<string, PageControllerClass>\n componentMap: Map<string, Component>\n referenceNumber: string\n submittedVersionNumber?: number\n}\n\nexport type FormContextRequest = (\n | {\n method: 'get'\n payload?: undefined\n }\n | {\n method: 'post'\n payload: FormPayload\n }\n | {\n method: FormRequest['method']\n payload?: object | undefined\n }\n) &\n Pick<\n FormRequest,\n 'app' | 'method' | 'params' | 'path' | 'query' | 'url' | 'server'\n >\n\nexport interface UploadInitiateResponse {\n uploadId: string\n uploadUrl: string\n statusUrl: string\n}\n\nexport {\n FileStatus,\n UploadStatus\n} from '~/src/server/plugins/engine/types/enums.js'\n\nexport type UploadState = FileState[]\n\nexport type FileUpload = {\n fileId: string\n filename: string\n contentLength: number\n} & (\n | {\n fileStatus: FileStatus.complete | FileStatus.rejected | FileStatus.pending\n errorMessage?: string\n }\n | {\n fileStatus: FileStatus.complete\n errorMessage?: undefined\n }\n)\n\nexport interface FileUploadMetadata {\n retrievalKey: string\n}\n\nexport type UploadStatusResponse =\n | {\n uploadStatus: UploadStatus.initiated\n metadata: FileUploadMetadata\n form: { file?: undefined }\n }\n | {\n uploadStatus: UploadStatus.pending | UploadStatus.ready\n metadata: FileUploadMetadata\n form: { file: FileUpload }\n numberOfRejectedFiles?: number\n }\n | {\n uploadStatus: UploadStatus.ready\n metadata: FileUploadMetadata\n form: { file: FileUpload }\n numberOfRejectedFiles: 0\n }\n\nexport type UploadStatusFileResponse = Exclude<\n UploadStatusResponse,\n { uploadStatus: UploadStatus.initiated }\n>\n\nexport interface FileState {\n uploadId: string\n status: UploadStatusFileResponse\n}\n\nexport interface TempFileState {\n upload?: UploadInitiateResponse\n files: UploadState\n}\n\nexport interface RepeatItemState extends FormPayload {\n itemId: string\n}\n\nexport type RepeatListState = RepeatItemState[]\n\nexport interface CheckAnswers {\n title?: ComponentText\n summaryList: SummaryList\n}\n\nexport interface SummaryList {\n classes?: string\n rows: SummaryListRow[]\n}\n\nexport interface SummaryListRow {\n key: ComponentText\n value: ComponentText\n actions?: { items: SummaryListAction[] }\n}\n\nexport type SummaryListAction = ComponentText & {\n href: string\n visuallyHiddenText: string\n}\n\nexport interface PageViewModelBase extends Partial<ViewContext> {\n page: PageController\n name?: string\n pageTitle: string\n sectionTitle?: string\n showTitle: boolean\n isStartPage: boolean\n backLink?: BackLink\n feedbackLink?: string\n serviceUrl: string\n phaseTag?: string\n}\n\nexport interface ItemDeletePageViewModel extends PageViewModelBase {\n context: FormContext\n itemTitle: string\n confirmation?: ComponentText\n buttonConfirm: ComponentText\n buttonCancel: ComponentText\n}\n\nexport interface FormPageViewModel extends PageViewModelBase {\n components: ComponentViewModel[]\n context: FormContext\n errors?: FormSubmissionError[]\n hasMissingNotificationEmail?: boolean\n allowSaveAndExit: boolean\n}\n\nexport interface RepeaterSummaryPageViewModel extends PageViewModelBase {\n context: FormContext\n errors?: FormSubmissionError[]\n checkAnswers: CheckAnswers[]\n repeatTitle: string\n allowSaveAndExit: boolean\n}\n\nexport interface FeaturedFormPageViewModel extends FormPageViewModel {\n formAction?: string\n formComponent: ComponentViewModel\n componentsBefore: ComponentViewModel[]\n uploadId: string | undefined\n proxyUrl: string | null\n}\n\nexport type PageViewModel =\n | PageViewModelBase\n | ItemDeletePageViewModel\n | FormPageViewModel\n | RepeaterSummaryPageViewModel\n | FeaturedFormPageViewModel\n\nexport type GlobalFunction = (value: unknown) => unknown\nexport type FilterFunction = (value: unknown) => unknown\nexport interface ErrorMessageTemplate {\n type: string\n template: JoiExpression\n}\n\nexport interface ErrorMessageTemplateList {\n baseErrors: ErrorMessageTemplate[]\n advancedSettingsErrors: ErrorMessageTemplate[]\n}\n\nexport type PreparePageEventRequestOptions = (\n options: RequestOptions,\n event: Event,\n page: PageControllerClass,\n context: FormContext\n) => void\n\nexport type OnRequestCallback = (\n request: AnyFormRequest,\n h: FormResponseToolkit,\n context: FormContext\n) =>\n | ResponseObject\n | FormResponseToolkit['continue']\n | Promise<ResponseObject | FormResponseToolkit['continue']>\n\nexport type SaveAndExitHandler = (\n request: FormRequestPayload,\n h: FormResponseToolkit,\n context: FormContext\n) => ResponseObject\n\nexport interface ExternalArgs {\n component: ComponentDef\n controller: QuestionPageController\n sourceUrl: string\n actionArgs: Record<string, string>\n}\n\nexport interface PostcodeLookupExternalArgs extends ExternalArgs {\n component: UkAddressFieldComponent\n actionArgs: { step: string }\n}\n\nexport interface ExternalStateAppendage {\n component: string\n data: FormStateValue | FormState\n}\n\nexport interface PluginOptions {\n model?: FormModel\n services?: Services\n controllers?: Record<string, typeof PageController>\n cache?: CacheService | string\n globals?: Record<string, GlobalFunction>\n filters?: Record<string, FilterFunction>\n saveAndExit?: SaveAndExitHandler\n pluginPath?: string\n nunjucks: {\n baseLayoutPath: string\n paths: string[]\n }\n viewContext: PluginProperties['forms-engine-plugin']['viewContext']\n preparePageEventRequestOptions?: PreparePageEventRequestOptions\n onRequest?: OnRequestCallback\n baseUrl: string // base URL of the application, protocol and hostname e.g. \"https://myapp.com\"\n ordnanceSurveyApiKey?: string\n ordnanceSurveyApiSecret?: string\n}\n\nexport interface FormAdapterSubmissionMessageMeta {\n schemaVersion: FormAdapterSubmissionSchemaVersion\n timestamp: Date\n referenceNumber: string\n formName: string\n formId: string\n formSlug: string\n status: FormStatus\n isPreview: boolean\n notificationEmail: string\n versionMetadata?: FormVersionMetadata\n custom?: Record<string, unknown>\n}\n\nexport type FormAdapterSubmissionMessageMetaSerialised = Omit<\n FormAdapterSubmissionMessageMeta,\n 'schemaVersion' | 'timestamp' | 'status'\n> & {\n schemaVersion: number\n status: string\n timestamp: string\n}\nexport interface FormAdapterFile {\n fileName: string\n fileId: string\n userDownloadLink: string\n}\n\nexport interface FormAdapterSubmissionMessageResult {\n files: {\n main: string\n repeaters: Record<string, string>\n }\n}\n\n/**\n * A detail item specifically for files\n */\nexport type FileUploadFieldDetailitem = Omit<DetailItemField, 'field'> & {\n field: FileUploadField\n}\nexport type RichFormValue =\n | FormValue\n | FormPayload\n | DatePartsState\n | MonthYearState\n | UkAddressState\n | EastingNorthingState\n | LatLongState\n\nexport interface FormAdapterSubmissionMessageData {\n main: Record<string, RichFormValue | null>\n repeaters: Record<string, Record<string, RichFormValue>[]>\n files: Record<string, FormAdapterFile[]>\n}\n\nexport interface FormAdapterSubmissionMessagePayload {\n meta: FormAdapterSubmissionMessageMeta\n data: FormAdapterSubmissionMessageData\n result: FormAdapterSubmissionMessageResult\n}\n\nexport interface FormAdapterSubmissionMessage\n extends FormAdapterSubmissionMessagePayload {\n messageId: string\n recordCreatedAt: Date\n}\n\nexport interface FormAdapterSubmissionService {\n handleFormSubmission: (\n submissionMessage: FormAdapterSubmissionMessage\n ) => unknown\n}\n"],"mappings":"AAsDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAyBA;AACA;AACA;AACA;;AAsGA,SACEA,UAAU,EACVC,YAAY;;AAoPd;AACA;AACA","ignoreList":[]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { post } from "../../../services/httpService.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @type {string}
|
|
5
|
+
*/
|
|
6
|
+
let cachedToken;
|
|
7
|
+
let tokenExpiry = 0;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Get Ordnance Survey OAuth token
|
|
11
|
+
* @param {MapConfiguration} options - Ordnance survey map options
|
|
12
|
+
*/
|
|
13
|
+
export async function getAccessToken(options) {
|
|
14
|
+
const {
|
|
15
|
+
ordnanceSurveyApiKey: key,
|
|
16
|
+
ordnanceSurveyApiSecret: secret
|
|
17
|
+
} = options;
|
|
18
|
+
const now = Date.now();
|
|
19
|
+
if (cachedToken && now < tokenExpiry) {
|
|
20
|
+
return cachedToken;
|
|
21
|
+
}
|
|
22
|
+
const creds = `${key}:${secret}`;
|
|
23
|
+
const result = await post('https://api.os.uk/oauth2/token/v1', {
|
|
24
|
+
headers: {
|
|
25
|
+
Authorization: `Basic ${btoa(creds)}`,
|
|
26
|
+
'Content-Type': 'application/x-www-form-urlencoded'
|
|
27
|
+
},
|
|
28
|
+
payload: 'grant_type=client_credentials',
|
|
29
|
+
json: true
|
|
30
|
+
});
|
|
31
|
+
const data = result.payload;
|
|
32
|
+
cachedToken = data.access_token;
|
|
33
|
+
tokenExpiry = now + (data.expires_in - 60) * 1000; // refresh early
|
|
34
|
+
|
|
35
|
+
return cachedToken;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @import { MapConfiguration } from '~/src/server/plugins/map/types.js'
|
|
40
|
+
*/
|
|
41
|
+
//# sourceMappingURL=get-os-token.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-os-token.js","names":["post","cachedToken","tokenExpiry","getAccessToken","options","ordnanceSurveyApiKey","key","ordnanceSurveyApiSecret","secret","now","Date","creds","result","headers","Authorization","btoa","payload","json","data","access_token","expires_in"],"sources":["../../../../../src/server/plugins/map/routes/get-os-token.js"],"sourcesContent":["import { post } from '~/src/server/services/httpService.js'\n\n/**\n * @type {string}\n */\nlet cachedToken\nlet tokenExpiry = 0\n\n/**\n * Get Ordnance Survey OAuth token\n * @param {MapConfiguration} options - Ordnance survey map options\n */\nexport async function getAccessToken(options) {\n const { ordnanceSurveyApiKey: key, ordnanceSurveyApiSecret: secret } = options\n const now = Date.now()\n\n if (cachedToken && now < tokenExpiry) {\n return cachedToken\n }\n\n const creds = `${key}:${secret}`\n const result = await post('https://api.os.uk/oauth2/token/v1', {\n headers: {\n Authorization: `Basic ${btoa(creds)}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n payload: 'grant_type=client_credentials',\n json: true\n })\n\n const data = result.payload\n\n cachedToken = data.access_token\n tokenExpiry = now + (data.expires_in - 60) * 1000 // refresh early\n\n return cachedToken\n}\n\n/**\n * @import { MapConfiguration } from '~/src/server/plugins/map/types.js'\n */\n"],"mappings":"AAAA,SAASA,IAAI;;AAEb;AACA;AACA;AACA,IAAIC,WAAW;AACf,IAAIC,WAAW,GAAG,CAAC;;AAEnB;AACA;AACA;AACA;AACA,OAAO,eAAeC,cAAcA,CAACC,OAAO,EAAE;EAC5C,MAAM;IAAEC,oBAAoB,EAAEC,GAAG;IAAEC,uBAAuB,EAAEC;EAAO,CAAC,GAAGJ,OAAO;EAC9E,MAAMK,GAAG,GAAGC,IAAI,CAACD,GAAG,CAAC,CAAC;EAEtB,IAAIR,WAAW,IAAIQ,GAAG,GAAGP,WAAW,EAAE;IACpC,OAAOD,WAAW;EACpB;EAEA,MAAMU,KAAK,GAAG,GAAGL,GAAG,IAAIE,MAAM,EAAE;EAChC,MAAMI,MAAM,GAAG,MAAMZ,IAAI,CAAC,mCAAmC,EAAE;IAC7Da,OAAO,EAAE;MACPC,aAAa,EAAE,SAASC,IAAI,CAACJ,KAAK,CAAC,EAAE;MACrC,cAAc,EAAE;IAClB,CAAC;IACDK,OAAO,EAAE,+BAA+B;IACxCC,IAAI,EAAE;EACR,CAAC,CAAC;EAEF,MAAMC,IAAI,GAAGN,MAAM,CAACI,OAAO;EAE3Bf,WAAW,GAAGiB,IAAI,CAACC,YAAY;EAC/BjB,WAAW,GAAGO,GAAG,GAAG,CAACS,IAAI,CAACE,UAAU,GAAG,EAAE,IAAI,IAAI,EAAC;;EAElD,OAAOnB,WAAW;AACpB;;AAEA;AACA;AACA","ignoreList":[]}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { getAccessToken } from "./get-os-token.js";
|
|
2
|
+
import { post } from "../../../services/httpService.js";
|
|
3
|
+
jest.mock("../../../services/httpService.ts");
|
|
4
|
+
describe('OS OAuth token', () => {
|
|
5
|
+
describe('getAccessToken', () => {
|
|
6
|
+
it('should get access token', async () => {
|
|
7
|
+
jest.mocked(post).mockResolvedValueOnce({
|
|
8
|
+
res: (/** @type {IncomingMessage} */{
|
|
9
|
+
statusCode: 200,
|
|
10
|
+
headers: {}
|
|
11
|
+
}),
|
|
12
|
+
payload: {
|
|
13
|
+
access_token: 'access_token',
|
|
14
|
+
expires_in: '299',
|
|
15
|
+
issued_at: '1770036762387',
|
|
16
|
+
token_type: 'Bearer'
|
|
17
|
+
},
|
|
18
|
+
error: undefined
|
|
19
|
+
});
|
|
20
|
+
const token = await getAccessToken({
|
|
21
|
+
ordnanceSurveyApiKey: 'apikey',
|
|
22
|
+
ordnanceSurveyApiSecret: 'apisecret'
|
|
23
|
+
});
|
|
24
|
+
expect(token).toBe('access_token');
|
|
25
|
+
expect(post).toHaveBeenCalledWith('https://api.os.uk/oauth2/token/v1', {
|
|
26
|
+
headers: {
|
|
27
|
+
Authorization: `Basic ${btoa('apikey:apisecret')}`,
|
|
28
|
+
'Content-Type': 'application/x-www-form-urlencoded'
|
|
29
|
+
},
|
|
30
|
+
payload: 'grant_type=client_credentials',
|
|
31
|
+
json: true
|
|
32
|
+
});
|
|
33
|
+
expect(post).toHaveBeenCalledTimes(1);
|
|
34
|
+
});
|
|
35
|
+
it('should return an cached token', async () => {
|
|
36
|
+
const token = await getAccessToken({
|
|
37
|
+
ordnanceSurveyApiKey: 'apikey',
|
|
38
|
+
ordnanceSurveyApiSecret: 'apisecret'
|
|
39
|
+
});
|
|
40
|
+
expect(token).toBe('access_token');
|
|
41
|
+
expect(post).toHaveBeenCalledTimes(0);
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @import { IncomingMessage } from 'node:http'
|
|
48
|
+
*/
|
|
49
|
+
//# sourceMappingURL=get-os-token.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-os-token.test.js","names":["getAccessToken","post","jest","mock","describe","it","mocked","mockResolvedValueOnce","res","statusCode","headers","payload","access_token","expires_in","issued_at","token_type","error","undefined","token","ordnanceSurveyApiKey","ordnanceSurveyApiSecret","expect","toBe","toHaveBeenCalledWith","Authorization","btoa","json","toHaveBeenCalledTimes"],"sources":["../../../../../src/server/plugins/map/routes/get-os-token.test.js"],"sourcesContent":["import { getAccessToken } from '~/src/server/plugins/map/routes/get-os-token.js'\nimport { post } from '~/src/server/services/httpService.js'\n\njest.mock('~/src/server/services/httpService.ts')\n\ndescribe('OS OAuth token', () => {\n describe('getAccessToken', () => {\n it('should get access token', async () => {\n jest.mocked(post).mockResolvedValueOnce({\n res: /** @type {IncomingMessage} */ ({\n statusCode: 200,\n headers: {}\n }),\n payload: {\n access_token: 'access_token',\n expires_in: '299',\n issued_at: '1770036762387',\n token_type: 'Bearer'\n },\n error: undefined\n })\n\n const token = await getAccessToken({\n ordnanceSurveyApiKey: 'apikey',\n ordnanceSurveyApiSecret: 'apisecret'\n })\n\n expect(token).toBe('access_token')\n\n expect(post).toHaveBeenCalledWith('https://api.os.uk/oauth2/token/v1', {\n headers: {\n Authorization: `Basic ${btoa('apikey:apisecret')}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n payload: 'grant_type=client_credentials',\n json: true\n })\n expect(post).toHaveBeenCalledTimes(1)\n })\n\n it('should return an cached token', async () => {\n const token = await getAccessToken({\n ordnanceSurveyApiKey: 'apikey',\n ordnanceSurveyApiSecret: 'apisecret'\n })\n\n expect(token).toBe('access_token')\n expect(post).toHaveBeenCalledTimes(0)\n })\n })\n})\n\n/**\n * @import { IncomingMessage } from 'node:http'\n */\n"],"mappings":"AAAA,SAASA,cAAc;AACvB,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