// ==UserScript== // @name WME Switzerland Helper (Beta) // @namespace wme-sdk-scripts // @version 1.5.2.5 // @description WME Switzerland Helper is a userscript that provides various tools and enhancements for Waze Map Editor (WME) users in Switzerland. // @updateURL https://raw.githubusercontent.com/Waze-Dev-CH/WME-Switzerland-Helper/beta-releases/releases/main.user.js // @downloadURL https://raw.githubusercontent.com/Waze-Dev-CH/WME-Switzerland-Helper/beta-releases/releases/main.user.js // @author Maël Pedretti (Marelitaw), Yann Rapenne (Neprena) // @match https://www.waze.com/editor* // @match https://beta.waze.com/editor* // @match https://www.waze.com/*/editor* // @match https://beta.waze.com/*/editor* // @exclude https://www.waze.com/user/editor* // @exclude https://beta.waze.com/user/editor* // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect api3.geo.admin.ch // @connect data.sbb.ch // @connect beta.waze.com // @connect www.waze.com // ==/UserScript== (function () { 'use strict'; const STORAGE_KEY$2 = "wme-switzerland-helper-layer-state"; function getLayerStates() { try { const stored = localStorage.getItem(STORAGE_KEY$2); return stored ? JSON.parse(stored) : {}; } catch { return {}; } } function saveLayerState(layerName, checked) { try { const states = getLayerStates(); states[layerName] = checked; localStorage.setItem(STORAGE_KEY$2, JSON.stringify(states)); } catch { console.warn("Failed to save layer state to localStorage"); } } function isLayerEnabled(layerName) { const states = getLayerStates(); return layerName in states ? states[layerName] : null; } class Layer { constructor(args) { this.name = args.name; this.eventCleanups = []; args.wmeSDK.LayerSwitcher.addLayerCheckbox({ name: this.name }); this.registerCheckboxHandler({ wmeSDK: args.wmeSDK }); } removeFromMap(args) { args.wmeSDK.Map.removeLayer({ layerName: this.name }); this.unregisterEvents(); } unregisterEvents() { for (const cleanup of this.eventCleanups) { try { cleanup(); } catch { console.warn("Failed to cleanup layer event listener"); } } this.eventCleanups = []; } registerCheckboxHandler(args) { const { wmeSDK } = args; const cleanup = wmeSDK.Events.on({ eventName: "wme-layer-checkbox-toggled", eventHandler: ({ name, checked }) => { if (name !== this.name) return; saveLayerState(this.name, checked); if (checked) { this.addToMap({ wmeSDK }); this.registerEvents({ wmeSDK }); } else { this.removeFromMap({ wmeSDK }); } }, }); this.eventCleanups.push(cleanup); } restoreState(args) { const { wmeSDK } = args; const enabled = isLayerEnabled(this.name); if (enabled === true) { this.addToMap({ wmeSDK }); wmeSDK.LayerSwitcher.setLayerCheckboxChecked({ name: this.name, isChecked: true, }); } } } class TileLayer extends Layer { constructor(args) { super({ name: args.name, wmeSDK: args.wmeSDK }); this.tileHeight = args.tileHeight; this.tileWidth = args.tileWidth; this.fileName = args.fileName; this.servers = args.servers; this.zIndex = args.zIndex ?? 2035; } addToMap(args) { const wmeSDK = args.wmeSDK; wmeSDK.Map.addTileLayer({ layerName: this.name, layerOptions: { tileHeight: this.tileHeight, tileWidth: this.tileWidth, url: { fileName: this.fileName, servers: this.servers, }, }, }); wmeSDK.Map.setLayerZIndex({ layerName: this.name, zIndex: this.zIndex, }); } registerEvents(args) { } } // index.ts var earthRadius = 63710088e-1; var factors = { centimeters: earthRadius * 100, centimetres: earthRadius * 100, degrees: 360 / (2 * Math.PI), feet: earthRadius * 3.28084, inches: earthRadius * 39.37, kilometers: earthRadius / 1e3, kilometres: earthRadius / 1e3, meters: earthRadius, metres: earthRadius, miles: earthRadius / 1609.344, millimeters: earthRadius * 1e3, millimetres: earthRadius * 1e3, nauticalmiles: earthRadius / 1852, radians: 1, yards: earthRadius * 1.0936 }; function feature(geom, properties, options = {}) { const feat = { type: "Feature" }; if (options.id === 0 || options.id) { feat.id = options.id; } if (options.bbox) { feat.bbox = options.bbox; } feat.properties = {}; feat.geometry = geom; return feat; } function point(coordinates, properties, options = {}) { if (!coordinates) { throw new Error("coordinates is required"); } if (!Array.isArray(coordinates)) { throw new Error("coordinates must be an Array"); } if (coordinates.length < 2) { throw new Error("coordinates must be at least 2 numbers long"); } if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) { throw new Error("coordinates must contain numbers"); } const geom = { type: "Point", coordinates }; return feature(geom, properties, options); } function radiansToLength(radians, units = "kilometers") { const factor = factors[units]; if (!factor) { throw new Error(units + " units is invalid"); } return radians * factor; } function degreesToRadians(degrees) { const normalisedDegrees = degrees % 360; return normalisedDegrees * Math.PI / 180; } function isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } // index.ts function getCoord(coord) { if (!coord) { throw new Error("coord is required"); } if (!Array.isArray(coord)) { if (coord.type === "Feature" && coord.geometry !== null && coord.geometry.type === "Point") { return [...coord.geometry.coordinates]; } if (coord.type === "Point") { return [...coord.coordinates]; } } if (Array.isArray(coord) && coord.length >= 2 && !Array.isArray(coord[0]) && !Array.isArray(coord[1])) { return [...coord]; } throw new Error("coord must be GeoJSON Point or an Array of numbers"); } function getGeom(geojson) { if (geojson.type === "Feature") { return geojson.geometry; } return geojson; } // index.ts function distance(from, to, options = {}) { var coordinates1 = getCoord(from); var coordinates2 = getCoord(to); var dLat = degreesToRadians(coordinates2[1] - coordinates1[1]); var dLon = degreesToRadians(coordinates2[0] - coordinates1[0]); var lat1 = degreesToRadians(coordinates1[1]); var lat2 = degreesToRadians(coordinates2[1]); var a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); return radiansToLength( 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)), options.units ); } const epsilon = 1.1102230246251565e-16; const splitter = 134217729; const resulterrbound = (3 + 8 * epsilon) * epsilon; // fast_expansion_sum_zeroelim routine from oritinal code function sum(elen, e, flen, f, h) { let Q, Qnew, hh, bvirt; let enow = e[0]; let fnow = f[0]; let eindex = 0; let findex = 0; if ((fnow > enow) === (fnow > -enow)) { Q = enow; enow = e[++eindex]; } else { Q = fnow; fnow = f[++findex]; } let hindex = 0; if (eindex < elen && findex < flen) { if ((fnow > enow) === (fnow > -enow)) { Qnew = enow + Q; hh = Q - (Qnew - enow); enow = e[++eindex]; } else { Qnew = fnow + Q; hh = Q - (Qnew - fnow); fnow = f[++findex]; } Q = Qnew; if (hh !== 0) { h[hindex++] = hh; } while (eindex < elen && findex < flen) { if ((fnow > enow) === (fnow > -enow)) { Qnew = Q + enow; bvirt = Qnew - Q; hh = Q - (Qnew - bvirt) + (enow - bvirt); enow = e[++eindex]; } else { Qnew = Q + fnow; bvirt = Qnew - Q; hh = Q - (Qnew - bvirt) + (fnow - bvirt); fnow = f[++findex]; } Q = Qnew; if (hh !== 0) { h[hindex++] = hh; } } } while (eindex < elen) { Qnew = Q + enow; bvirt = Qnew - Q; hh = Q - (Qnew - bvirt) + (enow - bvirt); enow = e[++eindex]; Q = Qnew; if (hh !== 0) { h[hindex++] = hh; } } while (findex < flen) { Qnew = Q + fnow; bvirt = Qnew - Q; hh = Q - (Qnew - bvirt) + (fnow - bvirt); fnow = f[++findex]; Q = Qnew; if (hh !== 0) { h[hindex++] = hh; } } if (Q !== 0 || hindex === 0) { h[hindex++] = Q; } return hindex; } function estimate(elen, e) { let Q = e[0]; for (let i = 1; i < elen; i++) Q += e[i]; return Q; } function vec(n) { return new Float64Array(n); } const ccwerrboundA = (3 + 16 * epsilon) * epsilon; const ccwerrboundB = (2 + 12 * epsilon) * epsilon; const ccwerrboundC = (9 + 64 * epsilon) * epsilon * epsilon; const B = vec(4); const C1 = vec(8); const C2 = vec(12); const D = vec(16); const u = vec(4); function orient2dadapt(ax, ay, bx, by, cx, cy, detsum) { let acxtail, acytail, bcxtail, bcytail; let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; const acx = ax - cx; const bcx = bx - cx; const acy = ay - cy; const bcy = by - cy; s1 = acx * bcy; c = splitter * acx; ahi = c - (c - acx); alo = acx - ahi; c = splitter * bcy; bhi = c - (c - bcy); blo = bcy - bhi; s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); t1 = acy * bcx; c = splitter * acy; ahi = c - (c - acy); alo = acy - ahi; c = splitter * bcx; bhi = c - (c - bcx); blo = bcx - bhi; t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); _i = s0 - t0; bvirt = s0 - _i; B[0] = s0 - (_i + bvirt) + (bvirt - t0); _j = s1 + _i; bvirt = _j - s1; _0 = s1 - (_j - bvirt) + (_i - bvirt); _i = _0 - t1; bvirt = _0 - _i; B[1] = _0 - (_i + bvirt) + (bvirt - t1); u3 = _j + _i; bvirt = u3 - _j; B[2] = _j - (u3 - bvirt) + (_i - bvirt); B[3] = u3; let det = estimate(4, B); let errbound = ccwerrboundB * detsum; if (det >= errbound || -det >= errbound) { return det; } bvirt = ax - acx; acxtail = ax - (acx + bvirt) + (bvirt - cx); bvirt = bx - bcx; bcxtail = bx - (bcx + bvirt) + (bvirt - cx); bvirt = ay - acy; acytail = ay - (acy + bvirt) + (bvirt - cy); bvirt = by - bcy; bcytail = by - (bcy + bvirt) + (bvirt - cy); if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) { return det; } errbound = ccwerrboundC * detsum + resulterrbound * Math.abs(det); det += (acx * bcytail + bcy * acxtail) - (acy * bcxtail + bcx * acytail); if (det >= errbound || -det >= errbound) return det; s1 = acxtail * bcy; c = splitter * acxtail; ahi = c - (c - acxtail); alo = acxtail - ahi; c = splitter * bcy; bhi = c - (c - bcy); blo = bcy - bhi; s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); t1 = acytail * bcx; c = splitter * acytail; ahi = c - (c - acytail); alo = acytail - ahi; c = splitter * bcx; bhi = c - (c - bcx); blo = bcx - bhi; t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); _i = s0 - t0; bvirt = s0 - _i; u[0] = s0 - (_i + bvirt) + (bvirt - t0); _j = s1 + _i; bvirt = _j - s1; _0 = s1 - (_j - bvirt) + (_i - bvirt); _i = _0 - t1; bvirt = _0 - _i; u[1] = _0 - (_i + bvirt) + (bvirt - t1); u3 = _j + _i; bvirt = u3 - _j; u[2] = _j - (u3 - bvirt) + (_i - bvirt); u[3] = u3; const C1len = sum(4, B, 4, u, C1); s1 = acx * bcytail; c = splitter * acx; ahi = c - (c - acx); alo = acx - ahi; c = splitter * bcytail; bhi = c - (c - bcytail); blo = bcytail - bhi; s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); t1 = acy * bcxtail; c = splitter * acy; ahi = c - (c - acy); alo = acy - ahi; c = splitter * bcxtail; bhi = c - (c - bcxtail); blo = bcxtail - bhi; t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); _i = s0 - t0; bvirt = s0 - _i; u[0] = s0 - (_i + bvirt) + (bvirt - t0); _j = s1 + _i; bvirt = _j - s1; _0 = s1 - (_j - bvirt) + (_i - bvirt); _i = _0 - t1; bvirt = _0 - _i; u[1] = _0 - (_i + bvirt) + (bvirt - t1); u3 = _j + _i; bvirt = u3 - _j; u[2] = _j - (u3 - bvirt) + (_i - bvirt); u[3] = u3; const C2len = sum(C1len, C1, 4, u, C2); s1 = acxtail * bcytail; c = splitter * acxtail; ahi = c - (c - acxtail); alo = acxtail - ahi; c = splitter * bcytail; bhi = c - (c - bcytail); blo = bcytail - bhi; s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); t1 = acytail * bcxtail; c = splitter * acytail; ahi = c - (c - acytail); alo = acytail - ahi; c = splitter * bcxtail; bhi = c - (c - bcxtail); blo = bcxtail - bhi; t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); _i = s0 - t0; bvirt = s0 - _i; u[0] = s0 - (_i + bvirt) + (bvirt - t0); _j = s1 + _i; bvirt = _j - s1; _0 = s1 - (_j - bvirt) + (_i - bvirt); _i = _0 - t1; bvirt = _0 - _i; u[1] = _0 - (_i + bvirt) + (bvirt - t1); u3 = _j + _i; bvirt = u3 - _j; u[2] = _j - (u3 - bvirt) + (_i - bvirt); u[3] = u3; const Dlen = sum(C2len, C2, 4, u, D); return D[Dlen - 1]; } function orient2d(ax, ay, bx, by, cx, cy) { const detleft = (ay - cy) * (bx - cx); const detright = (ax - cx) * (by - cy); const det = detleft - detright; const detsum = Math.abs(detleft + detright); if (Math.abs(det) >= ccwerrboundA * detsum) return det; return -orient2dadapt(ax, ay, bx, by, cx, cy, detsum); } function pointInPolygon(p, polygon) { var i; var ii; var k = 0; var f; var u1; var v1; var u2; var v2; var currentP; var nextP; var x = p[0]; var y = p[1]; var numContours = polygon.length; for (i = 0; i < numContours; i++) { ii = 0; var contour = polygon[i]; var contourLen = contour.length - 1; currentP = contour[0]; if (currentP[0] !== contour[contourLen][0] && currentP[1] !== contour[contourLen][1]) { throw new Error('First and last coordinates in a ring must be the same') } u1 = currentP[0] - x; v1 = currentP[1] - y; for (ii; ii < contourLen; ii++) { nextP = contour[ii + 1]; u2 = nextP[0] - x; v2 = nextP[1] - y; if (v1 === 0 && v2 === 0) { if ((u2 <= 0 && u1 >= 0) || (u1 <= 0 && u2 >= 0)) { return 0 } } else if ((v2 >= 0 && v1 <= 0) || (v2 <= 0 && v1 >= 0)) { f = orient2d(u1, u2, v1, v2, 0, 0); if (f === 0) { return 0 } if ((f > 0 && v2 > 0 && v1 <= 0) || (f < 0 && v2 <= 0 && v1 > 0)) { k++; } } currentP = nextP; v1 = v2; u1 = u2; } } if (k % 2 === 0) { return false } return true } // index.ts function booleanPointInPolygon(point, polygon, options = {}) { if (!point) { throw new Error("point is required"); } if (!polygon) { throw new Error("polygon is required"); } const pt = getCoord(point); const geom = getGeom(polygon); const type = geom.type; const bbox = polygon.bbox; let polys = geom.coordinates; if (bbox && inBBox(pt, bbox) === false) { return false; } if (type === "Polygon") { polys = [polys]; } let result = false; for (var i = 0; i < polys.length; ++i) { const polyResult = pointInPolygon(pt, polys[i]); if (polyResult === 0) return options.ignoreBoundary ? false : true; else if (polyResult) result = true; } return result; } function inBBox(pt, bbox) { return bbox[0] <= pt[0] && bbox[1] <= pt[1] && bbox[2] >= pt[0] && bbox[3] >= pt[1]; } class SBBDataFetcher { constructor(args) { this.baseUrl = "https://data.sbb.ch/api/explore/v2.1/catalog/datasets"; this.dataSet = args.dataSet; this.maxRecordsPerPage = 50; } async *fetchRecords(args) { const { wmeSDK, offset = 0 } = args; const mapExtent = wmeSDK.Map.getMapExtent(); const x1 = mapExtent[0]; const y1 = mapExtent[1]; const x2 = mapExtent[2]; const y2 = mapExtent[3]; const url = `${this.baseUrl}/${this.dataSet}/records?where=in_bbox(geopos_haltestelle,${y1},${x1},${y2},${x2})&limit=50&offset=${offset}`; const response = await GM.xmlHttpRequest({ method: "GET", url, responseType: "json", }); const batch = response.response?.results || []; yield batch; if (batch.length === this.maxRecordsPerPage) { yield* this.fetchRecords({ wmeSDK, offset: offset + this.maxRecordsPerPage, }); } } } function haversineDistance(lat1, lon1, lat2, lon2) { const R = 6371000; const toRad = (x) => (x * Math.PI) / 180; const dLat = toRad(lat2 - lat1); const dLon = toRad(lon2 - lon1); const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2; const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; } function showWmeDialog(options) { const { message, buttons, allowHtml = false, cancelValue } = options; return new Promise((resolve) => { const backdrop = document.createElement("div"); backdrop.style.position = "fixed"; backdrop.style.inset = "0"; backdrop.style.background = "rgba(0,0,0,.35)"; backdrop.style.zIndex = "10000"; backdrop.style.display = "flex"; backdrop.style.alignItems = "center"; backdrop.style.justifyContent = "center"; const modal = document.createElement("div"); modal.style.background = "var(--wz-color-background, #ffffff)"; modal.style.color = "var(--wz-color-on-background, #1b1d20)"; modal.style.border = "1px solid var(--wz-color-hairline, #d9dde2)"; modal.style.padding = "20px"; modal.style.boxShadow = "0 2px 10px rgba(0,0,0,0.5)"; modal.style.borderRadius = "6px"; modal.style.textAlign = "center"; modal.style.minWidth = "200px"; modal.style.maxWidth = "min(90vw, 480px)"; modal.setAttribute("role", "dialog"); modal.setAttribute("aria-modal", "true"); const msg = document.createElement("p"); msg.style.whiteSpace = "pre-line"; if (allowHtml) msg.innerHTML = message; else msg.textContent = message; modal.appendChild(msg); const close = (value) => { document.removeEventListener("keydown", onKeydown, true); backdrop.remove(); resolve(value); }; function onKeydown(event) { if (event.key === "Escape" && cancelValue !== undefined) { event.stopPropagation(); close(cancelValue); } } const rendered = []; buttons.forEach(({ label, value }) => { const btn = document.createElement("button"); btn.textContent = label; btn.className = "btn btn-default"; btn.style.margin = "5px"; btn.onclick = () => close(value); modal.appendChild(btn); rendered.push(btn); }); backdrop.appendChild(modal); backdrop.onclick = (event) => { if (event.target === backdrop && cancelValue !== undefined) close(cancelValue); }; document.addEventListener("keydown", onKeydown, true); document.body.appendChild(backdrop); rendered[0]?.focus(); }); } async function waitForMapIdle(args) { const { wmeSDK, intervalMs = 50, maxTries = 60 } = args; for (let i = 0; i < maxTries; i += 1) { if (!wmeSDK.State.isMapLoading()) { await new Promise((resolve) => setTimeout(resolve, 100)); return; } await new Promise((resolve) => setTimeout(resolve, intervalMs)); } } class FeatureLayer extends Layer { constructor(args) { super({ name: args.name, wmeSDK: args.wmeSDK }); this.styleContext = args.styleContext; this.styleRules = args.styleRules; this.features = new Map(); this.visibleFeatureIds = new Set(); this.minZoomLevel = args.minZoomLevel ?? 15; } async addToMap(args) { const { wmeSDK } = args; wmeSDK.Map.addLayer({ layerName: this.name, styleContext: this.styleContext, styleRules: this.styleRules, }); wmeSDK.Events.trackLayerEvents({ layerName: this.name }); await this.render({ wmeSDK }); } removeFromMap(args) { super.removeFromMap(args); this.visibleFeatureIds.clear(); } drawFeaturesBatch(args) { const { wmeSDK, records } = args; const wazeFeatures = records.map((r) => this.mapRecordToFeature({ record: r })); wmeSDK.Map.addFeaturesToLayer({ features: wazeFeatures, layerName: this.name, }); } removeFeature(args) { const { wmeSDK, featureId } = args; const featureIdStr = String(featureId); wmeSDK.Map.removeFeatureFromLayer({ featureId: featureIdStr, layerName: this.name, }); this.visibleFeatureIds.delete(featureIdStr); } refilterFeatures(args) { const { wmeSDK } = args; const checked = wmeSDK.LayerSwitcher.isLayerCheckboxChecked({ name: this.name, }); if (!checked) { return; } const context = this.getFilterContext?.({ wmeSDK }); const toHide = Array.from(this.visibleFeatureIds).filter((featureId) => { const record = this.features.get(featureId); return record && !this.shouldDrawRecord({ wmeSDK, record, context }); }); if (toHide.length > 0) { wmeSDK.Map.removeFeaturesFromLayer({ featureIds: toHide, layerName: this.name, }); for (const featureId of toHide) { this.visibleFeatureIds.delete(featureId); } } } async render(args) { const { wmeSDK } = args; const checked = wmeSDK.LayerSwitcher.isLayerCheckboxChecked({ name: this.name, }); if (!checked) { return; } const zoomLevel = wmeSDK.Map.getZoomLevel(); if (zoomLevel < this.minZoomLevel) { return; } const allRecords = []; for await (const batch of this.fetchData({ wmeSDK })) { allRecords.push(...batch); } const newRecordsById = new Map(); for (const record of allRecords) { const recordId = this.getRecordId({ record }); newRecordsById.set(recordId, record); this.features.set(recordId, record); } const notYetDrawn = Array.from(newRecordsById.keys()).filter((id) => !this.visibleFeatureIds.has(id)); const context = this.getFilterContext?.({ wmeSDK }); const recordsToDraw = notYetDrawn .map((id) => newRecordsById.get(id)) .filter((record) => this.shouldDrawRecord({ wmeSDK, record, context })); if (recordsToDraw.length > 0) { this.drawFeaturesBatch({ wmeSDK, records: recordsToDraw }); for (const record of recordsToDraw) { this.visibleFeatureIds.add(this.getRecordId({ record })); } } const obsoleteIds = Array.from(this.visibleFeatureIds).filter((id) => !newRecordsById.has(id) || !this.shouldDrawRecord({ wmeSDK, record: this.features.get(id), context, })); for (const featureId of obsoleteIds) { wmeSDK.Map.removeFeatureFromLayer({ featureId, layerName: this.name, }); this.visibleFeatureIds.delete(featureId); this.features.delete(featureId); } } registerEvents(args) { const { wmeSDK } = args; const cleanupMove = wmeSDK.Events.on({ eventName: "wme-map-move-end", eventHandler: () => this.onMapMoveEnd({ wmeSDK }), }); this.eventCleanups.push(cleanupMove); const cleanupClick = wmeSDK.Events.on({ eventName: "wme-layer-feature-clicked", eventHandler: async ({ featureId, layerName }) => { if (layerName !== this.name) return; await this.featureClicked({ wmeSDK, featureId }); }, }); this.eventCleanups.push(cleanupClick); } onMapMoveEnd(args) { const { wmeSDK } = args; waitForMapIdle({ wmeSDK, intervalMs: 50, maxTries: 60 }).then(() => { this.render({ wmeSDK }); }); } restoreState(args) { super.restoreState(args); const { wmeSDK } = args; const checked = wmeSDK.LayerSwitcher.isLayerCheckboxChecked({ name: this.name, }); if (checked) { this.render({ wmeSDK }); this.registerEvents({ wmeSDK }); } } } class StopGeometry { pointToLineSegmentDistance(args) { const { point: p, lineStart, lineEnd } = args; const [px, py] = p.geometry.coordinates; const [x1, y1] = lineStart; const [x2, y2] = lineEnd; const A = px - x1; const B = py - y1; const C = x2 - x1; const D = y2 - y1; const dot = A * C + B * D; const lenSq = C * C + D * D; let param = -1; if (lenSq !== 0) { param = dot / lenSq; } let xx; let yy; if (param < 0) { xx = x1; yy = y1; } else if (param > 1) { xx = x2; yy = y2; } else { xx = x1 + param * C; yy = y1 + param * D; } const closestPoint = point([xx, yy]); return distance(p, closestPoint, { units: "meters" }); } distanceToVenueGeometry(args) { const { stopPoint, geometry } = args; if (geometry.type === "Point") { const coords = geometry.coordinates; if (!Array.isArray(coords) || coords.length < 2) return null; const [vLon, vLat] = coords; if (typeof vLon !== "number" || typeof vLat !== "number") return null; const venuePoint = point([vLon, vLat]); return distance(stopPoint, venuePoint, { units: "meters" }); } if (geometry.type === "Polygon") { const polygon = geometry; if (booleanPointInPolygon(stopPoint, polygon)) { return 0; } let minDistance = Infinity; for (const ring of polygon.coordinates) { for (let i = 0; i < ring.length - 1; i++) { const dist = this.pointToLineSegmentDistance({ point: stopPoint, lineStart: ring[i], lineEnd: ring[i + 1], }); minDistance = Math.min(minDistance, dist); } } return minDistance; } if (geometry.type === "MultiPolygon") { const multiPolygon = geometry; if (booleanPointInPolygon(stopPoint, multiPolygon)) { return 0; } let minDistance = Infinity; for (const polygon of multiPolygon.coordinates) { for (const ring of polygon) { for (let i = 0; i < ring.length - 1; i++) { const dist = this.pointToLineSegmentDistance({ point: stopPoint, lineStart: ring[i], lineEnd: ring[i + 1], }); minDistance = Math.min(minDistance, dist); } } } return minDistance; } return null; } isWithinRadius(args) { const { stopPoint, venueGeometry, radiusMeters } = args; const distMeters = this.distanceToVenueGeometry({ stopPoint, geometry: venueGeometry, }); if (distMeters === null) return false; return distMeters <= radiusMeters; } } const ABBREVIATION_EXPANSIONS = { Ptes: "Petites", Pte: "Petite", Pts: "Petits", Pt: "Petit", Gdes: "Grandes", Gde: "Grande", Gds: "Grands", Gd: "Grand", Ste: "Sainte", St: "Saint", Rte: "Route", "Bif.": "Bifurcation", }; function isCantonAbbreviation(value) { return /^[A-Z]{2}$/.test(value); } function isTruncatedLocality(prefix, localityName) { const p = prefix .trim() .toLowerCase() .replace(/[^\p{L}\p{N}]+$/u, ""); const l = localityName.trim().toLowerCase(); return p.length >= 3 && l.startsWith(p); } const RAILWAY_BRAND_SUFFIXES = new Set(["cff", "sbb", "ffs"]); function removeRailwayBrand(name) { return name .split(" ") .filter((token) => !RAILWAY_BRAND_SUFFIXES.has(token.toLowerCase())) .join(" ") .trim(); } function stripLocalityPrefix(name, localityName) { const loc = localityName.trim(); if (loc.length > 0 && name.toLowerCase().startsWith(loc.toLowerCase())) { const next = name.charAt(loc.length); if (next === "" || next === "," || /\s/.test(next)) { const candidate = name .slice(loc.length) .replace(/^[\s,]+/u, "") .trim(); if (candidate.length > 0 && !isCantonAbbreviation(candidate)) { return candidate; } return name.trim(); } } const commaIndex = name.indexOf(","); if (commaIndex !== -1) { const rest = name.slice(commaIndex + 1).trim(); if (rest.length > 0 && !isCantonAbbreviation(rest) && isTruncatedLocality(name.slice(0, commaIndex), loc)) { return rest; } } return name.trim(); } const ABBREVIATION_EXPANSIONS_LOWER = new Map(Object.entries(ABBREVIATION_EXPANSIONS).map(([abbr, full]) => [ abbr.toLowerCase(), full, ])); function expandAbbreviations(name) { return name .split(" ") .map((token) => ABBREVIATION_EXPANSIONS_LOWER.get(token.toLowerCase()) ?? token) .join(" "); } function cleanStopName(rawName, localityName) { let cleaned = rawName.replace(/\s*\([^)]*\)\s*$/u, "").trim(); cleaned = removeRailwayBrand(cleaned); cleaned = stripLocalityPrefix(cleaned, localityName); cleaned = expandAbbreviations(cleaned).trim(); return cleaned.charAt(0).toUpperCase() + cleaned.slice(1); } class StopNameFormatter { constructor() { this.venueInnerTypeMapping = new Map(); this.defaultVenueInnerType = "arrêt"; this.venueInnerTypeMapping.set("TRAIN", "gare"); this.venueInnerTypeMapping.set("BOAT", "port"); this.venueInnerTypeMapping.set("CHAIRLIFT", "remontée mécanique"); this.venueInnerTypeMapping.set("CABLE_RAILWAY", "station de funiculaire"); } meansOfTransport(meansoftransport) { return meansoftransport.split("|"); } getVenueInnerType(meansoftransport) { const means = this.meansOfTransport(meansoftransport); return means .map((mean) => this.venueInnerTypeMapping.get(mean) || this.defaultVenueInnerType) .join(", "); } normalizeOrganization(abbreviation, fullName) { const abbrevLower = abbreviation.toLowerCase(); if (abbrevLower === "sbb") { return { abbreviation: "CFF", fullName: "Chemins de fer fédéraux CFF", }; } if ([ "trn/tc", "trn/autovr", "trn/autrvt", "trn-tn", "trn-cmn", "trn-rvt", ].includes(abbrevLower)) { return { abbreviation: "transN", fullName: "Transports Publics Neuchâtelois SA", }; } if (abbrevLower === "pag") { return { abbreviation: "", fullName: "CarPostal SA", }; } return { abbreviation, fullName }; } formatName(stop) { const rawName = stop.designationofficial || stop.designation || "Bus Stop"; const cleanedName = cleanStopName(rawName, stop.localityname); const venueInnerType = this.getVenueInnerType(stop.meansoftransport); const { abbreviation, fullName } = this.normalizeOrganization(stop.businessorganisationabbreviationde, stop.businessorganisationdescriptionde); const aliases = []; const shortName = cleanedName; if (stop.businessorganisationabbreviationde.toLowerCase() === "sbb") { aliases.push(`${cleanedName} (${venueInnerType} ${stop.businessorganisationdescriptionde})`); aliases.push(`${cleanedName} (${venueInnerType} ${stop.businessorganisationabbreviationde})`); } if (abbreviation !== "") { aliases.push(`${cleanedName} (${venueInnerType} ${fullName})`); return { name: `${cleanedName} (${venueInnerType} ${abbreviation})`, aliases, shortName, }; } return { name: `${cleanedName} (${venueInnerType} ${fullName})`, aliases, shortName, }; } } class VenueMatcher { constructor() { this.stopGeometry = new StopGeometry(); } findMatchingVenues(args) { const { venues, stopLon, stopLat, categories, radiusMeters } = args; const stopPoint = point([stopLon, stopLat]); return venues.filter((venue) => { const hasMatchingCategory = venue.categories.some((cat) => categories.includes(cat)); if (!hasMatchingCategory) return false; return this.stopGeometry.isWithinRadius({ stopPoint, venueGeometry: venue.geometry, radiusMeters, }); }); } hasExactMatch(args) { const { venues, stopLon, stopLat, stopName, categories } = args; const stopPoint = point([stopLon, stopLat]); return venues.some((v) => { if (v.name !== stopName) return false; const hasMatchingCategory = v.categories.some((cat) => categories.includes(cat)); if (!hasMatchingCategory) return false; return this.stopGeometry.isWithinRadius({ stopPoint, venueGeometry: v.geometry, radiusMeters: 75, }); }); } } const TRANSPORT_CATEGORIES = [ "BUS_STATION", "TRAIN_STATION", "SUBWAY_STATION", "SEAPORT_MARINA_HARBOR", "TRANSPORTATION", ]; class WazeVenueFetcher { getApiBaseUrl(args) { const host = args.wmeSDK.isBetaEnvironment() ? "https://beta.waze.com" : "https://www.waze.com"; const region = args.wmeSDK.Settings.getRegionCode() ?? "row"; return `${host}/${region}-Descartes`; } async fetchVenuesForBbox(args) { const apiBaseUrl = this.getApiBaseUrl({ wmeSDK: args.wmeSDK }); const [x1, y1, x2, y2] = args.bbox; const bbox = `${x1},${y1},${x2},${y2}`; const url = `${apiBaseUrl}/app/Features?bbox=${encodeURIComponent(bbox)}&v=2&apiV2=true&venueLevel=4`; let response; try { response = await GM.xmlHttpRequest({ method: "GET", url, responseType: "json", }); } catch (error) { console.warn("[WazeVenueFetcher] Request failed:", error); return []; } if (response.status !== 200) { console.warn(`[WazeVenueFetcher] API returned ${response.status}`); return []; } let data = response.response; if (typeof data === "string") { try { data = JSON.parse(data); } catch { data = null; } } const objects = data?.venues?.objects ?? []; return objects .filter((obj) => obj.id !== undefined && obj.name && obj.geometry && obj.categories.some((c) => typeof c === "string" && TRANSPORT_CATEGORIES.includes(c))) .map((obj) => ({ id: obj.id, name: obj.name, categories: obj.categories .filter((c) => typeof c === "string") .map((c) => c), geometry: obj.geometry, })); } } const CLUSTER_RADIUS_METERS = { 12: 4000, 13: 2000, 14: 800, }; class ClusterManager { cluster(args) { const { items, zoomLevel } = args; const radius = CLUSTER_RADIUS_METERS[zoomLevel] ?? 800; const sorted = [...items].sort((a, b) => a.lat - b.lat); const assigned = new Set(); const clusters = []; const singles = []; for (const anchor of sorted) { if (assigned.has(anchor.id)) continue; const nearby = sorted.filter((item) => !assigned.has(item.id) && item.kind === anchor.kind && haversineDistance(anchor.lat, anchor.lon, item.lat, item.lon) <= radius); if (nearby.length === 1) { singles.push(anchor); assigned.add(anchor.id); continue; } for (const item of nearby) assigned.add(item.id); const lons = nearby.map((i) => i.lon); const lats = nearby.map((i) => i.lat); const minLon = Math.min(...lons); const maxLon = Math.max(...lons); const minLat = Math.min(...lats); const maxLat = Math.max(...lats); clusters.push({ id: `cluster-${anchor.kind}-${anchor.id}`, center: { lat: (minLat + maxLat) / 2, lon: (minLon + maxLon) / 2 }, bbox: [minLon, minLat, maxLon, maxLat], count: nearby.length, kind: anchor.kind, itemIds: nearby.map((i) => i.id), }); } return { clusters, singles }; } zoomForBbox(bbox) { const spanLon = Math.abs(bbox[2] - bbox[0]); const spanLat = Math.abs(bbox[3] - bbox[1]); const maxSpan = Math.max(spanLon, spanLat); if (maxSpan < 0.004) return 17; if (maxSpan < 0.008) return 16; if (maxSpan < 0.016) return 15; if (maxSpan < 0.032) return 14; return 13; } } function findCityForStop(localityName, lookupCity) { const direct = lookupCity(localityName); if (direct) return direct; const trimmed = localityName.trim(); if (/[A-Z]{2}$/.test(trimmed)) { const withoutCanton = trimmed.slice(0, -3).trim(); if (withoutCanton.length > 0) return lookupCity(withoutCanton); } return null; } function isStopActive(validTo, today) { return validTo >= today; } function todayIsoDate() { const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, "0"); const day = String(now.getDate()).padStart(2, "0"); return `${year}-${month}-${day}`; } const OVERLAY_BAR_SELECTOR = ".overlay-buttons-container.top"; const STYLE_ELEMENT_ID = "wme-ch-reload-button-style"; const BUTTON_CLASS = "wme-ch-reload-button"; const MOUNT_RETRY_MS = 300; const MOUNT_MAX_RETRIES = 20; class ReloadButton { constructor(args) { this.button = null; this.retries = 0; this.onClick = args.onClick; this.title = args.title; } mount() { if (this.button?.isConnected) return; const bar = document.querySelector(OVERLAY_BAR_SELECTOR); if (!bar) { if (this.retries++ >= MOUNT_MAX_RETRIES) { console.warn("[ReloadButton] overlay button bar not found"); return; } setTimeout(() => this.mount(), MOUNT_RETRY_MS); return; } this.retries = 0; this.injectStyle(); const button = document.createElement("wz-button"); button.className = `overlay-button ${BUTTON_CLASS}`; button.setAttribute("color", "clear-icon"); button.setAttribute("size", "md"); button.setAttribute("type", "button"); button.title = this.title; const icon = document.createElement("i"); icon.className = "w-icon w-icon-bus"; button.appendChild(icon); button.addEventListener("click", () => { if (button.classList.contains("is-loading")) return; this.onClick(); }); bar.appendChild(button); this.button = button; } unmount() { this.button?.remove(); this.button = null; } setLoading(loading) { if (!this.button) return; this.button.classList.toggle("is-loading", loading); if (loading) this.button.setAttribute("disabled", ""); else this.button.removeAttribute("disabled"); } injectStyle() { if (document.getElementById(STYLE_ELEMENT_ID)) return; const style = document.createElement("style"); style.id = STYLE_ELEMENT_ID; style.textContent = ` @keyframes wme-ch-reload-spin { to { transform: rotate(360deg); } } .${BUTTON_CLASS}.is-loading { pointer-events: none; opacity: 0.6; } .${BUTTON_CLASS}.is-loading .w-icon-bus { display: inline-block; animation: wme-ch-reload-spin 1s linear infinite; } `; document.head.appendChild(style); } } const isString = obj => typeof obj === 'string'; const defer = () => { let res; let rej; const promise = new Promise((resolve, reject) => { res = resolve; rej = reject; }); promise.resolve = res; promise.reject = rej; return promise; }; const makeString = object => { if (object == null) return ''; return '' + object; }; const copy = (a, s, t) => { a.forEach(m => { if (s[m]) t[m] = s[m]; }); }; const lastOfPathSeparatorRegExp = /###/g; const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key; const canNotTraverseDeeper = object => !object || isString(object); const getLastOfPath = (object, path, Empty) => { const stack = !isString(path) ? path : path.split('.'); let stackIndex = 0; while (stackIndex < stack.length - 1) { if (canNotTraverseDeeper(object)) return {}; const key = cleanKey(stack[stackIndex]); if (!object[key] && Empty) object[key] = new Empty(); if (Object.prototype.hasOwnProperty.call(object, key)) { object = object[key]; } else { object = {}; } ++stackIndex; } if (canNotTraverseDeeper(object)) return {}; return { obj: object, k: cleanKey(stack[stackIndex]) }; }; const setPath = (object, path, newValue) => { const { obj, k } = getLastOfPath(object, path, Object); if (obj !== undefined || path.length === 1) { obj[k] = newValue; return; } let e = path[path.length - 1]; let p = path.slice(0, path.length - 1); let last = getLastOfPath(object, p, Object); while (last.obj === undefined && p.length) { e = `${p[p.length - 1]}.${e}`; p = p.slice(0, p.length - 1); last = getLastOfPath(object, p, Object); if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') { last.obj = undefined; } } last.obj[`${last.k}.${e}`] = newValue; }; const pushPath = (object, path, newValue, concat) => { const { obj, k } = getLastOfPath(object, path, Object); obj[k] = obj[k] || []; obj[k].push(newValue); }; const getPath = (object, path) => { const { obj, k } = getLastOfPath(object, path); if (!obj) return undefined; if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined; return obj[k]; }; const getPathWithDefaults = (data, defaultData, key) => { const value = getPath(data, key); if (value !== undefined) { return value; } return getPath(defaultData, key); }; const deepExtend = (target, source, overwrite) => { for (const prop in source) { if (prop !== '__proto__' && prop !== 'constructor') { if (prop in target) { if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) { if (overwrite) target[prop] = source[prop]; } else { deepExtend(target[prop], source[prop], overwrite); } } else { target[prop] = source[prop]; } } } return target; }; const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); var _entityMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '/': '/' }; const escape = data => { if (isString(data)) { return data.replace(/[&<>"'\/]/g, s => _entityMap[s]); } return data; }; class RegExpCache { constructor(capacity) { this.capacity = capacity; this.regExpMap = new Map(); this.regExpQueue = []; } getRegExp(pattern) { const regExpFromCache = this.regExpMap.get(pattern); if (regExpFromCache !== undefined) { return regExpFromCache; } const regExpNew = new RegExp(pattern); if (this.regExpQueue.length === this.capacity) { this.regExpMap.delete(this.regExpQueue.shift()); } this.regExpMap.set(pattern, regExpNew); this.regExpQueue.push(pattern); return regExpNew; } } const chars = [' ', ',', '?', '!', ';']; const looksLikeObjectPathRegExpCache = new RegExpCache(20); const looksLikeObjectPath = (key, nsSeparator, keySeparator) => { nsSeparator = nsSeparator || ''; keySeparator = keySeparator || ''; const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0); if (possibleChars.length === 0) return true; const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`); let matched = !r.test(key); if (!matched) { const ki = key.indexOf(keySeparator); if (ki > 0 && !r.test(key.substring(0, ki))) { matched = true; } } return matched; }; const deepFind = (obj, path, keySeparator = '.') => { if (!obj) return undefined; if (obj[path]) { if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined; return obj[path]; } const tokens = path.split(keySeparator); let current = obj; for (let i = 0; i < tokens.length;) { if (!current || typeof current !== 'object') { return undefined; } let next; let nextPath = ''; for (let j = i; j < tokens.length; ++j) { if (j !== i) { nextPath += keySeparator; } nextPath += tokens[j]; next = current[nextPath]; if (next !== undefined) { if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) { continue; } i += j - i + 1; break; } } current = next; } return current; }; const getCleanedCode = code => code?.replace('_', '-'); const consoleLogger = { type: 'logger', log(args) { this.output('log', args); }, warn(args) { this.output('warn', args); }, error(args) { this.output('error', args); }, output(type, args) { console?.[type]?.apply?.(console, args); } }; class Logger { constructor(concreteLogger, options = {}) { this.init(concreteLogger, options); } init(concreteLogger, options = {}) { this.prefix = options.prefix || 'i18next:'; this.logger = concreteLogger || consoleLogger; this.options = options; this.debug = options.debug; } log(...args) { return this.forward(args, 'log', '', true); } warn(...args) { return this.forward(args, 'warn', '', true); } error(...args) { return this.forward(args, 'error', ''); } deprecate(...args) { return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true); } forward(args, lvl, prefix, debugOnly) { if (debugOnly && !this.debug) return null; if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`; return this.logger[lvl](args); } create(moduleName) { return new Logger(this.logger, { ...{ prefix: `${this.prefix}:${moduleName}:` }, ...this.options }); } clone(options) { options = options || this.options; options.prefix = options.prefix || this.prefix; return new Logger(this.logger, options); } } var baseLogger = new Logger(); class EventEmitter { constructor() { this.observers = {}; } on(events, listener) { events.split(' ').forEach(event => { if (!this.observers[event]) this.observers[event] = new Map(); const numListeners = this.observers[event].get(listener) || 0; this.observers[event].set(listener, numListeners + 1); }); return this; } off(event, listener) { if (!this.observers[event]) return; if (!listener) { delete this.observers[event]; return; } this.observers[event].delete(listener); } emit(event, ...args) { if (this.observers[event]) { const cloned = Array.from(this.observers[event].entries()); cloned.forEach(([observer, numTimesAdded]) => { for (let i = 0; i < numTimesAdded; i++) { observer(...args); } }); } if (this.observers['*']) { const cloned = Array.from(this.observers['*'].entries()); cloned.forEach(([observer, numTimesAdded]) => { for (let i = 0; i < numTimesAdded; i++) { observer.apply(observer, [event, ...args]); } }); } } } class ResourceStore extends EventEmitter { constructor(data, options = { ns: ['translation'], defaultNS: 'translation' }) { super(); this.data = data || {}; this.options = options; if (this.options.keySeparator === undefined) { this.options.keySeparator = '.'; } if (this.options.ignoreJSONStructure === undefined) { this.options.ignoreJSONStructure = true; } } addNamespaces(ns) { if (this.options.ns.indexOf(ns) < 0) { this.options.ns.push(ns); } } removeNamespaces(ns) { const index = this.options.ns.indexOf(ns); if (index > -1) { this.options.ns.splice(index, 1); } } getResource(lng, ns, key, options = {}) { const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure; let path; if (lng.indexOf('.') > -1) { path = lng.split('.'); } else { path = [lng, ns]; if (key) { if (Array.isArray(key)) { path.push(...key); } else if (isString(key) && keySeparator) { path.push(...key.split(keySeparator)); } else { path.push(key); } } } const result = getPath(this.data, path); if (!result && !ns && !key && lng.indexOf('.') > -1) { lng = path[0]; ns = path[1]; key = path.slice(2).join('.'); } if (result || !ignoreJSONStructure || !isString(key)) return result; return deepFind(this.data?.[lng]?.[ns], key, keySeparator); } addResource(lng, ns, key, value, options = { silent: false }) { const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; let path = [lng, ns]; if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key); if (lng.indexOf('.') > -1) { path = lng.split('.'); value = ns; ns = path[1]; } this.addNamespaces(ns); setPath(this.data, path, value); if (!options.silent) this.emit('added', lng, ns, key, value); } addResources(lng, ns, resources, options = { silent: false }) { for (const m in resources) { if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], { silent: true }); } if (!options.silent) this.emit('added', lng, ns, resources); } addResourceBundle(lng, ns, resources, deep, overwrite, options = { silent: false, skipCopy: false }) { let path = [lng, ns]; if (lng.indexOf('.') > -1) { path = lng.split('.'); deep = resources; resources = ns; ns = path[1]; } this.addNamespaces(ns); let pack = getPath(this.data, path) || {}; if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources)); if (deep) { deepExtend(pack, resources, overwrite); } else { pack = { ...pack, ...resources }; } setPath(this.data, path, pack); if (!options.silent) this.emit('added', lng, ns, resources); } removeResourceBundle(lng, ns) { if (this.hasResourceBundle(lng, ns)) { delete this.data[lng][ns]; } this.removeNamespaces(ns); this.emit('removed', lng, ns); } hasResourceBundle(lng, ns) { return this.getResource(lng, ns) !== undefined; } getResourceBundle(lng, ns) { if (!ns) ns = this.options.defaultNS; return this.getResource(lng, ns); } getDataByLanguage(lng) { return this.data[lng]; } hasLanguageSomeTranslations(lng) { const data = this.getDataByLanguage(lng); const n = data && Object.keys(data) || []; return !!n.find(v => data[v] && Object.keys(data[v]).length > 0); } toJSON() { return this.data; } } var postProcessor = { processors: {}, addPostProcessor(module) { this.processors[module.name] = module; }, handle(processors, value, key, options, translator) { processors.forEach(processor => { value = this.processors[processor]?.process(value, key, options, translator) ?? value; }); return value; } }; const checkedLoadedFor = {}; const shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number'; class Translator extends EventEmitter { constructor(services, options = {}) { super(); copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this); this.options = options; if (this.options.keySeparator === undefined) { this.options.keySeparator = '.'; } this.logger = baseLogger.create('translator'); } changeLanguage(lng) { if (lng) this.language = lng; } exists(key, o = { interpolation: {} }) { const opt = { ...o }; if (key == null) return false; const resolved = this.resolve(key, opt); return resolved?.res !== undefined; } extractFromKey(key, opt) { let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator; if (nsSeparator === undefined) nsSeparator = ':'; const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator; let namespaces = opt.ns || this.options.defaultNS || []; const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1; const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator); if (wouldCheckForNsInKey && !seemsNaturalLanguage) { const m = key.match(this.interpolator.nestingRegexp); if (m && m.length > 0) { return { key, namespaces: isString(namespaces) ? [namespaces] : namespaces }; } const parts = key.split(nsSeparator); if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift(); key = parts.join(keySeparator); } return { key, namespaces: isString(namespaces) ? [namespaces] : namespaces }; } translate(keys, o, lastKey) { let opt = typeof o === 'object' ? { ...o } : o; if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) { opt = this.options.overloadTranslationOptionHandler(arguments); } if (typeof options === 'object') opt = { ...opt }; if (!opt) opt = {}; if (keys == null) return ''; if (!Array.isArray(keys)) keys = [String(keys)]; const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails; const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator; const { key, namespaces } = this.extractFromKey(keys[keys.length - 1], opt); const namespace = namespaces[namespaces.length - 1]; let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator; if (nsSeparator === undefined) nsSeparator = ':'; const lng = opt.lng || this.language; const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; if (lng?.toLowerCase() === 'cimode') { if (appendNamespaceToCIMode) { if (returnDetails) { return { res: `${namespace}${nsSeparator}${key}`, usedKey: key, exactUsedKey: key, usedLng: lng, usedNS: namespace, usedParams: this.getUsedParamsDetails(opt) }; } return `${namespace}${nsSeparator}${key}`; } if (returnDetails) { return { res: key, usedKey: key, exactUsedKey: key, usedLng: lng, usedNS: namespace, usedParams: this.getUsedParamsDetails(opt) }; } return key; } const resolved = this.resolve(keys, opt); let res = resolved?.res; const resUsedKey = resolved?.usedKey || key; const resExactUsedKey = resolved?.exactUsedKey || key; const noObject = ['[object Number]', '[object Function]', '[object RegExp]']; const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays; const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject; const needsPluralHandling = opt.count !== undefined && !isString(opt.count); const hasDefaultValue = Translator.hasDefaultValue(opt); const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : ''; const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, { ordinal: false }) : ''; const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0; const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue; let resForObjHndl = res; if (handleAsObjectInI18nFormat && !res && hasDefaultValue) { resForObjHndl = defaultValue; } const handleAsObject = shouldHandleAsObject(resForObjHndl); const resType = Object.prototype.toString.apply(resForObjHndl); if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) { if (!opt.returnObjects && !this.options.returnObjects) { if (!this.options.returnedObjectHandler) { this.logger.warn('accessing an object - but returnObjects options is not enabled!'); } const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, { ...opt, ns: namespaces }) : `key '${key} (${this.language})' returned an object instead of string.`; if (returnDetails) { resolved.res = r; resolved.usedParams = this.getUsedParamsDetails(opt); return resolved; } return r; } if (keySeparator) { const resTypeIsArray = Array.isArray(resForObjHndl); const copy = resTypeIsArray ? [] : {}; const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey; for (const m in resForObjHndl) { if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) { const deepKey = `${newKeyToUse}${keySeparator}${m}`; if (hasDefaultValue && !res) { copy[m] = this.translate(deepKey, { ...opt, defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined, ...{ joinArrays: false, ns: namespaces } }); } else { copy[m] = this.translate(deepKey, { ...opt, ...{ joinArrays: false, ns: namespaces } }); } if (copy[m] === deepKey) copy[m] = resForObjHndl[m]; } } res = copy; } } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) { res = res.join(joinArrays); if (res) res = this.extendTranslation(res, keys, opt, lastKey); } else { let usedDefault = false; let usedKey = false; if (!this.isValidLookup(res) && hasDefaultValue) { usedDefault = true; res = defaultValue; } if (!this.isValidLookup(res)) { usedKey = true; res = key; } const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey; const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res; const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing; if (usedKey || usedDefault || updateMissing) { this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res); if (keySeparator) { const fk = this.resolve(key, { ...opt, keySeparator: false }); if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.'); } let lngs = []; const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language); if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) { for (let i = 0; i < fallbackLngs.length; i++) { lngs.push(fallbackLngs[i]); } } else if (this.options.saveMissingTo === 'all') { lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language); } else { lngs.push(opt.lng || this.language); } const send = (l, k, specificDefaultValue) => { const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing; if (this.options.missingKeyHandler) { this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt); } else if (this.backendConnector?.saveMissing) { this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt); } this.emit('missingKey', l, namespace, k, res); }; if (this.options.saveMissing) { if (this.options.saveMissingPlurals && needsPluralHandling) { lngs.forEach(language => { const suffixes = this.pluralResolver.getSuffixes(language, opt); if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) { suffixes.push(`${this.options.pluralSeparator}zero`); } suffixes.forEach(suffix => { send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue); }); }); } else { send(lngs, key, defaultValue); } } } res = this.extendTranslation(res, keys, opt, resolved, lastKey); if (usedKey && res === key && this.options.appendNamespaceToMissingKey) { res = `${namespace}${nsSeparator}${key}`; } if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) { res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt); } } if (returnDetails) { resolved.res = res; resolved.usedParams = this.getUsedParamsDetails(opt); return resolved; } return res; } extendTranslation(res, key, opt, resolved, lastKey) { if (this.i18nFormat?.parse) { res = this.i18nFormat.parse(res, { ...this.options.interpolation.defaultVariables, ...opt }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, { resolved }); } else if (!opt.skipInterpolation) { if (opt.interpolation) this.interpolator.init({ ...opt, ...{ interpolation: { ...this.options.interpolation, ...opt.interpolation } } }); const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables); let nestBef; if (skipOnVariables) { const nb = res.match(this.interpolator.nestingRegexp); nestBef = nb && nb.length; } let data = opt.replace && !isString(opt.replace) ? opt.replace : opt; if (this.options.interpolation.defaultVariables) data = { ...this.options.interpolation.defaultVariables, ...data }; res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt); if (skipOnVariables) { const na = res.match(this.interpolator.nestingRegexp); const nestAft = na && na.length; if (nestBef < nestAft) opt.nest = false; } if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng; if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => { if (lastKey?.[0] === args[0] && !opt.context) { this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`); return null; } return this.translate(...args, key); }, opt); if (opt.interpolation) this.interpolator.reset(); } const postProcess = opt.postProcess || this.options.postProcess; const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess; if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) { res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? { i18nResolved: { ...resolved, usedParams: this.getUsedParamsDetails(opt) }, ...opt } : opt, this); } return res; } resolve(keys, opt = {}) { let found; let usedKey; let exactUsedKey; let usedLng; let usedNS; if (isString(keys)) keys = [keys]; keys.forEach(k => { if (this.isValidLookup(found)) return; const extracted = this.extractFromKey(k, opt); const key = extracted.key; usedKey = key; let namespaces = extracted.namespaces; if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS); const needsPluralHandling = opt.count !== undefined && !isString(opt.count); const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0; const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== ''; const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng); namespaces.forEach(ns => { if (this.isValidLookup(found)) return; usedNS = ns; if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) { checkedLoadedFor[`${codes[0]}-${ns}`] = true; this.logger.warn(`key "${usedKey}" for languages "${codes.join(', ')}" won't get resolved as namespace "${usedNS}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'); } codes.forEach(code => { if (this.isValidLookup(found)) return; usedLng = code; const finalKeys = [key]; if (this.i18nFormat?.addLookupKeys) { this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt); } else { let pluralSuffix; if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt); const zeroSuffix = `${this.options.pluralSeparator}zero`; const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`; if (needsPluralHandling) { finalKeys.push(key + pluralSuffix); if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) { finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); } if (needsZeroSuffixLookup) { finalKeys.push(key + zeroSuffix); } } if (needsContextHandling) { const contextKey = `${key}${this.options.contextSeparator}${opt.context}`; finalKeys.push(contextKey); if (needsPluralHandling) { finalKeys.push(contextKey + pluralSuffix); if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) { finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); } if (needsZeroSuffixLookup) { finalKeys.push(contextKey + zeroSuffix); } } } } let possibleKey; while (possibleKey = finalKeys.pop()) { if (!this.isValidLookup(found)) { exactUsedKey = possibleKey; found = this.getResource(code, ns, possibleKey, opt); } } }); }); }); return { res: found, usedKey, exactUsedKey, usedLng, usedNS }; } isValidLookup(res) { return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === ''); } getResource(code, ns, key, options = {}) { if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options); return this.resourceStore.getResource(code, ns, key, options); } getUsedParamsDetails(options = {}) { const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation']; const useOptionsReplaceForData = options.replace && !isString(options.replace); let data = useOptionsReplaceForData ? options.replace : options; if (useOptionsReplaceForData && typeof options.count !== 'undefined') { data.count = options.count; } if (this.options.interpolation.defaultVariables) { data = { ...this.options.interpolation.defaultVariables, ...data }; } if (!useOptionsReplaceForData) { data = { ...data }; for (const key of optionsKeys) { delete data[key]; } } return data; } static hasDefaultValue(options) { const prefix = 'defaultValue'; for (const option in options) { if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) { return true; } } return false; } } class LanguageUtil { constructor(options) { this.options = options; this.supportedLngs = this.options.supportedLngs || false; this.logger = baseLogger.create('languageUtils'); } getScriptPartFromCode(code) { code = getCleanedCode(code); if (!code || code.indexOf('-') < 0) return null; const p = code.split('-'); if (p.length === 2) return null; p.pop(); if (p[p.length - 1].toLowerCase() === 'x') return null; return this.formatLanguageCode(p.join('-')); } getLanguagePartFromCode(code) { code = getCleanedCode(code); if (!code || code.indexOf('-') < 0) return code; const p = code.split('-'); return this.formatLanguageCode(p[0]); } formatLanguageCode(code) { if (isString(code) && code.indexOf('-') > -1) { let formattedCode; try { formattedCode = Intl.getCanonicalLocales(code)[0]; } catch (e) {} if (formattedCode && this.options.lowerCaseLng) { formattedCode = formattedCode.toLowerCase(); } if (formattedCode) return formattedCode; if (this.options.lowerCaseLng) { return code.toLowerCase(); } return code; } return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code; } isSupportedCode(code) { if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) { code = this.getLanguagePartFromCode(code); } return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1; } getBestMatchFromCodes(codes) { if (!codes) return null; let found; codes.forEach(code => { if (found) return; const cleanedLng = this.formatLanguageCode(code); if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng; }); if (!found && this.options.supportedLngs) { codes.forEach(code => { if (found) return; const lngScOnly = this.getScriptPartFromCode(code); if (this.isSupportedCode(lngScOnly)) return found = lngScOnly; const lngOnly = this.getLanguagePartFromCode(code); if (this.isSupportedCode(lngOnly)) return found = lngOnly; found = this.options.supportedLngs.find(supportedLng => { if (supportedLng === lngOnly) return supportedLng; if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return; if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng; if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng; }); }); } if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0]; return found; } getFallbackCodes(fallbacks, code) { if (!fallbacks) return []; if (typeof fallbacks === 'function') fallbacks = fallbacks(code); if (isString(fallbacks)) fallbacks = [fallbacks]; if (Array.isArray(fallbacks)) return fallbacks; if (!code) return fallbacks.default || []; let found = fallbacks[code]; if (!found) found = fallbacks[this.getScriptPartFromCode(code)]; if (!found) found = fallbacks[this.formatLanguageCode(code)]; if (!found) found = fallbacks[this.getLanguagePartFromCode(code)]; if (!found) found = fallbacks.default; return found || []; } toResolveHierarchy(code, fallbackCode) { const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code); const codes = []; const addCode = c => { if (!c) return; if (this.isSupportedCode(c)) { codes.push(c); } else { this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`); } }; if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) { if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code)); if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code)); if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code)); } else if (isString(code)) { addCode(this.formatLanguageCode(code)); } fallbackCodes.forEach(fc => { if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc)); }); return codes; } } const suffixesOrder = { zero: 0, one: 1, two: 2, few: 3, many: 4, other: 5 }; const dummyRule = { select: count => count === 1 ? 'one' : 'other', resolvedOptions: () => ({ pluralCategories: ['one', 'other'] }) }; class PluralResolver { constructor(languageUtils, options = {}) { this.languageUtils = languageUtils; this.options = options; this.logger = baseLogger.create('pluralResolver'); this.pluralRulesCache = {}; } addRule(lng, obj) { this.rules[lng] = obj; } clearCache() { this.pluralRulesCache = {}; } getRule(code, options = {}) { const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code); const type = options.ordinal ? 'ordinal' : 'cardinal'; const cacheKey = JSON.stringify({ cleanedCode, type }); if (cacheKey in this.pluralRulesCache) { return this.pluralRulesCache[cacheKey]; } let rule; try { rule = new Intl.PluralRules(cleanedCode, { type }); } catch (err) { if (!Intl) { this.logger.error('No Intl support, please use an Intl polyfill!'); return dummyRule; } if (!code.match(/-|_/)) return dummyRule; const lngPart = this.languageUtils.getLanguagePartFromCode(code); rule = this.getRule(lngPart, options); } this.pluralRulesCache[cacheKey] = rule; return rule; } needsPlural(code, options = {}) { let rule = this.getRule(code, options); if (!rule) rule = this.getRule('dev', options); return rule?.resolvedOptions().pluralCategories.length > 1; } getPluralFormsOfKey(code, key, options = {}) { return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`); } getSuffixes(code, options = {}) { let rule = this.getRule(code, options); if (!rule) rule = this.getRule('dev', options); if (!rule) return []; return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`); } getSuffix(code, count, options = {}) { const rule = this.getRule(code, options); if (rule) { return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`; } this.logger.warn(`no plural rule found for: ${code}`); return this.getSuffix('dev', count, options); } } const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => { let path = getPathWithDefaults(data, defaultData, key); if (!path && ignoreJSONStructure && isString(key)) { path = deepFind(data, key, keySeparator); if (path === undefined) path = deepFind(defaultData, key, keySeparator); } return path; }; const regexSafe = val => val.replace(/\$/g, '$$$$'); class Interpolator { constructor(options = {}) { this.logger = baseLogger.create('interpolator'); this.options = options; this.format = options?.interpolation?.format || (value => value); this.init(options); } init(options = {}) { if (!options.interpolation) options.interpolation = { escapeValue: true }; const { escape: escape$1, escapeValue, useRawValueToEscape, prefix, prefixEscaped, suffix, suffixEscaped, formatSeparator, unescapeSuffix, unescapePrefix, nestingPrefix, nestingPrefixEscaped, nestingSuffix, nestingSuffixEscaped, nestingOptionsSeparator, maxReplaces, alwaysFormat } = options.interpolation; this.escape = escape$1 !== undefined ? escape$1 : escape; this.escapeValue = escapeValue !== undefined ? escapeValue : true; this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false; this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{'; this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}'; this.formatSeparator = formatSeparator || ','; this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-'; this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || ''; this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t('); this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')'); this.nestingOptionsSeparator = nestingOptionsSeparator || ','; this.maxReplaces = maxReplaces || 1000; this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false; this.resetRegExp(); } reset() { if (this.options) this.init(this.options); } resetRegExp() { const getOrResetRegExp = (existingRegExp, pattern) => { if (existingRegExp?.source === pattern) { existingRegExp.lastIndex = 0; return existingRegExp; } return new RegExp(pattern, 'g'); }; this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`); this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`); this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}(.+?)${this.nestingSuffix}`); } interpolate(str, data, lng, options) { let match; let value; let replaces; const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {}; const handleFormat = key => { if (key.indexOf(this.formatSeparator) < 0) { const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure); return this.alwaysFormat ? this.format(path, undefined, lng, { ...options, ...data, interpolationkey: key }) : path; } const p = key.split(this.formatSeparator); const k = p.shift().trim(); const f = p.join(this.formatSeparator).trim(); return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, { ...options, ...data, interpolationkey: k }); }; this.resetRegExp(); const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler; const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables; const todos = [{ regex: this.regexpUnescape, safeValue: val => regexSafe(val) }, { regex: this.regexp, safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val) }]; todos.forEach(todo => { replaces = 0; while (match = todo.regex.exec(str)) { const matchedVar = match[1].trim(); value = handleFormat(matchedVar); if (value === undefined) { if (typeof missingInterpolationHandler === 'function') { const temp = missingInterpolationHandler(str, match, options); value = isString(temp) ? temp : ''; } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) { value = ''; } else if (skipOnVariables) { value = match[0]; continue; } else { this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`); value = ''; } } else if (!isString(value) && !this.useRawValueToEscape) { value = makeString(value); } const safeValue = todo.safeValue(value); str = str.replace(match[0], safeValue); if (skipOnVariables) { todo.regex.lastIndex += value.length; todo.regex.lastIndex -= match[0].length; } else { todo.regex.lastIndex = 0; } replaces++; if (replaces >= this.maxReplaces) { break; } } }); return str; } nest(str, fc, options = {}) { let match; let value; let clonedOptions; const handleHasOptions = (key, inheritedOptions) => { const sep = this.nestingOptionsSeparator; if (key.indexOf(sep) < 0) return key; const c = key.split(new RegExp(`${sep}[ ]*{`)); let optionsString = `{${c[1]}`; key = c[0]; optionsString = this.interpolate(optionsString, clonedOptions); const matchedSingleQuotes = optionsString.match(/'/g); const matchedDoubleQuotes = optionsString.match(/"/g); if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) { optionsString = optionsString.replace(/'/g, '"'); } try { clonedOptions = JSON.parse(optionsString); if (inheritedOptions) clonedOptions = { ...inheritedOptions, ...clonedOptions }; } catch (e) { this.logger.warn(`failed parsing options string in nesting for key ${key}`, e); return `${key}${sep}${optionsString}`; } if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue; return key; }; while (match = this.nestingRegexp.exec(str)) { let formatters = []; clonedOptions = { ...options }; clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions; clonedOptions.applyPostProcessor = false; delete clonedOptions.defaultValue; const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator); if (keyEndIndex !== -1) { formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean); match[1] = match[1].slice(0, keyEndIndex); } value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions); if (value && match[0] === str && !isString(value)) return value; if (!isString(value)) value = makeString(value); if (!value) { this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`); value = ''; } if (formatters.length) { value = formatters.reduce((v, f) => this.format(v, f, options.lng, { ...options, interpolationkey: match[1].trim() }), value.trim()); } str = str.replace(match[0], value); this.regexp.lastIndex = 0; } return str; } } const parseFormatStr = formatStr => { let formatName = formatStr.toLowerCase().trim(); const formatOptions = {}; if (formatStr.indexOf('(') > -1) { const p = formatStr.split('('); formatName = p[0].toLowerCase().trim(); const optStr = p[1].substring(0, p[1].length - 1); if (formatName === 'currency' && optStr.indexOf(':') < 0) { if (!formatOptions.currency) formatOptions.currency = optStr.trim(); } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) { if (!formatOptions.range) formatOptions.range = optStr.trim(); } else { const opts = optStr.split(';'); opts.forEach(opt => { if (opt) { const [key, ...rest] = opt.split(':'); const val = rest.join(':').trim().replace(/^'+|'+$/g, ''); const trimmedKey = key.trim(); if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val; if (val === 'false') formatOptions[trimmedKey] = false; if (val === 'true') formatOptions[trimmedKey] = true; if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10); } }); } } return { formatName, formatOptions }; }; const createCachedFormatter = fn => { const cache = {}; return (v, l, o) => { let optForCache = o; if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) { optForCache = { ...optForCache, [o.interpolationkey]: undefined }; } const key = l + JSON.stringify(optForCache); let frm = cache[key]; if (!frm) { frm = fn(getCleanedCode(l), o); cache[key] = frm; } return frm(v); }; }; const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v); class Formatter { constructor(options = {}) { this.logger = baseLogger.create('formatter'); this.options = options; this.init(options); } init(services, options = { interpolation: {} }) { this.formatSeparator = options.interpolation.formatSeparator || ','; const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter; this.formats = { number: cf((lng, opt) => { const formatter = new Intl.NumberFormat(lng, { ...opt }); return val => formatter.format(val); }), currency: cf((lng, opt) => { const formatter = new Intl.NumberFormat(lng, { ...opt, style: 'currency' }); return val => formatter.format(val); }), datetime: cf((lng, opt) => { const formatter = new Intl.DateTimeFormat(lng, { ...opt }); return val => formatter.format(val); }), relativetime: cf((lng, opt) => { const formatter = new Intl.RelativeTimeFormat(lng, { ...opt }); return val => formatter.format(val, opt.range || 'day'); }), list: cf((lng, opt) => { const formatter = new Intl.ListFormat(lng, { ...opt }); return val => formatter.format(val); }) }; } add(name, fc) { this.formats[name.toLowerCase().trim()] = fc; } addCached(name, fc) { this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc); } format(value, format, lng, options = {}) { const formats = format.split(this.formatSeparator); if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) { const lastIndex = formats.findIndex(f => f.indexOf(')') > -1); formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator); } const result = formats.reduce((mem, f) => { const { formatName, formatOptions } = parseFormatStr(f); if (this.formats[formatName]) { let formatted = mem; try { const valOptions = options?.formatParams?.[options.interpolationkey] || {}; const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng; formatted = this.formats[formatName](mem, l, { ...formatOptions, ...options, ...valOptions }); } catch (error) { this.logger.warn(error); } return formatted; } else { this.logger.warn(`there was no format function for ${formatName}`); } return mem; }, value); return result; } } const removePending = (q, name) => { if (q.pending[name] !== undefined) { delete q.pending[name]; q.pendingCount--; } }; class Connector extends EventEmitter { constructor(backend, store, services, options = {}) { super(); this.backend = backend; this.store = store; this.services = services; this.languageUtils = services.languageUtils; this.options = options; this.logger = baseLogger.create('backendConnector'); this.waitingReads = []; this.maxParallelReads = options.maxParallelReads || 10; this.readingCalls = 0; this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5; this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350; this.state = {}; this.queue = []; this.backend?.init?.(services, options.backend, options); } queueLoad(languages, namespaces, options, callback) { const toLoad = {}; const pending = {}; const toLoadLanguages = {}; const toLoadNamespaces = {}; languages.forEach(lng => { let hasAllNamespaces = true; namespaces.forEach(ns => { const name = `${lng}|${ns}`; if (!options.reload && this.store.hasResourceBundle(lng, ns)) { this.state[name] = 2; } else if (this.state[name] < 0) ; else if (this.state[name] === 1) { if (pending[name] === undefined) pending[name] = true; } else { this.state[name] = 1; hasAllNamespaces = false; if (pending[name] === undefined) pending[name] = true; if (toLoad[name] === undefined) toLoad[name] = true; if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true; } }); if (!hasAllNamespaces) toLoadLanguages[lng] = true; }); if (Object.keys(toLoad).length || Object.keys(pending).length) { this.queue.push({ pending, pendingCount: Object.keys(pending).length, loaded: {}, errors: [], callback }); } return { toLoad: Object.keys(toLoad), pending: Object.keys(pending), toLoadLanguages: Object.keys(toLoadLanguages), toLoadNamespaces: Object.keys(toLoadNamespaces) }; } loaded(name, err, data) { const s = name.split('|'); const lng = s[0]; const ns = s[1]; if (err) this.emit('failedLoading', lng, ns, err); if (!err && data) { this.store.addResourceBundle(lng, ns, data, undefined, undefined, { skipCopy: true }); } this.state[name] = err ? -1 : 2; if (err && data) this.state[name] = 0; const loaded = {}; this.queue.forEach(q => { pushPath(q.loaded, [lng], ns); removePending(q, name); if (err) q.errors.push(err); if (q.pendingCount === 0 && !q.done) { Object.keys(q.loaded).forEach(l => { if (!loaded[l]) loaded[l] = {}; const loadedKeys = q.loaded[l]; if (loadedKeys.length) { loadedKeys.forEach(n => { if (loaded[l][n] === undefined) loaded[l][n] = true; }); } }); q.done = true; if (q.errors.length) { q.callback(q.errors); } else { q.callback(); } } }); this.emit('loaded', loaded); this.queue = this.queue.filter(q => !q.done); } read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) { if (!lng.length) return callback(null, {}); if (this.readingCalls >= this.maxParallelReads) { this.waitingReads.push({ lng, ns, fcName, tried, wait, callback }); return; } this.readingCalls++; const resolver = (err, data) => { this.readingCalls--; if (this.waitingReads.length > 0) { const next = this.waitingReads.shift(); this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback); } if (err && data && tried < this.maxRetries) { setTimeout(() => { this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback); }, wait); return; } callback(err, data); }; const fc = this.backend[fcName].bind(this.backend); if (fc.length === 2) { try { const r = fc(lng, ns); if (r && typeof r.then === 'function') { r.then(data => resolver(null, data)).catch(resolver); } else { resolver(null, r); } } catch (err) { resolver(err); } return; } return fc(lng, ns, resolver); } prepareLoading(languages, namespaces, options = {}, callback) { if (!this.backend) { this.logger.warn('No backend was added via i18next.use. Will not load resources.'); return callback && callback(); } if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages); if (isString(namespaces)) namespaces = [namespaces]; const toLoad = this.queueLoad(languages, namespaces, options, callback); if (!toLoad.toLoad.length) { if (!toLoad.pending.length) callback(); return null; } toLoad.toLoad.forEach(name => { this.loadOne(name); }); } load(languages, namespaces, callback) { this.prepareLoading(languages, namespaces, {}, callback); } reload(languages, namespaces, callback) { this.prepareLoading(languages, namespaces, { reload: true }, callback); } loadOne(name, prefix = '') { const s = name.split('|'); const lng = s[0]; const ns = s[1]; this.read(lng, ns, 'read', undefined, undefined, (err, data) => { if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err); if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data); this.loaded(name, err, data); }); } saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) { if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) { this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!'); return; } if (key === undefined || key === null || key === '') return; if (this.backend?.create) { const opts = { ...options, isUpdate }; const fc = this.backend.create.bind(this.backend); if (fc.length < 6) { try { let r; if (fc.length === 5) { r = fc(languages, namespace, key, fallbackValue, opts); } else { r = fc(languages, namespace, key, fallbackValue); } if (r && typeof r.then === 'function') { r.then(data => clb(null, data)).catch(clb); } else { clb(null, r); } } catch (err) { clb(err); } } else { fc(languages, namespace, key, fallbackValue, clb, opts); } } if (!languages || !languages[0]) return; this.store.addResource(languages[0], namespace, key, fallbackValue); } } const get = () => ({ debug: false, initAsync: true, ns: ['translation'], defaultNS: ['translation'], fallbackLng: ['dev'], fallbackNS: false, supportedLngs: false, nonExplicitSupportedLngs: false, load: 'all', preload: false, simplifyPluralSuffix: true, keySeparator: '.', nsSeparator: ':', pluralSeparator: '_', contextSeparator: '_', partialBundledLanguages: false, saveMissing: false, updateMissing: false, saveMissingTo: 'fallback', saveMissingPlurals: true, missingKeyHandler: false, missingInterpolationHandler: false, postProcess: false, postProcessPassResolved: false, returnNull: false, returnEmptyString: true, returnObjects: false, joinArrays: false, returnedObjectHandler: false, parseMissingKeyHandler: false, appendNamespaceToMissingKey: false, appendNamespaceToCIMode: false, overloadTranslationOptionHandler: args => { let ret = {}; if (typeof args[1] === 'object') ret = args[1]; if (isString(args[1])) ret.defaultValue = args[1]; if (isString(args[2])) ret.tDescription = args[2]; if (typeof args[2] === 'object' || typeof args[3] === 'object') { const options = args[3] || args[2]; Object.keys(options).forEach(key => { ret[key] = options[key]; }); } return ret; }, interpolation: { escapeValue: true, format: value => value, prefix: '{{', suffix: '}}', formatSeparator: ',', unescapePrefix: '-', nestingPrefix: '$t(', nestingSuffix: ')', nestingOptionsSeparator: ',', maxReplaces: 1000, skipOnVariables: true }, cacheInBuiltFormats: true }); const transformOptions = options => { if (isString(options.ns)) options.ns = [options.ns]; if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng]; if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS]; if (options.supportedLngs?.indexOf?.('cimode') < 0) { options.supportedLngs = options.supportedLngs.concat(['cimode']); } if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate; return options; }; const noop = () => {}; const bindMemberFunctions = inst => { const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst)); mems.forEach(mem => { if (typeof inst[mem] === 'function') { inst[mem] = inst[mem].bind(inst); } }); }; class I18n extends EventEmitter { constructor(options = {}, callback) { super(); this.options = transformOptions(options); this.services = {}; this.logger = baseLogger; this.modules = { external: [] }; bindMemberFunctions(this); if (callback && !this.isInitialized && !options.isClone) { if (!this.options.initAsync) { this.init(options, callback); return this; } setTimeout(() => { this.init(options, callback); }, 0); } } init(options = {}, callback) { this.isInitializing = true; if (typeof options === 'function') { callback = options; options = {}; } if (options.defaultNS == null && options.ns) { if (isString(options.ns)) { options.defaultNS = options.ns; } else if (options.ns.indexOf('translation') < 0) { options.defaultNS = options.ns[0]; } } const defOpts = get(); this.options = { ...defOpts, ...this.options, ...transformOptions(options) }; this.options.interpolation = { ...defOpts.interpolation, ...this.options.interpolation }; if (options.keySeparator !== undefined) { this.options.userDefinedKeySeparator = options.keySeparator; } if (options.nsSeparator !== undefined) { this.options.userDefinedNsSeparator = options.nsSeparator; } const createClassOnDemand = ClassOrObject => { if (!ClassOrObject) return null; if (typeof ClassOrObject === 'function') return new ClassOrObject(); return ClassOrObject; }; if (!this.options.isClone) { if (this.modules.logger) { baseLogger.init(createClassOnDemand(this.modules.logger), this.options); } else { baseLogger.init(null, this.options); } let formatter; if (this.modules.formatter) { formatter = this.modules.formatter; } else { formatter = Formatter; } const lu = new LanguageUtil(this.options); this.store = new ResourceStore(this.options.resources, this.options); const s = this.services; s.logger = baseLogger; s.resourceStore = this.store; s.languageUtils = lu; s.pluralResolver = new PluralResolver(lu, { prepend: this.options.pluralSeparator, simplifyPluralSuffix: this.options.simplifyPluralSuffix }); const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format; if (usingLegacyFormatFunction) { this.logger.warn(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`); } if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) { s.formatter = createClassOnDemand(formatter); if (s.formatter.init) s.formatter.init(s, this.options); this.options.interpolation.format = s.formatter.format.bind(s.formatter); } s.interpolator = new Interpolator(this.options); s.utils = { hasLoadedNamespace: this.hasLoadedNamespace.bind(this) }; s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options); s.backendConnector.on('*', (event, ...args) => { this.emit(event, ...args); }); if (this.modules.languageDetector) { s.languageDetector = createClassOnDemand(this.modules.languageDetector); if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options); } if (this.modules.i18nFormat) { s.i18nFormat = createClassOnDemand(this.modules.i18nFormat); if (s.i18nFormat.init) s.i18nFormat.init(this); } this.translator = new Translator(this.services, this.options); this.translator.on('*', (event, ...args) => { this.emit(event, ...args); }); this.modules.external.forEach(m => { if (m.init) m.init(this); }); } this.format = this.options.interpolation.format; if (!callback) callback = noop; if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) { const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0]; } if (!this.services.languageDetector && !this.options.lng) { this.logger.warn('init: no languageDetector is used and no lng is defined'); } const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage']; storeApi.forEach(fcName => { this[fcName] = (...args) => this.store[fcName](...args); }); const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle']; storeApiChained.forEach(fcName => { this[fcName] = (...args) => { this.store[fcName](...args); return this; }; }); const deferred = defer(); const load = () => { const finish = (err, t) => { this.isInitializing = false; if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!'); this.isInitialized = true; if (!this.options.isClone) this.logger.log('initialized', this.options); this.emit('initialized', this.options); deferred.resolve(t); callback(err, t); }; if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this)); this.changeLanguage(this.options.lng, finish); }; if (this.options.resources || !this.options.initAsync) { load(); } else { setTimeout(load, 0); } return deferred; } loadResources(language, callback = noop) { let usedCallback = callback; const usedLng = isString(language) ? language : this.language; if (typeof language === 'function') usedCallback = language; if (!this.options.resources || this.options.partialBundledLanguages) { if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback(); const toLoad = []; const append = lng => { if (!lng) return; if (lng === 'cimode') return; const lngs = this.services.languageUtils.toResolveHierarchy(lng); lngs.forEach(l => { if (l === 'cimode') return; if (toLoad.indexOf(l) < 0) toLoad.push(l); }); }; if (!usedLng) { const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); fallbacks.forEach(l => append(l)); } else { append(usedLng); } this.options.preload?.forEach?.(l => append(l)); this.services.backendConnector.load(toLoad, this.options.ns, e => { if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language); usedCallback(e); }); } else { usedCallback(null); } } reloadResources(lngs, ns, callback) { const deferred = defer(); if (typeof lngs === 'function') { callback = lngs; lngs = undefined; } if (typeof ns === 'function') { callback = ns; ns = undefined; } if (!lngs) lngs = this.languages; if (!ns) ns = this.options.ns; if (!callback) callback = noop; this.services.backendConnector.reload(lngs, ns, err => { deferred.resolve(); callback(err); }); return deferred; } use(module) { if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()'); if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()'); if (module.type === 'backend') { this.modules.backend = module; } if (module.type === 'logger' || module.log && module.warn && module.error) { this.modules.logger = module; } if (module.type === 'languageDetector') { this.modules.languageDetector = module; } if (module.type === 'i18nFormat') { this.modules.i18nFormat = module; } if (module.type === 'postProcessor') { postProcessor.addPostProcessor(module); } if (module.type === 'formatter') { this.modules.formatter = module; } if (module.type === '3rdParty') { this.modules.external.push(module); } return this; } setResolvedLanguage(l) { if (!l || !this.languages) return; if (['cimode', 'dev'].indexOf(l) > -1) return; for (let li = 0; li < this.languages.length; li++) { const lngInLngs = this.languages[li]; if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue; if (this.store.hasLanguageSomeTranslations(lngInLngs)) { this.resolvedLanguage = lngInLngs; break; } } if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) { this.resolvedLanguage = l; this.languages.unshift(l); } } changeLanguage(lng, callback) { this.isLanguageChangingTo = lng; const deferred = defer(); this.emit('languageChanging', lng); const setLngProps = l => { this.language = l; this.languages = this.services.languageUtils.toResolveHierarchy(l); this.resolvedLanguage = undefined; this.setResolvedLanguage(l); }; const done = (err, l) => { if (l) { if (this.isLanguageChangingTo === lng) { setLngProps(l); this.translator.changeLanguage(l); this.isLanguageChangingTo = undefined; this.emit('languageChanged', l); this.logger.log('languageChanged', l); } } else { this.isLanguageChangingTo = undefined; } deferred.resolve((...args) => this.t(...args)); if (callback) callback(err, (...args) => this.t(...args)); }; const setLng = lngs => { if (!lng && !lngs && this.services.languageDetector) lngs = []; const fl = isString(lngs) ? lngs : lngs && lngs[0]; const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs); if (l) { if (!this.language) { setLngProps(l); } if (!this.translator.language) this.translator.changeLanguage(l); this.services.languageDetector?.cacheUserLanguage?.(l); } this.loadResources(l, err => { done(err, l); }); }; if (!lng && this.services.languageDetector && !this.services.languageDetector.async) { setLng(this.services.languageDetector.detect()); } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) { if (this.services.languageDetector.detect.length === 0) { this.services.languageDetector.detect().then(setLng); } else { this.services.languageDetector.detect(setLng); } } else { setLng(lng); } return deferred; } getFixedT(lng, ns, keyPrefix) { const fixedT = (key, opts, ...rest) => { let o; if (typeof opts !== 'object') { o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest)); } else { o = { ...opts }; } o.lng = o.lng || fixedT.lng; o.lngs = o.lngs || fixedT.lngs; o.ns = o.ns || fixedT.ns; if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix; const keySeparator = this.options.keySeparator || '.'; let resultKey; if (o.keyPrefix && Array.isArray(key)) { resultKey = key.map(k => `${o.keyPrefix}${keySeparator}${k}`); } else { resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key; } return this.t(resultKey, o); }; if (isString(lng)) { fixedT.lng = lng; } else { fixedT.lngs = lng; } fixedT.ns = ns; fixedT.keyPrefix = keyPrefix; return fixedT; } t(...args) { return this.translator?.translate(...args); } exists(...args) { return this.translator?.exists(...args); } setDefaultNamespace(ns) { this.options.defaultNS = ns; } hasLoadedNamespace(ns, options = {}) { if (!this.isInitialized) { this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages); return false; } if (!this.languages || !this.languages.length) { this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages); return false; } const lng = options.lng || this.resolvedLanguage || this.languages[0]; const fallbackLng = this.options ? this.options.fallbackLng : false; const lastLng = this.languages[this.languages.length - 1]; if (lng.toLowerCase() === 'cimode') return true; const loadNotPending = (l, n) => { const loadState = this.services.backendConnector.state[`${l}|${n}`]; return loadState === -1 || loadState === 0 || loadState === 2; }; if (options.precheck) { const preResult = options.precheck(this, loadNotPending); if (preResult !== undefined) return preResult; } if (this.hasResourceBundle(lng, ns)) return true; if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true; if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; return false; } loadNamespaces(ns, callback) { const deferred = defer(); if (!this.options.ns) { if (callback) callback(); return Promise.resolve(); } if (isString(ns)) ns = [ns]; ns.forEach(n => { if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n); }); this.loadResources(err => { deferred.resolve(); if (callback) callback(err); }); return deferred; } loadLanguages(lngs, callback) { const deferred = defer(); if (isString(lngs)) lngs = [lngs]; const preloaded = this.options.preload || []; const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng)); if (!newLngs.length) { if (callback) callback(); return Promise.resolve(); } this.options.preload = preloaded.concat(newLngs); this.loadResources(err => { deferred.resolve(); if (callback) callback(err); }); return deferred; } dir(lng) { if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language); if (!lng) return 'rtl'; try { const l = new Intl.Locale(lng); if (l && l.getTextInfo) { const ti = l.getTextInfo(); if (ti && ti.direction) return ti.direction; } } catch (e) {} const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb']; const languageUtils = this.services?.languageUtils || new LanguageUtil(get()); if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr'; return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr'; } static createInstance(options = {}, callback) { return new I18n(options, callback); } cloneInstance(options = {}, callback = noop) { const forkResourceStore = options.forkResourceStore; if (forkResourceStore) delete options.forkResourceStore; const mergedOptions = { ...this.options, ...options, ...{ isClone: true } }; const clone = new I18n(mergedOptions); if (options.debug !== undefined || options.prefix !== undefined) { clone.logger = clone.logger.clone(options); } const membersToCopy = ['store', 'services', 'language']; membersToCopy.forEach(m => { clone[m] = this[m]; }); clone.services = { ...this.services }; clone.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) }; if (forkResourceStore) { const clonedData = Object.keys(this.store.data).reduce((prev, l) => { prev[l] = { ...this.store.data[l] }; prev[l] = Object.keys(prev[l]).reduce((acc, n) => { acc[n] = { ...prev[l][n] }; return acc; }, prev[l]); return prev; }, {}); clone.store = new ResourceStore(clonedData, mergedOptions); clone.services.resourceStore = clone.store; } clone.translator = new Translator(clone.services, mergedOptions); clone.translator.on('*', (event, ...args) => { clone.emit(event, ...args); }); clone.init(mergedOptions, callback); clone.translator.options = mergedOptions; clone.translator.backendConnector.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) }; return clone; } toJSON() { return { options: this.options, store: this.store, language: this.language, languages: this.languages, resolvedLanguage: this.resolvedLanguage }; } } const instance = I18n.createInstance(); instance.createInstance = I18n.createInstance; instance.createInstance; instance.dir; instance.init; instance.loadResources; instance.reloadResources; instance.use; instance.changeLanguage; instance.getFixedT; instance.t; instance.exists; instance.setDefaultNamespace; instance.hasLoadedNamespace; instance.loadNamespaces; instance.loadLanguages; var scriptName$4 = "WME Switzerland Helper"; var layers$3 = { boundaries: { municipality: "Municipal boundaries", state: "Cantonal boundaries" }, "3d": "Geographical Names swissNAMES3D", topo: { national_colors: "National Maps (color)" }, background: { swissimage: "SWISSIMAGE Background" }, public_transport_stops: "Public Transport Stops" }; var introduction$3 = "This script adds map layers that can be enabled via the right navigation bar at the very bottom."; var readmeLink$3 = "For more information, see the full documentation."; var note$3 = { layers: { background: { swissimage: "Notes" } } }; var swissimageUpdateText$3 = "This map shows when the {{layer}} map was updated for each region."; var publicTransportStopsNote$3 = "Public transport stops appear as orange circular icons on the map. Click on them to create or update venues. Stops already mapped by a venue with the same name within a 75-meter radius are hidden, so only the ones still needing work are shown."; var streetCheck$3 = { appName: "Street names", tabNote: "Compares Waze street names against the official Swiss register and flags mismatches, with one-click fixes. Open the dedicated Street names tab to review the issues.", editPanelHostTitle: "Switzerland", stateIdle: "Idle", stateDisabled: "Script disabled", stateOutsideCh: "Outside Switzerland", toggleEnabled: "Enabled", toggleEnabledTitle: "Master switch: off disables scanning, the map layer and the edit-panel box", toggleAutoScan: "Auto scan", toggleAutoScanTitle: "Scan automatically when the map moves; off = use the Rescan button", stateZoomGated: "Zoom in to scan", stateAreaGated: "View too large to scan", stateSweeping: "Scanning area… {{done}}/{{total}} tiles", scanArea: "Scan this area", scanAreaTitle: "Fetch the official register for the whole view, tile by tile. May take a minute or two.", cancelSweep: "Cancel", sweepTooLarge: "View too large to scan, even area by area", warnTruncated: "{{n}} dense area(s) truncated by the register API, some official names may be missing (possible false \"not found\")", warnFailedTiles: "{{n}} area(s) failed to load, affected segments were not checked", warnContinuationCap: "lookup budget reached, some \"not found\" may clear on the next scan", stateFetching: "Fetching official register…", stateEvaluating: "Comparing names…", statePaused: "Paused (layer unchecked)", stateError: "Scan failed", updating: "Updating…", stateDone: "{{issues}} issue(s) · {{ok}} OK · {{streets}} official streets", unsavedBadge: "{{n}} unsaved", rescan: "Rescan", rescanTitle: "Clear the cache and fetch the official register again", nextIssue: "Next issue", nextIssueTitle: "Select the next mismatching segment", locateTitle: "Center the map on the segment", zoomToGroupTitle: "Zoom the map to all segments of this group", geoAdminLinkTitle: "Open this spot on map.geo.admin.ch (official register layer)", cantonMapLinkTitle: "Open this spot on the {{canton}} cantonal map", filterChipTitle: "Filter the list by this status", unnamed: "(unnamed)", noteUnofficial: "unofficial", notePlanned: "planned", noteFullLabel: "full label: {{label}}", noteExistsIn: "exists in: {{place}}", noteOwnDistance: "its official axis is ~{{m}} m away", noteLock: "L{{current}} → expected L{{expected}}", fixAll: "Fix all ({{n}})", fix: "Fix", fixTitle: "Apply \"{{name}}\"", fixLockTitle: "Set lock to L{{n}}", ignore: "Ignore", ignoreTitle: "Hide this finding (false positive) — stored locally on this device", ignoredCount: "{{n}} ignored", resetIgnored: "Reset", confirmOverLockFix: "This segment is locked above the Swiss minimum (often intentional). Lower the lock to L{{n}}?", fixFailed: "Fix failed: {{error}}", fixStopped: "Fixed {{done}}/{{total}}, then stopped: {{error}} (segment {{id}})", allMatch: "All street names match ✓", labelCOSMETIC: "Typography", labelVARIANT: "Spelling", labelNEAR: "Likely typo", labelWRONG_TYPE: "Road type", labelBILINGUAL: "Bilingual", labelWRONG_STREET: "Other street", labelWRONG_CITY: "Other locality", labelNOT_FOUND: "Not found", labelUNNAMED: "Unnamed", labelUNNAMED_NO_MATCH: "Unnamed, no match", labelUNDER_LOCK: "Lock too low", labelOVER_LOCK: "Lock too high", labelMICRO_SEGMENT: "Micro-segment", labelLOOP: "Loop", labelNARROW_MISUSE: "Narrow street", legendTitle: "Legend", legendCOSMETIC: "typography only (case, apostrophe, spacing), dashed line", legendVARIANT: "abbreviation, missing accent or article; official spelling suggested", legendNEAR: "probable typo; one close official name found", legendWRONG_TYPE: "different or missing way type (Chemin ↔ Route, X → Rue X); unique official name suggested", legendBILINGUAL: "bilingual street: primary should be one language, the other as an alternate", legendWRONG_STREET: "valid name, but the official street underneath has another name", geometryMatching: "Geometry matching (official street under the segment)", geometryMatchingTitle: "Enables UNNAMED suggestions, wrong-street detection and disambiguation by distance", viewportOnly: "Show only segments visible on the map", viewportOnlyTitle: "Filters the list and counters to the area currently on screen (no rescan)", editableOnly: "Only segments I can edit", editableOnlyTitle: "Hide segments locked above my editor rank", legendWRONG_CITY: "name exists, but in another locality (city scoping)", legendNOT_FOUND: "not found in the official register", legendUNNAMED: "checked road type without a name; the official street underneath is suggested when found, dashed line", legendUNNAMED_NO_MATCH: "unnamed and no official street found underneath (geometry matching) — usually legitimate", legendMICRO_SEGMENT: "drivable segment shorter than 5 m (Swiss guideline; roundabouts excluded)", legendLOOP: "loop made of fewer than 3 segments (same endpoints); split it", legendNARROW_MISUSE: "Narrow Street misuse: one-way or shorter than 50 m", legendUNDER_LOCK: "lock level below the Swiss minimum for its road type (roundabouts: at least L3)", legendOVER_LOCK: "lock rank above the Swiss minimum (often intentional)", guidelineChecks: "Swiss guideline checks (micro-segments, loops, narrow streets)", guidelineChecksTitle: "Checks from the Suisse romande editing guidelines that need no external data", helperOk: "matches the official register", helperSetting: "Issue box in the segment edit panel", settingsTitle: "Settings", settingsAndHelp: "Settings and help", roadTypesLabel: "Checked road types:", statusesLabel: "Checked issue types:", optionsLabel: "Options", scopeDisplayLabel: "Scope & display", altOk: "Alternate name match counts as OK", altOkTitle: "Useful in bilingual communes where the second language is an alternate name", showMapLabels: "Show expected name on the map (zoom ≥ 17)", keepOldName: "Keep old name as alternate when fixing", keepOldNameTitle: "Never applied to typo (NEAR) fixes", scopingLabel: "City scoping:", scopingTitle: "Compare the segment's city with the official locality (zip_label)", scopingOff: "off", scopingWarn: "warn", scopingStrict: "strict", minZoomLabel: "Min zoom to scan:", languageLabel: "Language:", languageAuto: "Auto (WME)", shortcutNextIssue: "Street names: select the next issue", shortcutFixSelected: "Street names: fix the selected segment", errNotFixable: "Not fixable", errEditingNotAllowed: "Editing is not allowed here", errSegmentUnloaded: "Segment no longer loaded", errNoCity: "Segment has no city; set the city first", errStreetCreate: "Could not find or create the street record", errLockAboveRank: "Lock L{{expected}} is above your editor level (L{{user}})", ignoreAll: "Ignore all ({{n}})", confirmIgnoreAll: "Ignore all {{n}} findings in this group? They are hidden locally and can be restored from the settings (Reset).", dialogConfirm: "Confirm", dialogCancel: "Cancel", dialogOk: "OK", detach: "Detach", detachTitle: "Move the panel into a floating window that stays visible when WME switches to the Selection tab", dock: "Dock", dockTitle: "Put the panel back into the sidebar tab", shortcutToggleWindow: "Toggle the floating window", noteMatchConfidence: "match {{pct}}% of the segment, {{m}} m from its axis", noteRunnerUp: "next candidate {{m}} m behind", confirmWrongStreetFix: "This segment is named \"{{current}}\" but another official street runs underneath.\nRename it to \"{{suggestion}}\"?\nThis verdict comes from geometry, so check it on the map first.", confirmGroupFixDetailed: "Rename {{n}} segments from \"{{current}}\" to \"{{suggestion}}\"?\nNothing is saved automatically; review and save in WME.", errGroupFixRank: "Fixing a whole group needs editor level {{level}} or above. Fix the segments one by one.", tabTitle: "Street names" }; var reloadStops$3 = "Refresh public transport stops"; var deleteObsoleteStop$3 = { message: "The venue \"{{name}}\" has no matching SBB stop. Do you want to delete it?", confirm: "Delete", cancel: "Cancel" }; var venueMatchDialog$3 = { cancel: "Cancel", selectMessage: "Multiple matching stops found. Choose which one to merge with:", merge: "Merge", mergeWithCoords: "Merge and update coordinates", saveNew: "Save new", message: "It seems {{venueCount}} stop(s) with this name already exist.
We have selected them for you.
What would you like to do?
Selecting
Merge
will apply the information to the existing stops without creating a new one." }; var hnImport$3 = { appName: "House numbers", layerName: "Swiss house numbers", tabNote: "Shows official Swiss address points from the federal building register (RegBL/GWR). Select a street, then click a green point to create its house number.", enable: "Enabled", enableTitle: "Enable the house-number importer", stateIdle: "Idle", stateFetching: "Loading address points ({{done}}/{{total}} tiles)", stateWaitingApi: "Waiting for geo.admin.ch", stateZoomGated: "Zoom in to load address points", stateAreaGated: "Area too large, zoom in", stateOutsideCh: "Outside Switzerland", stateCheckingExisting: "Checking existing numbers", stateError: "Error: {{message}}", hintSelectSegment: "Select the street segment first, so the number is attached to it and existing numbers can be checked.", selectedStreet: "Selected: {{name}}", countGwr: "Address points: {{count}}", countMissing: "missing {{count}}", countPresent: "already there {{count}}", countOtherStreet: "other street {{count}}", unsavedBadge: "{{count}} unsaved change(s)", btnImportMissing: "Import the {{count}} missing numbers", btnImportMissingCapped: "Import {{cap}} of the {{count}} missing numbers", btnRefreshExisting: "Refresh existing numbers", btnClearCache: "Clear the cache and reload", confirmMassImport: "Create {{count}} house numbers on {{street}}?\n\nNumbers: {{numbers}}\n\nThey go to your pending edits; nothing is saved. Ctrl+Z undoes them.", confirmMassImportCapped: "Create {{cap}} of the {{count}} missing house numbers on {{street}}?\n\nNumbers: {{numbers}}\n\nThe per-action limit is {{cap}}; run it again for the rest. They go to your pending edits; nothing is saved.", confirmSingleImport: "Create house number {{number}} on {{street}}?", importedCount: "{{count}} house number(s) created. Nothing is saved yet.", importStopped: "Stopped after {{done}} of {{total}}: {{message}}", errNotAllowed: "Editing is not allowed here.", errTooFar: "That address is {{distance}} m from the selected street; select the right segment.", errSegmentNotFound: "The segment is no longer loaded.", errInvalidState: "WME refused the edit.", errUnknown: "Unexpected error.", errNoSelection: "No street segment selected.", warnTruncated: "Too many addresses here to list them all; bulk import is off. Individual clicks still work.", warnIncomplete: "Part of this view could not be loaded; bulk import is off. Individual clicks still work.", legendMissing: "To import", legendPresent: "Already there", legendOtherStreet: "Other street", legendNeutral: "No street selected", tooltipPresentFar: "{{number}} exists, but {{distance}} m away", settingsTitle: "Settings", settingsAndHelp: "Settings and help", legendNote: "Statuses absent from the selection are not listed above.", settingsMinZoom: "Minimum zoom", settingsShowLabels: "Show numbers on the map", settingsStrictMatch: "Strict street-name matching", settingsExistingOnly: "Only buildings that are built", settingsConfirmSingle: "Confirm every single import", settingsLanguage: "Language", shortcutImportMissing: "Import the missing house numbers", shortcutToggleLayer: "Toggle the house-number layer", dialogConfirm: "Confirm", dialogCancel: "Cancel", dialogOk: "OK", legendTitle: "Legend", verdictOk: "Name matches the official register", verdictMismatch: "Name differs from the register: {{suggestion}}", confirmMassImportUnverifiedName: "Note: the street-name checker reports this street's name as differing from the official register. The numbers will be attached to it as it is named today.", confirmMassImportSegments: "The street is split into {{segments}} WME segments; each number is attached to the one it sits on.", confirmMassImportReview: "Once created, check the result on the map and move any number that did not land where it belongs.", tabTitle: "House numbers" }; var enCommon = { scriptName: scriptName$4, layers: layers$3, introduction: introduction$3, readmeLink: readmeLink$3, note: note$3, swissimageUpdateText: swissimageUpdateText$3, publicTransportStopsNote: publicTransportStopsNote$3, streetCheck: streetCheck$3, reloadStops: reloadStops$3, deleteObsoleteStop: deleteObsoleteStop$3, venueMatchDialog: venueMatchDialog$3, hnImport: hnImport$3 }; var enCommon$1 = /*#__PURE__*/Object.freeze({ __proto__: null, default: enCommon, deleteObsoleteStop: deleteObsoleteStop$3, hnImport: hnImport$3, introduction: introduction$3, layers: layers$3, note: note$3, publicTransportStopsNote: publicTransportStopsNote$3, readmeLink: readmeLink$3, reloadStops: reloadStops$3, scriptName: scriptName$4, streetCheck: streetCheck$3, swissimageUpdateText: swissimageUpdateText$3, venueMatchDialog: venueMatchDialog$3 }); var scriptName$3 = "WME Suisse Helper"; var layers$2 = { boundaries: { municipality: "Limites communales", state: "Limites cantonales" }, "3d": "Noms géographiques swissNAMES3D", topo: { national_colors: "Cartes nationales (couleur)" }, background: { swissimage: "Fond SWISSIMAGE" }, public_transport_stops: "Arrêts de transports publics" }; var introduction$2 = "Ce script ajoute des couches cartographiques qui peuvent être activées via la barre de navigation de droite tout en bas."; var readmeLink$2 = "Pour plus d'informations, consultez la documentation complète."; var note$2 = { layers: { background: { swissimage: "Notes" } } }; var swissimageUpdateText$2 = "Cette carte indique quand la couche {{layer}} a été mise à jour pour chaque région."; var publicTransportStopsNote$2 = "Les arrêts de transports publics apparaissent sous forme d'icônes circulaires orange sur la carte. Cliquez dessus pour créer ou mettre à jour des lieux. Les arrêts déjà cartographiés par un lieu de même nom dans un rayon de 75 mètres sont masqués ; seuls ceux nécessitant une action sont affichés."; var streetCheck$2 = { appName: "Nom des rues", tabNote: "Compare les noms de rues Waze au répertoire officiel suisse et signale les écarts, avec correction en 1 clic. Ouvre l'onglet dédié Nom des rues pour voir les écarts.", editPanelHostTitle: "Suisse", stateIdle: "En attente", stateDisabled: "Script désactivé", stateOutsideCh: "Hors de Suisse", toggleEnabled: "Actif", toggleEnabledTitle: "Interrupteur général: désactive le scan, la couche carte et l'encadré du panneau", toggleAutoScan: "Scan auto", toggleAutoScanTitle: "Scanner automatiquement au déplacement de la carte; sinon utiliser le bouton Rescanner", stateZoomGated: "Zoomez pour scanner", stateAreaGated: "Vue trop large pour scanner", stateSweeping: "Scan de la zone… {{done}}/{{total}} tuiles", scanArea: "Scanner cette zone", scanAreaTitle: "Récupère le répertoire officiel pour toute la vue, tuile par tuile. Peut prendre une à deux minutes.", cancelSweep: "Annuler", sweepTooLarge: "Vue trop large pour scanner, même zone par zone", warnTruncated: "{{n}} zone(s) dense(s) tronquée(s) par l'API du répertoire, des noms officiels peuvent manquer (faux « introuvable » possibles)", warnFailedTiles: "{{n}} zone(s) n'ont pas pu être chargées, les segments concernés n'ont pas été vérifiés", warnContinuationCap: "budget de recherche atteint, certains « introuvable » peuvent disparaître au prochain scan", stateFetching: "Lecture du répertoire officiel…", stateEvaluating: "Comparaison des noms…", statePaused: "En pause (couche décochée)", stateError: "Échec du scan", updating: "Mise à jour…", stateDone: "{{issues}} écart(s) · {{ok}} OK · {{streets}} rues officielles", unsavedBadge: "{{n}} non sauvegardé(s)", rescan: "Rescanner", rescanTitle: "Vider le cache et relire le répertoire officiel", nextIssue: "Écart suivant", nextIssueTitle: "Sélectionner le segment en écart suivant", locateTitle: "Centrer la carte sur le segment", zoomToGroupTitle: "Zoomer la carte sur tous les segments de ce groupe", geoAdminLinkTitle: "Ouvrir cet endroit sur map.geo.admin.ch (couche du répertoire officiel)", cantonMapLinkTitle: "Ouvrir cet endroit sur la carte cantonale ({{canton}})", filterChipTitle: "Filtrer la liste sur ce statut", unnamed: "(sans nom)", noteUnofficial: "non officiel", notePlanned: "planifié", noteFullLabel: "libellé complet: {{label}}", noteExistsIn: "existe à: {{place}}", noteOwnDistance: "son axe officiel à ~{{m}} m", noteLock: "L{{current}} → attendu L{{expected}}", fixAll: "Tout corriger ({{n}})", fix: "Corriger", fixTitle: "Appliquer «{{name}}»", fixLockTitle: "Régler le verrou sur L{{n}}", ignore: "Ignorer", ignoreTitle: "Masquer ce signalement (faux positif) — stocké localement sur cet appareil", ignoredCount: "{{n}} ignorés", resetIgnored: "Réinitialiser", confirmOverLockFix: "Ce segment est verrouillé au-dessus du minimum suisse (souvent volontaire). Abaisser le verrou à L{{n}} ?", fixFailed: "Échec de la correction: {{error}}", fixStopped: "{{done}}/{{total}} corrigés, puis arrêt: {{error}} (segment {{id}})", allMatch: "Tous les noms de rues correspondent ✓", labelCOSMETIC: "Typographie", labelVARIANT: "Orthographe", labelNEAR: "Faute probable", labelWRONG_TYPE: "Type de voie", labelBILINGUAL: "Bilingue", labelWRONG_STREET: "Autre rue", labelWRONG_CITY: "Autre localité", labelNOT_FOUND: "Introuvable", labelUNNAMED: "Sans nom", labelUNNAMED_NO_MATCH: "Sans nom, sans corr.", labelUNDER_LOCK: "Verrou trop bas", labelOVER_LOCK: "Verrou trop haut", labelMICRO_SEGMENT: "Micro-segment", labelLOOP: "Boucle", labelNARROW_MISUSE: "Rue étroite", legendTitle: "Légende", legendCOSMETIC: "typographie uniquement (casse, apostrophe, espaces), trait pointillé", legendVARIANT: "abréviation, accent ou article manquant; orthographe officielle proposée", legendNEAR: "faute de frappe probable; un seul nom officiel proche", legendWRONG_TYPE: "type de voie différent ou manquant (Chemin ↔ Route, X → Rue X); nom officiel unique proposé", legendBILINGUAL: "rue bilingue: le primaire doit être une seule langue, l'autre en alternatif", legendWRONG_STREET: "nom valide, mais la rue officielle dessous porte un autre nom", geometryMatching: "Matching géométrique (rue officielle sous le segment)", geometryMatchingTitle: "Active les suggestions UNNAMED, la détection de mauvaise rue et la désambiguïsation par distance", viewportOnly: "N'afficher que les segments visibles", viewportOnlyTitle: "Filtre la liste et les compteurs sur la zone actuellement à l'écran (sans relancer de scan)", editableOnly: "Seulement les segments modifiables", editableOnlyTitle: "Masquer les segments verrouillés au-dessus de mon niveau d'éditeur", legendWRONG_CITY: "le nom existe, mais dans une autre localité (scoping)", legendNOT_FOUND: "introuvable dans le répertoire officiel", legendUNNAMED: "type de route vérifié sans nom ; la rue officielle dessous est suggérée si trouvée, trait pointillé", legendUNNAMED_NO_MATCH: "sans nom et aucune rue officielle dessous (matching géométrique) — généralement normal", legendMICRO_SEGMENT: "segment carrossable de moins de 5 m (règle suisse; ronds-points exclus)", legendLOOP: "boucle de moins de 3 segments (nœuds identiques); à diviser", legendNARROW_MISUSE: "Rue étroite mal utilisée: sens unique ou moins de 50 m", legendUNDER_LOCK: "verrou plus bas que le minimum suisse pour ce type de route (ronds-points: au moins L3)", legendOVER_LOCK: "verrou plus haut que le minimum suisse (souvent volontaire)", guidelineChecks: "Contrôles des règles suisses (micro-segments, boucles, rues étroites)", guidelineChecksTitle: "Contrôles issus des règles d'édition de Suisse romande, sans donnée externe", helperOk: "correspond au répertoire officiel", helperSetting: "Encadré d'écart dans le panneau d'édition du segment", settingsTitle: "Réglages", settingsAndHelp: "Réglages et aide", roadTypesLabel: "Types de routes vérifiés:", statusesLabel: "Types d'erreurs vérifiés:", optionsLabel: "Options", scopeDisplayLabel: "Portée & affichage", altOk: "Nom alternatif correspondant = OK", altOkTitle: "Utile dans les communes bilingues où la seconde langue est en nom alternatif", showMapLabels: "Afficher le nom attendu sur la carte (zoom ≥ 17)", keepOldName: "Conserver l'ancien nom en alternatif lors de la correction", keepOldNameTitle: "Jamais appliqué aux corrections de fautes de frappe (NEAR)", scopingLabel: "Scoping par localité:", scopingTitle: "Compare la ville du segment à la localité officielle (zip_label)", scopingOff: "désactivé", scopingWarn: "avertir", scopingStrict: "strict", minZoomLabel: "Zoom minimal pour scanner:", languageLabel: "Langue:", languageAuto: "Auto (WME)", shortcutNextIssue: "Nom des rues: sélectionner l'écart suivant", shortcutFixSelected: "Nom des rues: corriger le segment sélectionné", errNotFixable: "Non corrigeable", errEditingNotAllowed: "Édition non autorisée ici", errSegmentUnloaded: "Segment plus chargé", errNoCity: "Segment sans ville; définissez d'abord la ville", errStreetCreate: "Impossible de trouver ou de créer la rue", errLockAboveRank: "Verrou L{{expected}} au-dessus de ton niveau d'éditeur (L{{user}})", ignoreAll: "Tout ignorer ({{n}})", confirmIgnoreAll: "Ignorer les {{n}} signalements de ce groupe ? Masqués localement, récupérables dans les réglages (Réinitialiser).", dialogConfirm: "Confirmer", dialogCancel: "Annuler", dialogOk: "OK", detach: "Détacher", detachTitle: "Déplacer le panneau dans une fenêtre flottante qui reste visible quand WME bascule sur l onglet Selection", dock: "Rattacher", dockTitle: "Remettre le panneau dans l onglet de la barre latérale", shortcutToggleWindow: "Basculer la fenêtre flottante", noteMatchConfidence: "correspond à {{pct}} % du segment, à {{m}} m de son axe", noteRunnerUp: "candidat suivant à {{m}} m derrière", confirmWrongStreetFix: "Ce segment s appelle « {{current}} » mais une autre rue officielle passe dessous.\nLe renommer en « {{suggestion}} » ?\nCe verdict vient de la géométrie, vérifie-le sur la carte avant.", confirmGroupFixDetailed: "Renommer {{n}} segments de « {{current}} » en « {{suggestion}} » ?\nRien n est enregistré automatiquement ; relis et enregistre dans WME.", errGroupFixRank: "La correction de groupe demande le niveau éditeur {{level}} ou plus. Corrige les segments un par un.", tabTitle: "Noms de rues" }; var reloadStops$2 = "Recharger les arrêts de transport public"; var deleteObsoleteStop$2 = { message: "Le lieu \"{{name}}\" n'a pas d'arrêt SBB correspondant. Voulez-vous le supprimer ?", confirm: "Supprimer", cancel: "Annuler" }; var venueMatchDialog$2 = { cancel: "Annuler", selectMessage: "Plusieurs arrêts correspondants trouvés. Choisissez celui avec lequel fusionner :", merge: "Fusionner", mergeWithCoords: "Fusionner et mettre à jour les coordonnées", saveNew: "Enregistrer le nouveau", message: "Il semble qu'il existe déjà {{venueCount}} arrêt(s) avec ce nom.
Nous les avons sélectionnés pour vous.
Que voulez-vous faire ?
Sélectionner
Fusionner
appliquera les informations aux anciens points sans créer le nouveau." }; var hnImport$2 = { appName: "Numéros de maison", layerName: "Numéros de maison suisses", tabNote: "Affiche les points d'adresse officiels du registre fédéral des bâtiments (RegBL/GWR). Sélectionnez une rue, puis cliquez sur un point vert pour créer son numéro.", enable: "Actif", enableTitle: "Activer l'importateur de numéros", stateIdle: "En attente", stateFetching: "Chargement des adresses ({{done}}/{{total}} tuiles)", stateWaitingApi: "En attente de geo.admin.ch", stateZoomGated: "Zoomez pour charger les adresses", stateAreaGated: "Zone trop grande, zoomez", stateOutsideCh: "Hors de Suisse", stateCheckingExisting: "Vérification des numéros existants", stateError: "Erreur : {{message}}", hintSelectSegment: "Sélectionnez d'abord le segment de rue, pour que le numéro y soit rattaché et que les numéros existants puissent être vérifiés.", selectedStreet: "Sélection : {{name}}", countGwr: "Points d'adresse : {{count}}", countMissing: "manquants {{count}}", countPresent: "déjà posés {{count}}", countOtherStreet: "autre rue {{count}}", unsavedBadge: "{{count}} modification(s) non enregistrée(s)", btnImportMissing: "Importer les {{count}} numéros manquants", btnImportMissingCapped: "Importer {{cap}} des {{count}} numéros manquants", btnRefreshExisting: "Rafraîchir les numéros existants", btnClearCache: "Vider le cache et recharger", confirmMassImport: "Créer {{count}} numéros de maison sur {{street}} ?\n\nNuméros : {{numbers}}\n\nIls rejoignent vos modifications en cours ; rien n'est enregistré. Ctrl+Z les annule.", confirmMassImportCapped: "Créer {{cap}} des {{count}} numéros manquants sur {{street}} ?\n\nNuméros : {{numbers}}\n\nLa limite par action est de {{cap}} ; relancez pour la suite. Ils rejoignent vos modifications en cours ; rien n'est enregistré.", confirmSingleImport: "Créer le numéro {{number}} sur {{street}} ?", importedCount: "{{count}} numéro(s) créé(s). Rien n'est encore enregistré.", importStopped: "Arrêt après {{done}} sur {{total}} : {{message}}", errNotAllowed: "L'édition n'est pas autorisée ici.", errTooFar: "Cette adresse est à {{distance}} m de la rue sélectionnée ; sélectionnez le bon segment.", errSegmentNotFound: "Le segment n'est plus chargé.", errInvalidState: "WME a refusé la modification.", errUnknown: "Erreur inattendue.", errNoSelection: "Aucun segment de rue sélectionné.", warnTruncated: "Trop d'adresses ici pour toutes les lister ; l'import en masse est désactivé. Les clics individuels fonctionnent toujours.", warnIncomplete: "Une partie de cette vue n'a pas pu être chargée ; l'import en masse est désactivé. Les clics individuels fonctionnent toujours.", legendMissing: "À importer", legendPresent: "Déjà posé", legendOtherStreet: "Autre rue", legendNeutral: "Aucune rue sélectionnée", tooltipPresentFar: "{{number}} existe, mais à {{distance}} m", settingsTitle: "Réglages", settingsAndHelp: "Réglages et aide", legendNote: "Les statuts absents de la sélection ne sont pas listés ci-dessus.", settingsMinZoom: "Zoom minimum", settingsShowLabels: "Afficher les numéros sur la carte", settingsStrictMatch: "Correspondance stricte des noms de rue", settingsExistingOnly: "Uniquement les bâtiments construits", settingsConfirmSingle: "Confirmer chaque import unitaire", settingsLanguage: "Langue", shortcutImportMissing: "Importer les numéros manquants", shortcutToggleLayer: "Activer/désactiver la couche des numéros", dialogConfirm: "Confirmer", dialogCancel: "Annuler", dialogOk: "OK", legendTitle: "Légende", verdictOk: "Nom conforme au registre officiel", verdictMismatch: "Nom différent du registre : {{suggestion}}", confirmMassImportUnverifiedName: "Note : le contrôleur de noms signale que le nom de cette rue diffère du registre officiel. Les numéros y seront rattachés tel qu'elle est nommée aujourd'hui.", confirmMassImportSegments: "La rue est découpée en {{segments}} segments WME ; chaque numéro est rattaché à celui devant lequel il se trouve.", confirmMassImportReview: "Une fois créés, vérifiez le résultat sur la carte et déplacez les numéros qui ne seraient pas au bon endroit.", tabTitle: "Numéros de maison" }; var frCommon = { scriptName: scriptName$3, layers: layers$2, introduction: introduction$2, readmeLink: readmeLink$2, note: note$2, swissimageUpdateText: swissimageUpdateText$2, publicTransportStopsNote: publicTransportStopsNote$2, streetCheck: streetCheck$2, reloadStops: reloadStops$2, deleteObsoleteStop: deleteObsoleteStop$2, venueMatchDialog: venueMatchDialog$2, hnImport: hnImport$2 }; var frCommon$1 = /*#__PURE__*/Object.freeze({ __proto__: null, default: frCommon, deleteObsoleteStop: deleteObsoleteStop$2, hnImport: hnImport$2, introduction: introduction$2, layers: layers$2, note: note$2, publicTransportStopsNote: publicTransportStopsNote$2, readmeLink: readmeLink$2, reloadStops: reloadStops$2, scriptName: scriptName$3, streetCheck: streetCheck$2, swissimageUpdateText: swissimageUpdateText$2, venueMatchDialog: venueMatchDialog$2 }); var scriptName$2 = "WME Svizzera Helper"; var layers$1 = { boundaries: { municipality: "Limiti comunali", state: "Frontiere cantonali" }, "3d": "Nomi geografici swissNAMES3D", topo: { national_colors: "Carte nazionali (colori)" }, background: { swissimage: "SWISSIMAGE Sfondo" }, public_transport_stops: "Fermate dei trasporti pubblici" }; var introduction$1 = "Questo script aggiunge livelli di mappa che possono essere attivati tramite la barra di navigazione a destra in basso."; var readmeLink$1 = "Per ulteriori informazioni, consultare la documentazione completa."; var note$1 = { layers: { background: { swissimage: "Note" } } }; var swissimageUpdateText$1 = "Questa mappa mostra quando il layer {{layer}} è stato aggiornato per ogni regione."; var publicTransportStopsNote$1 = "Le fermate dei trasporti pubblici appaiono come icone circolari arancioni sulla mappa. Cliccate su di esse per creare o aggiornare le location. Le fermate già mappate da una location con lo stesso nome entro un raggio di 75 metri vengono nascoste; vengono mostrate solo quelle che richiedono un intervento."; var streetCheck$1 = { appName: "Nomi delle strade", tabNote: "Confronta i nomi delle strade di Waze con il repertorio ufficiale svizzero e segnala le differenze, con correzione in 1 clic. Apri la scheda dedicata Nomi delle strade per esaminare le differenze.", editPanelHostTitle: "Svizzera", stateIdle: "In attesa", stateDisabled: "Script disattivato", stateOutsideCh: "Fuori dalla Svizzera", toggleEnabled: "Attivo", toggleEnabledTitle: "Interruttore generale: disattiva scansione, livello mappa e riquadro del pannello", toggleAutoScan: "Scansione auto", toggleAutoScanTitle: "Scansiona automaticamente al movimento della mappa; altrimenti usare Riscansiona", stateZoomGated: "Ingrandisci per scansionare", stateAreaGated: "Vista troppo ampia per la scansione", stateSweeping: "Scansione dell'area… {{done}}/{{total}} riquadri", scanArea: "Scansiona quest'area", scanAreaTitle: "Recupera il repertorio ufficiale per l'intera vista, riquadro per riquadro. Può richiedere uno o due minuti.", cancelSweep: "Annulla", sweepTooLarge: "Vista troppo ampia per la scansione, anche area per area", warnTruncated: "{{n}} riquadri densi troncati dall'API del repertorio, alcuni nomi ufficiali potrebbero mancare (possibili falsi \"non trovato\")", warnFailedTiles: "{{n}} riquadri non caricati, i segmenti interessati non sono stati verificati", warnContinuationCap: "budget di ricerca esaurito, alcuni \"non trovato\" potrebbero sparire alla prossima scansione", stateFetching: "Lettura del repertorio ufficiale…", stateEvaluating: "Confronto dei nomi…", statePaused: "In pausa (livello disattivato)", stateError: "Scansione fallita", updating: "Aggiornamento…", stateDone: "{{issues}} differenze · {{ok}} OK · {{streets}} strade ufficiali", unsavedBadge: "{{n}} non salvati", rescan: "Riscansiona", rescanTitle: "Svuota la cache e rilegge il repertorio ufficiale", nextIssue: "Prossima differenza", nextIssueTitle: "Seleziona il prossimo segmento con differenza", locateTitle: "Centra la mappa sul segmento", zoomToGroupTitle: "Zooma la mappa su tutti i segmenti di questo gruppo", geoAdminLinkTitle: "Apri questo punto su map.geo.admin.ch (livello del repertorio ufficiale)", cantonMapLinkTitle: "Apri questo punto sulla mappa cantonale ({{canton}})", filterChipTitle: "Filtra l'elenco per questo stato", unnamed: "(senza nome)", noteUnofficial: "non ufficiale", notePlanned: "pianificata", noteFullLabel: "denominazione completa: {{label}}", noteExistsIn: "esiste a: {{place}}", noteOwnDistance: "asse ufficiale a ~{{m}} m", noteLock: "L{{current}} → atteso L{{expected}}", fixAll: "Correggi tutti ({{n}})", fix: "Correggi", fixTitle: "Applica «{{name}}»", fixLockTitle: "Imposta blocco a L{{n}}", ignore: "Ignora", ignoreTitle: "Nascondi questa segnalazione (falso positivo) — salvata localmente su questo dispositivo", ignoredCount: "{{n}} ignorati", resetIgnored: "Reimposta", confirmOverLockFix: "Questo segmento è bloccato oltre il minimo svizzero (spesso intenzionale). Abbassare il blocco a L{{n}}?", fixFailed: "Correzione fallita: {{error}}", fixStopped: "{{done}}/{{total}} corretti, poi interrotto: {{error}} (segmento {{id}})", allMatch: "Tutti i nomi delle strade corrispondono ✓", labelCOSMETIC: "Tipografia", labelVARIANT: "Ortografia", labelNEAR: "Probabile refuso", labelWRONG_TYPE: "Tipo di strada", labelBILINGUAL: "Bilingue", labelWRONG_STREET: "Altra via", labelWRONG_CITY: "Altra località", labelNOT_FOUND: "Non trovata", labelUNNAMED: "Senza nome", labelUNNAMED_NO_MATCH: "Senza nome, no corr.", labelUNDER_LOCK: "Blocco troppo basso", labelOVER_LOCK: "Blocco troppo alto", labelMICRO_SEGMENT: "Micro-segmento", labelLOOP: "Anello", labelNARROW_MISUSE: "Via stretta", legendTitle: "Legenda", legendCOSMETIC: "solo tipografia (maiuscole, apostrofo, spazi), linea tratteggiata", legendVARIANT: "abbreviazione, accento o articolo mancante; proposta la grafia ufficiale", legendNEAR: "probabile errore di battitura; un solo nome ufficiale vicino", legendWRONG_TYPE: "tipo di via diverso o mancante (Chemin ↔ Route, X → Via X); proposto il nome ufficiale unico", legendBILINGUAL: "strada bilingue: il primario dev'essere una lingua, l'altra come alternativa", legendWRONG_STREET: "nome valido, ma la strada ufficiale sottostante ha un altro nome", geometryMatching: "Matching geometrico (strada ufficiale sotto il segmento)", geometryMatchingTitle: "Attiva i suggerimenti UNNAMED, il rilevamento di strada errata e la disambiguazione per distanza", viewportOnly: "Mostra solo i segmenti visibili sulla mappa", viewportOnlyTitle: "Filtra l'elenco e i contatori sull'area attualmente visibile (senza nuova scansione)", editableOnly: "Solo i segmenti modificabili", editableOnlyTitle: "Nascondi i segmenti bloccati oltre il mio livello di editor", legendWRONG_CITY: "il nome esiste, ma in un'altra località (scoping)", legendNOT_FOUND: "non presente nel repertorio ufficiale", legendUNNAMED: "tipo di strada verificato senza nome; la strada ufficiale sotto è suggerita se trovata, linea tratteggiata", legendUNNAMED_NO_MATCH: "senza nome e nessuna strada ufficiale sotto (matching geometrico) — di solito normale", legendMICRO_SEGMENT: "segmento percorribile più corto di 5 m (regola svizzera; rotatorie escluse)", legendLOOP: "anello con meno di 3 segmenti (stessi nodi); da dividere", legendNARROW_MISUSE: "Strada stretta usata male: senso unico o meno di 50 m", legendUNDER_LOCK: "livello di blocco sotto il minimo svizzero per questo tipo di strada (rotatorie: almeno L3)", legendOVER_LOCK: "livello di blocco sopra il minimo svizzero (spesso intenzionale)", guidelineChecks: "Controlli delle regole svizzere (micro-segmenti, anelli, strade strette)", guidelineChecksTitle: "Controlli dalle regole di editing della Svizzera romanda, senza dati esterni", helperOk: "corrisponde al repertorio ufficiale", helperSetting: "Riquadro differenze nel pannello di modifica del segmento", settingsTitle: "Impostazioni", settingsAndHelp: "Impostazioni e aiuto", roadTypesLabel: "Tipi di strada verificati:", statusesLabel: "Tipi di errore verificati:", optionsLabel: "Opzioni", scopeDisplayLabel: "Ambito e visualizzazione", altOk: "Nome alternativo corrispondente = OK", altOkTitle: "Utile nei comuni bilingui con la seconda lingua come nome alternativo", showMapLabels: "Mostra il nome atteso sulla mappa (zoom ≥ 17)", keepOldName: "Mantieni il vecchio nome come alternativo alla correzione", keepOldNameTitle: "Mai applicato alle correzioni di errori di battitura (NEAR)", scopingLabel: "Scoping per località:", scopingTitle: "Confronta la città del segmento con la località ufficiale (zip_label)", scopingOff: "disattivato", scopingWarn: "avvisa", scopingStrict: "rigoroso", minZoomLabel: "Zoom minimo per la scansione:", languageLabel: "Lingua:", languageAuto: "Auto (WME)", shortcutNextIssue: "Nomi delle strade: seleziona la prossima differenza", shortcutFixSelected: "Nomi delle strade: correggi il segmento selezionato", errNotFixable: "Non correggibile", errEditingNotAllowed: "La modifica non è consentita qui", errSegmentUnloaded: "Segmento non più caricato", errNoCity: "Segmento senza città; imposta prima la città", errStreetCreate: "Impossibile trovare o creare la strada", errLockAboveRank: "Blocco L{{expected}} oltre il tuo livello editor (L{{user}})", ignoreAll: "Ignora tutti ({{n}})", confirmIgnoreAll: "Ignorare tutte le {{n}} segnalazioni del gruppo? Nascoste localmente, ripristinabili dalle impostazioni (Reimposta).", dialogConfirm: "Conferma", dialogCancel: "Annulla", dialogOk: "OK", detach: "Stacca", detachTitle: "Sposta il pannello in una finestra mobile che resta visibile quando WME passa alla scheda Selection", dock: "Aggancia", dockTitle: "Rimetti il pannello nella scheda della barra laterale", shortcutToggleWindow: "Attiva o disattiva la finestra mobile", noteMatchConfidence: "copre il {{pct}} % del segmento, a {{m}} m dal suo asse", noteRunnerUp: "candidato successivo a {{m}} m di distanza", confirmWrongStreetFix: "Questo segmento si chiama « {{current}} » ma sotto passa un altra strada ufficiale.\nRinominarlo in « {{suggestion}} »?\nQuesto verdetto deriva dalla geometria, verificalo prima sulla mappa.", confirmGroupFixDetailed: "Rinominare {{n}} segmenti da « {{current}} » a « {{suggestion}} »?\nNulla viene salvato automaticamente; controlla e salva in WME.", errGroupFixRank: "La correzione di gruppo richiede il livello editor {{level}} o superiore. Correggi i segmenti uno per uno.", tabTitle: "Nomi delle vie" }; var reloadStops$1 = "Ricarica le fermate del trasporto pubblico"; var deleteObsoleteStop$1 = { message: "La location \"{{name}}\" non ha una fermata SBB corrispondente. Vuoi eliminarla?", confirm: "Elimina", cancel: "Annulla" }; var venueMatchDialog$1 = { cancel: "Annulla", selectMessage: "Trovate più fermate corrispondenti. Scegli con quale unire:", merge: "Unisci", mergeWithCoords: "Unisci e aggiorna coordinate", saveNew: "Salva nuovo", message: "Sembra che esistano già {{venueCount}} fermata/e con questo nome.
Le abbiamo selezionate per voi.
Cosa volete fare?
Selezionando
Unisci
verranno applicate le informazioni ai punti esistenti senza crearne uno nuovo." }; var hnImport$1 = { appName: "Numeri civici", layerName: "Numeri civici svizzeri", tabNote: "Mostra i punti indirizzo ufficiali del registro federale degli edifici (RegBL/GWR). Selezionate una via, poi cliccate su un punto verde per creare il suo numero.", enable: "Attivo", enableTitle: "Attivare l'importatore di numeri civici", stateIdle: "In attesa", stateFetching: "Caricamento dei punti indirizzo ({{done}}/{{total}} tasselli)", stateWaitingApi: "In attesa di geo.admin.ch", stateZoomGated: "Ingrandite per caricare gli indirizzi", stateAreaGated: "Area troppo grande, ingrandite", stateOutsideCh: "Fuori dalla Svizzera", stateCheckingExisting: "Verifica dei numeri esistenti", stateError: "Errore: {{message}}", hintSelectSegment: "Selezionate prima il segmento stradale, così il numero vi sarà collegato e i numeri esistenti potranno essere verificati.", selectedStreet: "Selezione: {{name}}", countGwr: "Punti indirizzo: {{count}}", countMissing: "mancanti {{count}}", countPresent: "già presenti {{count}}", countOtherStreet: "altra via {{count}}", unsavedBadge: "{{count}} modifica/modifiche non salvate", btnImportMissing: "Importare i {{count}} numeri mancanti", btnImportMissingCapped: "Importare {{cap}} dei {{count}} numeri mancanti", btnRefreshExisting: "Aggiornare i numeri esistenti", btnClearCache: "Svuotare la cache e ricaricare", confirmMassImport: "Creare {{count}} numeri civici su {{street}}?\n\nNumeri: {{numbers}}\n\nVanno nelle vostre modifiche in corso; nulla viene salvato. Ctrl+Z le annulla.", confirmMassImportCapped: "Creare {{cap}} dei {{count}} numeri civici mancanti su {{street}}?\n\nNumeri: {{numbers}}\n\nIl limite per azione è {{cap}}; rilanciate per il resto. Nulla viene salvato.", confirmSingleImport: "Creare il numero civico {{number}} su {{street}}?", importedCount: "{{count}} numero/i civico/i creato/i. Nulla è ancora salvato.", importStopped: "Interrotto dopo {{done}} su {{total}}: {{message}}", errNotAllowed: "La modifica non è consentita qui.", errTooFar: "Questo indirizzo è a {{distance}} m dalla via selezionata; selezionate il segmento giusto.", errSegmentNotFound: "Il segmento non è più caricato.", errInvalidState: "WME ha rifiutato la modifica.", errUnknown: "Errore imprevisto.", errNoSelection: "Nessun segmento stradale selezionato.", warnTruncated: "Troppi indirizzi qui per elencarli tutti; l'importazione in blocco è disattivata. I clic singoli funzionano ancora.", warnIncomplete: "Una parte di questa vista non ha potuto essere caricata; l'importazione in blocco è disattivata. I clic singoli funzionano ancora.", legendMissing: "Da importare", legendPresent: "Già presente", legendOtherStreet: "Altra via", legendNeutral: "Nessuna via selezionata", tooltipPresentFar: "{{number}} esiste, ma a {{distance}} m", settingsTitle: "Impostazioni", settingsAndHelp: "Impostazioni e aiuto", legendNote: "Gli stati assenti dalla selezione non sono elencati sopra.", settingsMinZoom: "Zoom minimo", settingsShowLabels: "Mostrare i numeri sulla mappa", settingsStrictMatch: "Corrispondenza rigorosa dei nomi delle vie", settingsExistingOnly: "Solo edifici costruiti", settingsConfirmSingle: "Confermare ogni importazione singola", settingsLanguage: "Lingua", shortcutImportMissing: "Importare i numeri civici mancanti", shortcutToggleLayer: "Attivare/disattivare il livello dei numeri civici", dialogConfirm: "Confermare", dialogCancel: "Annullare", dialogOk: "OK", legendTitle: "Legenda", verdictOk: "Nome conforme al registro ufficiale", verdictMismatch: "Nome diverso dal registro: {{suggestion}}", confirmMassImportUnverifiedName: "Nota: il controllo dei nomi segnala che il nome di questa via differisce dal registro ufficiale. I numeri le saranno collegati con il nome attuale.", confirmMassImportSegments: "La via è divisa in {{segments}} segmenti WME; ogni numero è collegato a quello davanti al quale si trova.", confirmMassImportReview: "Una volta creati, verificate il risultato sulla mappa e spostate i numeri che non fossero nel posto giusto.", tabTitle: "Numeri civici" }; var itCommon = { scriptName: scriptName$2, layers: layers$1, introduction: introduction$1, readmeLink: readmeLink$1, note: note$1, swissimageUpdateText: swissimageUpdateText$1, publicTransportStopsNote: publicTransportStopsNote$1, streetCheck: streetCheck$1, reloadStops: reloadStops$1, deleteObsoleteStop: deleteObsoleteStop$1, venueMatchDialog: venueMatchDialog$1, hnImport: hnImport$1 }; var itCommon$1 = /*#__PURE__*/Object.freeze({ __proto__: null, default: itCommon, deleteObsoleteStop: deleteObsoleteStop$1, hnImport: hnImport$1, introduction: introduction$1, layers: layers$1, note: note$1, publicTransportStopsNote: publicTransportStopsNote$1, readmeLink: readmeLink$1, reloadStops: reloadStops$1, scriptName: scriptName$2, streetCheck: streetCheck$1, swissimageUpdateText: swissimageUpdateText$1, venueMatchDialog: venueMatchDialog$1 }); var scriptName$1 = "WME Schweiz Helfer"; var layers = { boundaries: { municipality: "Gemeindegrenzen", state: "Kantonsgrenzen" }, "3d": "Geografische Namen swissNAMES3D", topo: { national_colors: "Landeskarten (Farbe)" }, background: { swissimage: "SWISSIMAGE Hintergrund" }, public_transport_stops: "Haltestellen des öffentlichen Verkehrs" }; var introduction = "Dieses Skript fügt Kartenebenen hinzu, die über die rechte Navigationsleiste ganz unten aktiviert werden können."; var readmeLink = "Weitere Informationen finden Sie in der vollständigen Dokumentation."; var note = { layers: { background: { swissimage: "Hinweise" } } }; var swissimageUpdateText = "Diese Karte zeigt, wann die {{layer}}-Ebene für jede Region aktualisiert wurde."; var publicTransportStopsNote = "Haltestellen des öffentlichen Nahverkehrs werden als orangefarbene Kreissymbole auf der Karte angezeigt. Klicken Sie darauf, um Venues zu erstellen oder zu aktualisieren. Haltestellen, die bereits durch einen Ort mit demselben Namen innerhalb eines Radius von 75 Metern erfasst sind, werden ausgeblendet; angezeigt werden nur die, die noch Arbeit erfordern."; var streetCheck = { appName: "Strassennamen", tabNote: "Vergleicht die Strassennamen in Waze mit dem amtlichen Schweizer Verzeichnis und meldet Abweichungen, mit 1-Klick-Korrektur. Öffne den eigenen Tab Strassennamen, um die Abweichungen zu prüfen.", editPanelHostTitle: "Schweiz", stateIdle: "Bereit", stateDisabled: "Skript deaktiviert", stateOutsideCh: "Ausserhalb der Schweiz", toggleEnabled: "Aktiv", toggleEnabledTitle: "Hauptschalter: deaktiviert Scan, Kartenebene und Panel-Box", toggleAutoScan: "Auto-Scan", toggleAutoScanTitle: "Automatisch bei Kartenbewegung scannen; sonst Neu-scannen-Knopf verwenden", stateZoomGated: "Zum Scannen hineinzoomen", stateAreaGated: "Ausschnitt zu gross zum Scannen", stateSweeping: "Bereich wird gescannt… {{done}}/{{total}} Kacheln", scanArea: "Diesen Bereich scannen", scanAreaTitle: "Lädt das amtliche Verzeichnis für den ganzen Ausschnitt, Kachel für Kachel. Kann ein bis zwei Minuten dauern.", cancelSweep: "Abbrechen", sweepTooLarge: "Ausschnitt zu gross zum Scannen, auch Bereich für Bereich", warnTruncated: "{{n}} dichte Kachel(n) von der Verzeichnis-API gekürzt, amtliche Namen können fehlen (mögliche falsche «nicht gefunden»)", warnFailedTiles: "{{n}} Kachel(n) konnten nicht geladen werden, betroffene Segmente wurden nicht geprüft", warnContinuationCap: "Such-Budget erreicht, einige «nicht gefunden» können beim nächsten Scan verschwinden", stateFetching: "Amtliches Verzeichnis wird geladen…", stateEvaluating: "Namen werden verglichen…", statePaused: "Pausiert (Ebene deaktiviert)", stateError: "Scan fehlgeschlagen", updating: "Aktualisierung…", stateDone: "{{issues}} Abweichung(en) · {{ok}} OK · {{streets}} amtliche Strassen", unsavedBadge: "{{n}} ungespeichert", rescan: "Neu scannen", rescanTitle: "Cache leeren und amtliches Verzeichnis neu laden", nextIssue: "Nächste Abweichung", nextIssueTitle: "Nächstes abweichendes Segment auswählen", locateTitle: "Karte auf das Segment zentrieren", zoomToGroupTitle: "Karte auf alle Segmente dieser Gruppe zoomen", geoAdminLinkTitle: "Diese Stelle auf map.geo.admin.ch öffnen (amtliche Verzeichnis-Ebene)", cantonMapLinkTitle: "Diese Stelle auf der Kantonskarte öffnen ({{canton}})", filterChipTitle: "Liste nach diesem Status filtern", unnamed: "(unbenannt)", noteUnofficial: "inoffiziell", notePlanned: "geplant", noteFullLabel: "vollständige Bezeichnung: {{label}}", noteExistsIn: "existiert in: {{place}}", noteOwnDistance: "amtliche Achse ~{{m}} m entfernt", noteLock: "L{{current}} → erwartet L{{expected}}", fixAll: "Alle korrigieren ({{n}})", fix: "Korrigieren", fixTitle: "«{{name}}» übernehmen", fixLockTitle: "Sperrstufe auf L{{n}} setzen", ignore: "Ignorieren", ignoreTitle: "Diesen Befund ausblenden (Fehlalarm) — lokal auf diesem Gerät gespeichert", ignoredCount: "{{n}} ignoriert", resetIgnored: "Zurücksetzen", confirmOverLockFix: "Dieses Segment ist über dem Schweizer Minimum gesperrt (oft beabsichtigt). Sperrstufe auf L{{n}} senken?", fixFailed: "Korrektur fehlgeschlagen: {{error}}", fixStopped: "{{done}}/{{total}} korrigiert, dann gestoppt: {{error}} (Segment {{id}})", allMatch: "Alle Strassennamen stimmen überein ✓", labelCOSMETIC: "Typografie", labelVARIANT: "Schreibweise", labelNEAR: "Tippfehler?", labelWRONG_TYPE: "Strassentyp", labelBILINGUAL: "Zweisprachig", labelWRONG_STREET: "Andere Strasse", labelWRONG_CITY: "Anderer Ort", labelNOT_FOUND: "Nicht gefunden", labelUNNAMED: "Ohne Namen", labelUNNAMED_NO_MATCH: "Ohne Namen, kein Tr.", labelUNDER_LOCK: "Sperre zu tief", labelOVER_LOCK: "Sperre zu hoch", labelMICRO_SEGMENT: "Mikrosegment", labelLOOP: "Schleife", labelNARROW_MISUSE: "Enge Strasse", legendTitle: "Legende", legendCOSMETIC: "nur Typografie (Gross-/Kleinschreibung, Apostroph, Leerzeichen), gestrichelt", legendVARIANT: "Abkürzung, fehlender Akzent oder Artikel; amtliche Schreibweise vorgeschlagen", legendNEAR: "wahrscheinlicher Tippfehler; ein einziger naher amtlicher Name", legendWRONG_TYPE: "anderer oder fehlender Strassentyp (Weg ↔ Strasse, X → Strasse X); eindeutiger amtlicher Name vorgeschlagen", legendBILINGUAL: "zweisprachige Strasse: primär eine Sprache, die andere als Alternative", legendWRONG_STREET: "gültiger Name, aber die amtliche Strasse darunter heisst anders", geometryMatching: "Geometrie-Matching (amtliche Strasse unter dem Segment)", geometryMatchingTitle: "Aktiviert UNNAMED-Vorschläge, Falsche-Strasse-Erkennung und Distanz-Disambiguierung", viewportOnly: "Nur auf der Karte sichtbare Segmente anzeigen", viewportOnlyTitle: "Filtert Liste und Zähler auf den aktuell sichtbaren Bereich (ohne erneuten Scan)", editableOnly: "Nur bearbeitbare Segmente", editableOnlyTitle: "Über meinem Rang gesperrte Segmente ausblenden", legendWRONG_CITY: "Name existiert, aber in einer anderen Ortschaft (Scoping)", legendNOT_FOUND: "nicht im amtlichen Verzeichnis", legendUNNAMED: "geprüfter Strassentyp ohne Namen; die amtliche Strasse darunter wird vorgeschlagen, falls gefunden, gestrichelt", legendUNNAMED_NO_MATCH: "ohne Namen und keine amtliche Strasse darunter (Geometrie-Matching) — meist normal", legendMICRO_SEGMENT: "befahrbares Segment kürzer als 5 m (Schweizer Regel; Kreisel ausgenommen)", legendLOOP: "Schleife aus weniger als 3 Segmenten (gleiche Endknoten); aufteilen", legendNARROW_MISUSE: "Falsch verwendete enge Strasse: Einbahn oder kürzer als 50 m", legendUNDER_LOCK: "Sperrstufe unter dem Schweizer Minimum für diesen Strassentyp (Kreisel: mindestens L3)", legendOVER_LOCK: "Sperrstufe über dem Schweizer Minimum (oft beabsichtigt)", guidelineChecks: "Schweizer Regelprüfungen (Mikrosegmente, Schleifen, enge Strassen)", guidelineChecksTitle: "Prüfungen aus den Editier-Richtlinien der Romandie, ohne externe Daten", helperOk: "stimmt mit dem amtlichen Verzeichnis überein", helperSetting: "Abweichungsbox im Segment-Bearbeitungspanel", settingsTitle: "Einstellungen", settingsAndHelp: "Einstellungen und Hilfe", roadTypesLabel: "Geprüfte Strassentypen:", statusesLabel: "Geprüfte Fehlertypen:", optionsLabel: "Optionen", scopeDisplayLabel: "Geltungsbereich & Anzeige", altOk: "Alternativname zählt als OK", altOkTitle: "Nützlich in zweisprachigen Gemeinden mit der zweiten Sprache als Alternativname", showMapLabels: "Erwarteten Namen auf der Karte anzeigen (Zoom ≥ 17)", keepOldName: "Alten Namen bei Korrektur als Alternative behalten", keepOldNameTitle: "Nie bei Tippfehler-Korrekturen (NEAR)", scopingLabel: "Ortschafts-Scoping:", scopingTitle: "Vergleicht die Stadt des Segments mit der amtlichen Ortschaft (zip_label)", scopingOff: "aus", scopingWarn: "warnen", scopingStrict: "strikt", minZoomLabel: "Minimaler Zoom zum Scannen:", languageLabel: "Sprache:", languageAuto: "Auto (WME)", shortcutNextIssue: "Strassennamen: nächste Abweichung auswählen", shortcutFixSelected: "Strassennamen: ausgewähltes Segment korrigieren", errNotFixable: "Nicht korrigierbar", errEditingNotAllowed: "Bearbeiten ist hier nicht erlaubt", errSegmentUnloaded: "Segment nicht mehr geladen", errNoCity: "Segment ohne Stadt; zuerst die Stadt setzen", errStreetCreate: "Strasse konnte nicht gefunden oder erstellt werden", errLockAboveRank: "Sperrstufe L{{expected}} über deiner Editor-Stufe (L{{user}})", ignoreAll: "Alle ignorieren ({{n}})", confirmIgnoreAll: "Alle {{n}} Befunde dieser Gruppe ignorieren? Lokal ausgeblendet, über die Einstellungen (Zurücksetzen) wiederherstellbar.", dialogConfirm: "Bestätigen", dialogCancel: "Abbrechen", dialogOk: "OK", detach: "Abtrennen", detachTitle: "Das Panel in ein schwebendes Fenster verschieben, das sichtbar bleibt, wenn WME zum Selection-Tab wechselt", dock: "Andocken", dockTitle: "Das Panel zurück in den Sidebar-Tab setzen", shortcutToggleWindow: "Schwebendes Fenster umschalten", noteMatchConfidence: "deckt {{pct}} % des Segments ab, {{m}} m von seiner Achse", noteRunnerUp: "nächster Kandidat {{m}} m dahinter", confirmWrongStreetFix: "Dieses Segment heisst « {{current}} », aber darunter verläuft eine andere amtliche Strasse.\nIn « {{suggestion}} » umbenennen?\nDieses Urteil stammt aus der Geometrie, prüfe es zuerst auf der Karte.", confirmGroupFixDetailed: "{{n}} Segmente von « {{current}} » in « {{suggestion}} » umbenennen?\nEs wird nichts automatisch gespeichert; in WME prüfen und speichern.", errGroupFixRank: "Gruppenkorrektur erfordert Editor-Level {{level}} oder höher. Korrigiere die Segmente einzeln.", tabTitle: "Strassennamen" }; var reloadStops = "Haltestellen des öffentlichen Verkehrs neu laden"; var deleteObsoleteStop = { message: "Der Ort \"{{name}}\" hat keine entsprechende SBB-Haltestelle. Möchten Sie ihn löschen?", confirm: "Löschen", cancel: "Abbrechen" }; var venueMatchDialog = { cancel: "Abbrechen", selectMessage: "Mehrere passende Haltestellen gefunden. Wählen Sie aus, mit welcher zusammengeführt werden soll:", merge: "Zusammenführen", mergeWithCoords: "Zusammenführen und Koordinaten aktualisieren", saveNew: "Neuen speichern", message: "Es scheinen bereits {{venueCount}} Haltestelle(n) mit diesem Namen zu existieren.
Wir haben sie für Sie ausgewählt.
Was möchten Sie tun?
Wenn Sie
Zusammenführen
wählen, werden die Informationen auf die bestehenden Punkte angewendet, ohne einen neuen zu erstellen." }; var hnImport = { appName: "Hausnummern", layerName: "Schweizer Hausnummern", tabNote: "Zeigt die offiziellen Adresspunkte des eidgenössischen Gebäude- und Wohnungsregisters (GWR). Wählen Sie eine Strasse und klicken Sie auf einen grünen Punkt, um die Hausnummer zu erstellen.", enable: "Aktiv", enableTitle: "Hausnummern-Importer aktivieren", stateIdle: "Bereit", stateFetching: "Adresspunkte werden geladen ({{done}}/{{total}} Kacheln)", stateWaitingApi: "Warte auf geo.admin.ch", stateZoomGated: "Zoomen Sie hinein, um Adressen zu laden", stateAreaGated: "Bereich zu gross, bitte hineinzoomen", stateOutsideCh: "Ausserhalb der Schweiz", stateCheckingExisting: "Bestehende Nummern werden geprüft", stateError: "Fehler: {{message}}", hintSelectSegment: "Wählen Sie zuerst das Strassensegment, damit die Nummer daran hängt und bestehende Nummern geprüft werden können.", selectedStreet: "Ausgewählt: {{name}}", countGwr: "Adresspunkte: {{count}}", countMissing: "fehlend {{count}}", countPresent: "bereits vorhanden {{count}}", countOtherStreet: "andere Strasse {{count}}", unsavedBadge: "{{count}} nicht gespeicherte Änderung(en)", btnImportMissing: "Die {{count}} fehlenden Nummern importieren", btnImportMissingCapped: "{{cap}} von {{count}} fehlenden Nummern importieren", btnRefreshExisting: "Bestehende Nummern aktualisieren", btnClearCache: "Cache leeren und neu laden", confirmMassImport: "{{count}} Hausnummern an {{street}} erstellen?\n\nNummern: {{numbers}}\n\nSie kommen zu Ihren offenen Änderungen; nichts wird gespeichert. Ctrl+Z macht sie rückgängig.", confirmMassImportCapped: "{{cap}} von {{count}} fehlenden Hausnummern an {{street}} erstellen?\n\nNummern: {{numbers}}\n\nDas Limit pro Aktion ist {{cap}}; führen Sie es für den Rest erneut aus. Nichts wird gespeichert.", confirmSingleImport: "Hausnummer {{number}} an {{street}} erstellen?", importedCount: "{{count}} Hausnummer(n) erstellt. Es ist noch nichts gespeichert.", importStopped: "Abgebrochen nach {{done}} von {{total}}: {{message}}", errNotAllowed: "Bearbeiten ist hier nicht erlaubt.", errTooFar: "Diese Adresse ist {{distance}} m von der gewählten Strasse entfernt; wählen Sie das richtige Segment.", errSegmentNotFound: "Das Segment ist nicht mehr geladen.", errInvalidState: "WME hat die Änderung abgelehnt.", errUnknown: "Unerwarteter Fehler.", errNoSelection: "Kein Strassensegment ausgewählt.", warnTruncated: "Zu viele Adressen hier, um sie alle aufzulisten; der Massenimport ist deaktiviert. Einzelne Klicks funktionieren weiterhin.", warnIncomplete: "Ein Teil dieser Ansicht konnte nicht geladen werden; der Massenimport ist deaktiviert. Einzelne Klicks funktionieren weiterhin.", legendMissing: "Zu importieren", legendPresent: "Bereits vorhanden", legendOtherStreet: "Andere Strasse", legendNeutral: "Keine Strasse ausgewählt", tooltipPresentFar: "{{number}} existiert, aber {{distance}} m entfernt", settingsTitle: "Einstellungen", settingsAndHelp: "Einstellungen und Hilfe", legendNote: "Nicht in der Auswahl vorhandene Status werden oben nicht aufgeführt.", settingsMinZoom: "Mindest-Zoom", settingsShowLabels: "Nummern auf der Karte anzeigen", settingsStrictMatch: "Strikter Abgleich der Strassennamen", settingsExistingOnly: "Nur gebaute Gebäude", settingsConfirmSingle: "Jeden Einzelimport bestätigen", settingsLanguage: "Sprache", shortcutImportMissing: "Fehlende Hausnummern importieren", shortcutToggleLayer: "Hausnummern-Ebene ein-/ausschalten", dialogConfirm: "Bestätigen", dialogCancel: "Abbrechen", dialogOk: "OK", legendTitle: "Legende", verdictOk: "Name entspricht dem offiziellen Register", verdictMismatch: "Name weicht vom Register ab: {{suggestion}}", confirmMassImportUnverifiedName: "Hinweis: Die Strassennamen-Prüfung meldet, dass der Name dieser Strasse vom offiziellen Register abweicht. Die Nummern werden ihr unter dem heutigen Namen zugeordnet.", confirmMassImportSegments: "Die Strasse ist in {{segments}} WME-Segmente unterteilt; jede Nummer wird dem Segment zugeordnet, an dem sie liegt.", confirmMassImportReview: "Prüfen Sie danach das Ergebnis auf der Karte und verschieben Sie Nummern, die nicht am richtigen Ort liegen.", tabTitle: "Hausnummern" }; var deCommon = { scriptName: scriptName$1, layers: layers, introduction: introduction, readmeLink: readmeLink, note: note, swissimageUpdateText: swissimageUpdateText, publicTransportStopsNote: publicTransportStopsNote, streetCheck: streetCheck, reloadStops: reloadStops, deleteObsoleteStop: deleteObsoleteStop, venueMatchDialog: venueMatchDialog, hnImport: hnImport }; var deCommon$1 = /*#__PURE__*/Object.freeze({ __proto__: null, default: deCommon, deleteObsoleteStop: deleteObsoleteStop, hnImport: hnImport, introduction: introduction, layers: layers, note: note, publicTransportStopsNote: publicTransportStopsNote, readmeLink: readmeLink, reloadStops: reloadStops, scriptName: scriptName$1, streetCheck: streetCheck, swissimageUpdateText: swissimageUpdateText, venueMatchDialog: venueMatchDialog }); instance.init({ lng: "en", fallbackLng: "en", resources: { en: { common: enCommon$1, }, fr: { common: frCommon$1, }, it: { common: itCommon$1, }, de: { common: deCommon$1, }, }, }); const ORANGE_COLOR = "#e67e22"; const RED_COLOR = "#e74c3c"; const BUS_PATH = "M29.726 14a3 3 0 0 1 2.995 2.824l.005.176v1h1.017l.15.005c.938.06 1.76.684 1.843 1.591l.007.154V22l-.007.117a1 1 0 0 1-.876.876l-.117.007-.117-.007a1 1 0 0 1-.876-.876L33.743 22v-2h-1.017v10a1 1 0 0 1-.883.993l-.117.007h-1v1.5a1.5 1.5 0 0 1-3 0V31h-6v1.5a1.5 1.5 0 0 1-3 0V31h-1a1 1 0 0 1-.993-.883L16.726 30V20h-1v2a1 1 0 0 1-.883.993l-.117.007a1 1 0 0 1-.993-.883L13.726 22v-2.25c0-.99.86-1.682 1.85-1.745l.15-.005h1v-1a3 3 0 0 1 2.824-2.995l.176-.005zm-1 13h-1a1 1 0 1 0 0 2h1a1 1 0 1 0 0-2m-7 0h-1a1 1 0 1 0 0 2h1a1 1 0 1 0 0-2m-.429-11h-1.57l-.117.007a1 1 0 0 0-.877.876l-.007.117v8h12v-8l-.007-.117a1 1 0 0 0-.764-.857l-.112-.02-.117-.006h-1.572l-.854 1.496-.065.1a1 1 0 0 1-.803.404H23.02l-.119-.007a1 1 0 0 1-.75-.497z"; function generateStopSvg(color) { const svg = ``; return `data:image/svg+xml;base64,${btoa(svg)}`; } function generateClusterSvg(color, count) { const label = count > 99 ? "99+" : String(count); const svg = `${label}`; return `data:image/svg+xml;base64,${btoa(svg)}`; } const ORANGE_STOP_SVG = generateStopSvg(ORANGE_COLOR); const RED_STOP_SVG = generateStopSvg(RED_COLOR); const MATCH_CHUNK_SIZE = 100; const OBSOLETE_EXEMPT_CATEGORIES = ["SEAPORT_MARINA_HARBOR"]; const ADD_VENUE_MIN_ZOOM = 16; const ADD_VENUE_ZOOM_IN_LEVEL = 17; const SAME_COORD_RADIUS_METERS = 2.5; const CELL_MARGIN_DEG = 0.002; const RENDER_DEBOUNCE_MS = 700; function yieldToEventLoop() { return new Promise((resolve) => setTimeout(resolve, 0)); } class PublicTransportStopsLayer extends FeatureLayer { constructor(args) { super({ ...args, wmeSDK: args.wmeSDK, minZoomLevel: 12 }); this.renderGeneration = 0; this.cachedData = null; this.renderDebounceTimer = null; this.sdk = args.wmeSDK; this.reloadButton = new ReloadButton({ onClick: () => this.forceReload(), title: instance.t("common:reloadStops", "Refresh public transport stops"), }); this.dataFetcher = new SBBDataFetcher({ dataSet: "haltestelle-haltekante", }); this.stopGeometry = new StopGeometry(); this.nameFormatter = new StopNameFormatter(); this.venueMatcher = new VenueMatcher(); this.wazeVenueFetcher = new WazeVenueFetcher(); this.clusterManager = new ClusterManager(); this.featureKinds = new Map(); this.clusterData = new Map(); this.styleContext = this.buildStyleContext(); this.styleRules = this.buildStyleRules(); } buildStyleContext() { return { externalGraphic: ({ feature }) => { const id = String(feature?.id ?? ""); const kind = this.featureKinds.get(id); if (kind === "obsolete-venue") return RED_STOP_SVG; if (kind === "cluster-sbb") { return this.clusterData.get(id)?.svgDataUrl ?? ORANGE_STOP_SVG; } if (kind === "cluster-obsolete") { return this.clusterData.get(id)?.svgDataUrl ?? RED_STOP_SVG; } return ORANGE_STOP_SVG; }, pointRadius: ({ feature }) => { const id = String(feature?.id ?? ""); const kind = this.featureKinds.get(id); return kind === "cluster-sbb" || kind === "cluster-obsolete" ? 20 : 13; }, }; } buildStyleRules() { return [ { style: { fillOpacity: 1, cursor: "pointer", pointRadius: "${pointRadius}", externalGraphic: "${externalGraphic}", }, }, ]; } getRecordId(args) { const record = args.record; return String(record.number); } mapRecordToFeature(args) { const record = args.record; return { geometry: { coordinates: [ record.geopos_haltestelle.lon, record.geopos_haltestelle.lat, ], type: "Point", }, type: "Feature", id: String(record.number), }; } async *fetchData(args) { for await (const batch of this.dataFetcher.fetchRecords({ wmeSDK: args.wmeSDK, })) { yield batch; } } shouldDrawRecord(_args) { return true; } async render(args) { const generation = ++this.renderGeneration; this.reloadButton.setLoading(true); try { await this.runRender(args, generation); } finally { if (generation === this.renderGeneration) { this.reloadButton.setLoading(false); } } } async runRender(args, generation) { const { wmeSDK } = args; if (!wmeSDK.LayerSwitcher.isLayerCheckboxChecked({ name: this.name })) return; const zoomLevel = wmeSDK.Map.getZoomLevel(); if (zoomLevel < this.minZoomLevel) { this.clearAllFeatures({ wmeSDK }); this.cachedData = null; return; } const extent = wmeSDK.Map.getMapExtent(); const cells = this.buildRasterCells({ extent, zoomLevel }); const sdkVenues = this.getSdkTransportVenues({ wmeSDK }); const reuse = this.cachedData !== null && this.extentContains({ outer: this.cachedData.extent, inner: extent }); let sbbStops; let cellVenues; if (reuse) { const cache = this.cachedData; sbbStops = cache.sbbStops; cellVenues = cells.map((bbox) => { const expanded = this.expandBbox(bbox); return Promise.resolve(cache.venues.filter((v) => this.isInBbox({ lonLat: this.getVenueCenter(v), bbox: expanded }))); }); } else { sbbStops = await this.collectAllSBBStops({ wmeSDK }); if (this.isStale(generation)) return; cellVenues = cells.map((bbox) => this.wazeVenueFetcher.fetchVenuesForBbox({ wmeSDK, bbox: this.expandBbox(bbox), })); } const today = todayIsoDate(); const activeStops = sbbStops.filter((s) => isStopActive(s.validto, today)); this.clearAllFeatures({ wmeSDK }); const fetchedVenues = new Map(); for (let i = 0; i < cells.length; i++) { const bbox = cells[i]; const apiVenues = await cellVenues[i]; if (this.isStale(generation)) return; if (!reuse) { for (const venue of apiVenues) fetchedVenues.set(String(venue.id), venue); } const venues = this.mergeCellVenues({ apiVenues, sdkVenues, bbox: this.expandBbox(bbox), }); const activeCellStops = activeStops.filter((stop) => this.isInBbox({ lonLat: this.stopLonLat(stop), bbox })); const orangeStops = await this.filterOrangeStops({ sbbStops: activeCellStops, venues, generation, }); if (this.isStale(generation)) return; const ownedVenues = venues.filter((v) => this.isInBbox({ lonLat: this.getVenueCenter(v), bbox })); const obsoleteVenues = await this.filterRedVenues({ venues: ownedVenues, activeStops, generation, }); if (this.isStale(generation)) return; const desired = zoomLevel < 15 ? this.buildClusteredFeatures({ orangeStops, obsoleteVenues, zoomLevel, }) : this.buildIndividualFeatures({ orangeStops, obsoleteVenues }); this.addFeatures({ wmeSDK, desired }); await yieldToEventLoop(); if (this.isStale(generation)) return; } if (!reuse) { this.cachedData = { extent, sbbStops, venues: Array.from(fetchedVenues.values()), }; } } onMapMoveEnd(args) { if (this.renderDebounceTimer !== null) { clearTimeout(this.renderDebounceTimer); } this.renderDebounceTimer = setTimeout(() => { this.renderDebounceTimer = null; void waitForMapIdle({ wmeSDK: args.wmeSDK, intervalMs: 50, maxTries: 60, }).then(() => this.render({ wmeSDK: args.wmeSDK })); }, RENDER_DEBOUNCE_MS); } extentContains(args) { const [oMinLon, oMinLat, oMaxLon, oMaxLat] = args.outer; const [iMinLon, iMinLat, iMaxLon, iMaxLat] = args.inner; return (iMinLon >= oMinLon && iMinLat >= oMinLat && iMaxLon <= oMaxLon && iMaxLat <= oMaxLat); } isStale(generation) { return generation !== this.renderGeneration; } buildRasterCells(args) { const [minLon, minLat, maxLon, maxLat] = args.extent; const side = Math.max(1, 2 ** (14 - args.zoomLevel)); const lonStep = (maxLon - minLon) / side; const latStep = (maxLat - minLat) / side; const cells = []; for (let r = 0; r < side; r++) { const y2 = maxLat - r * latStep; const y1 = y2 - latStep; for (let c = 0; c < side; c++) { const x1 = minLon + c * lonStep; cells.push([x1, y1, x1 + lonStep, y2]); } } return cells; } getSdkTransportVenues(args) { const venues = args.wmeSDK.DataModel.Venues.getAll(); return venues.filter((venue) => venue.categories.some((c) => TRANSPORT_CATEGORIES.includes(c))); } mergeCellVenues(args) { const byId = new Map(); for (const venue of args.apiVenues) byId.set(String(venue.id), venue); for (const venue of args.sdkVenues) { const center = this.getVenueCenter(venue); if (center && this.isInBbox({ lonLat: center, bbox: args.bbox })) { byId.set(String(venue.id), venue); } } return Array.from(byId.values()); } expandBbox(bbox) { const [x1, y1, x2, y2] = bbox; return [ x1 - CELL_MARGIN_DEG, y1 - CELL_MARGIN_DEG, x2 + CELL_MARGIN_DEG, y2 + CELL_MARGIN_DEG, ]; } isInBbox(args) { if (!args.lonLat) return false; const [x1, y1, x2, y2] = args.bbox; const { lon, lat } = args.lonLat; return lon >= x1 && lon < x2 && lat >= y1 && lat < y2; } async filterOrangeStops(args) { const result = []; let processed = 0; for (const stop of args.sbbStops) { const stopLonLat = stop.meansoftransport ? this.stopLonLat(stop) : null; if (stopLonLat) { const { name } = this.nameFormatter.formatName(stop); const categories = this.venueCategories({ meansoftransport: stop.meansoftransport, }); const matched = this.venueMatcher.hasExactMatch({ venues: args.venues, stopLon: stopLonLat.lon, stopLat: stopLonLat.lat, stopName: name, categories, }); if (!matched) result.push(stop); } if (++processed % MATCH_CHUNK_SIZE === 0) { await yieldToEventLoop(); if (this.isStale(args.generation)) return result; } } return result; } async filterRedVenues(args) { const result = []; let processed = 0; for (const venue of args.venues) { const isExempt = venue.categories.some((c) => OBSOLETE_EXEMPT_CATEGORIES.includes(c)); const coveredByActive = this.isCoveredBySBBStop({ venue, sbbStops: args.activeStops, }); if (!isExempt && !coveredByActive) { result.push(venue); } if (++processed % MATCH_CHUNK_SIZE === 0) { await yieldToEventLoop(); if (this.isStale(args.generation)) return result; } } return result; } clearAllFeatures(args) { const ids = Array.from(this.visibleFeatureIds); if (ids.length > 0) { args.wmeSDK.Map.removeFeaturesFromLayer({ featureIds: ids, layerName: this.name, }); } this.visibleFeatureIds.clear(); this.features.clear(); this.featureKinds.clear(); this.clusterData.clear(); } addFeatures(args) { const toAdd = args.desired.filter((f) => !this.visibleFeatureIds.has(f.id)); if (toAdd.length === 0) return; for (const f of toAdd) { this.visibleFeatureIds.add(f.id); this.features.set(f.id, f.record); this.featureKinds.set(f.id, f.kind); if (f.clusterDisplayData) { this.clusterData.set(f.id, f.clusterDisplayData); } } args.wmeSDK.Map.addFeaturesToLayer({ features: toAdd.map((f) => f.sdkFeature), layerName: this.name, }); } refilterFeatures(args) { void this.render(args); } async addToMap(args) { this.reloadButton.mount(); await super.addToMap(args); } registerEvents(args) { super.registerEvents(args); const cleanup = args.wmeSDK.Events.on({ eventName: "wme-save-finished", eventHandler: () => this.reloadButton.mount(), }); this.eventCleanups.push(cleanup); } removeFromMap(args) { super.removeFromMap(args); this.reloadButton.unmount(); this.renderGeneration++; if (this.renderDebounceTimer !== null) { clearTimeout(this.renderDebounceTimer); this.renderDebounceTimer = null; } this.cachedData = null; this.features.clear(); this.featureKinds.clear(); this.clusterData.clear(); } forceReload() { this.cachedData = null; void this.render({ wmeSDK: this.sdk }); } async featureClicked(args) { const { wmeSDK, featureId } = args; const id = String(featureId); const kind = this.featureKinds.get(id); if (kind === "cluster-sbb" || kind === "cluster-obsolete") { this.handleClusterClick({ wmeSDK, featureId: id }); } else if (kind === "obsolete-venue") { await this.handleObsoleteVenueClick({ wmeSDK, featureId: id }); } else { await this.handleSBBStopClick({ wmeSDK, featureId }); } } buildIndividualFeatures(args) { const result = []; for (const stop of args.orangeStops) { result.push({ id: String(stop.number), sdkFeature: this.mapRecordToFeature({ record: stop }), kind: "sbb-stop", record: stop, }); } for (const venue of args.obsoleteVenues) { const center = this.getVenueCenter(venue); if (!center) continue; const id = `venue-${venue.id}`; result.push({ id, sdkFeature: { type: "Feature", id, geometry: { type: "Point", coordinates: [center.lon, center.lat] }, }, kind: "obsolete-venue", record: venue, }); } return result; } buildClusteredFeatures(args) { const result = []; const { zoomLevel } = args; const orangeItems = args.orangeStops .map((stop) => { const lonLat = this.stopLonLat(stop); if (!lonLat) return null; return { id: String(stop.number), lat: lonLat.lat, lon: lonLat.lon, kind: "sbb-stop", }; }) .filter((item) => item !== null); const orangeResult = this.clusterManager.cluster({ items: orangeItems, zoomLevel, }); const orangeStopById = new Map(args.orangeStops.map((s) => [String(s.number), s])); for (const cluster of orangeResult.clusters) { const svgDataUrl = generateClusterSvg(ORANGE_COLOR, cluster.count); result.push(this.clusterToFeature(cluster, "cluster-sbb", svgDataUrl)); } for (const item of orangeResult.singles) { const stop = orangeStopById.get(item.id); if (!stop) continue; result.push({ id: item.id, sdkFeature: this.mapRecordToFeature({ record: stop }), kind: "sbb-stop", record: stop, }); } const redItems = args.obsoleteVenues .map((venue) => { const center = this.getVenueCenter(venue); if (!center) return null; return { id: `venue-${venue.id}`, lat: center.lat, lon: center.lon, kind: "obsolete-venue", }; }) .filter((item) => item !== null); const redResult = this.clusterManager.cluster({ items: redItems, zoomLevel, }); const obsoleteById = new Map(args.obsoleteVenues.map((v) => [`venue-${v.id}`, v])); for (const cluster of redResult.clusters) { const svgDataUrl = generateClusterSvg(RED_COLOR, cluster.count); result.push(this.clusterToFeature(cluster, "cluster-obsolete", svgDataUrl)); } for (const item of redResult.singles) { const venue = obsoleteById.get(item.id); if (!venue) continue; const center = this.getVenueCenter(venue); if (!center) continue; result.push({ id: item.id, sdkFeature: { type: "Feature", id: item.id, geometry: { type: "Point", coordinates: [center.lon, center.lat] }, }, kind: "obsolete-venue", record: venue, }); } return result; } clusterToFeature(cluster, kind, svgDataUrl) { return { id: cluster.id, sdkFeature: { type: "Feature", id: cluster.id, geometry: { type: "Point", coordinates: [cluster.center.lon, cluster.center.lat], }, }, kind, record: cluster, clusterDisplayData: { bbox: cluster.bbox, count: cluster.count, itemIds: cluster.itemIds, svgDataUrl, }, }; } async collectAllSBBStops(args) { const stops = []; for await (const batch of this.dataFetcher.fetchRecords({ wmeSDK: args.wmeSDK, })) { stops.push(...batch); } return stops; } isCoveredBySBBStop(args) { const { venue, sbbStops } = args; return sbbStops.some((stop) => { if (!stop.meansoftransport) return false; const stopLonLat = this.stopLonLat(stop); if (!stopLonLat) return false; const stopCategories = this.venueCategories({ meansoftransport: stop.meansoftransport, }); const hasMatchingCategory = venue.categories.some((c) => stopCategories.includes(c)); if (!hasMatchingCategory) return false; const stopPoint = point([stopLonLat.lon, stopLonLat.lat]); return this.stopGeometry.isWithinRadius({ stopPoint, venueGeometry: venue.geometry, radiusMeters: 75, }); }); } getVenueCenter(venue) { const geo = venue.geometry; if (!geo) return null; if (geo.type === "Point") { const coords = geo.coordinates; return { lon: coords[0], lat: coords[1] }; } if (geo.type === "Polygon") { const ring = geo.coordinates[0]; return { lon: ring.reduce((s, c) => s + c[0], 0) / ring.length, lat: ring.reduce((s, c) => s + c[1], 0) / ring.length, }; } if (geo.type === "MultiPolygon") { const ring = geo.coordinates[0][0]; return { lon: ring.reduce((s, c) => s + c[0], 0) / ring.length, lat: ring.reduce((s, c) => s + c[1], 0) / ring.length, }; } return null; } meansOfTransport(args) { return args.meansoftransport.split("|"); } venueCategories(args) { return this.meansOfTransport(args).map((mean) => { if (mean === "METRO") return "SUBWAY_STATION"; if (mean === "BOAT") return "SEAPORT_MARINA_HARBOR"; if (mean === "CHAIRLIFT") return "TRANSPORTATION"; if (mean === "CABLE_RAILWAY") return "TRAIN_STATION"; return `${mean}_STATION`; }); } stopLonLat(record) { const lat = parseFloat(String(record.geopos_haltestelle?.lat || record.lat || 0)); const lon = parseFloat(String(record.geopos_haltestelle?.lon || record.lon || 0)); if (Number.isNaN(lat) || Number.isNaN(lon)) return null; return { lat, lon }; } handleClusterClick(args) { const { wmeSDK, featureId } = args; const data = this.clusterData.get(featureId); if (!data) return; const [minLon, minLat, maxLon, maxLat] = data.bbox; const centerLat = (minLat + maxLat) / 2; const centerLon = (minLon + maxLon) / 2; const zoomLevel = this.clusterManager.zoomForBbox(data.bbox); wmeSDK.Map.setMapCenter({ lonLat: { lat: centerLat, lon: centerLon }, zoomLevel, }); } async handleObsoleteVenueClick(args) { const { wmeSDK, featureId } = args; const venue = this.features.get(featureId); if (!venue) return; const result = await showWmeDialog({ message: instance.t("common:deleteObsoleteStop.message", { name: venue.name, }), buttons: [ { label: instance.t("common:deleteObsoleteStop.confirm"), value: "confirm", }, { label: instance.t("common:deleteObsoleteStop.cancel"), value: "cancel", }, ], }); if (result !== "confirm") return; const venueId = String(venue.id); const loaded = await this.ensureVenueLoaded({ wmeSDK, venue, venueId }); if (!loaded) return; wmeSDK.DataModel.Venues.deleteVenue({ venueId }); this.removeFeature({ wmeSDK, featureId }); this.featureKinds.delete(featureId); this.features.delete(featureId); this.cachedData = null; } async ensureVenueLoaded(args) { const { wmeSDK, venue, venueId } = args; if (wmeSDK.DataModel.Venues.getById({ venueId })) return true; const center = this.getVenueCenter(venue); if (!center) return false; wmeSDK.Map.setMapCenter({ lonLat: { lat: center.lat, lon: center.lon }, zoomLevel: ADD_VENUE_ZOOM_IN_LEVEL, }); await waitForMapIdle({ wmeSDK, intervalMs: 50, maxTries: 60 }); for (let i = 0; i < 30; i++) { if (wmeSDK.DataModel.Venues.getById({ venueId })) return true; await new Promise((resolve) => setTimeout(resolve, 100)); } return false; } findNearbyVenues(args) { const byId = new Map(); for (const venue of this.cachedData?.venues ?? []) { byId.set(String(venue.id), venue); } for (const venue of this.getSdkTransportVenues({ wmeSDK: args.wmeSDK })) { byId.set(String(venue.id), venue); } return this.venueMatcher.findMatchingVenues({ venues: Array.from(byId.values()), stopLon: args.lon, stopLat: args.lat, categories: args.categories, radiusMeters: 75, }); } async ensureAreaLoaded(args) { const { wmeSDK, lat, lon } = args; wmeSDK.Map.setMapCenter({ lonLat: { lat, lon }, zoomLevel: ADD_VENUE_ZOOM_IN_LEVEL, }); await waitForMapIdle({ wmeSDK, intervalMs: 50, maxTries: 60 }); await new Promise((resolve) => setTimeout(resolve, 200)); } async handleSBBStopClick(args) { const { wmeSDK, featureId } = args; const id = String(featureId); const stop = this.features.get(id); if (!stop) return; const stopLonLat = this.stopLonLat(stop); if (!stopLonLat) return; const { lat, lon } = stopLonLat; const zoomLevel = wmeSDK.Map.getZoomLevel(); if (zoomLevel < ADD_VENUE_MIN_ZOOM) { this.handleZoomRequired({ wmeSDK, lat, lon }); return; } const { name, aliases } = this.nameFormatter.formatName(stop); const venueCategories = this.venueCategories({ meansoftransport: stop.meansoftransport, }); const nearbyVenues = this.findNearbyVenues({ wmeSDK, lat, lon, categories: venueCategories, }); const candidateMissingFromSdk = nearbyVenues.some((v) => !wmeSDK.DataModel.Venues.getById({ venueId: String(v.id) })); if (candidateMissingFromSdk) { await this.ensureAreaLoaded({ wmeSDK, lat, lon }); } const sdkCategoryVenues = wmeSDK.DataModel.Venues.getAll().filter((v) => v.categories.some((cat) => venueCategories.includes(cat))); let venuesToUpdate = []; if (sdkCategoryVenues.length > 0) { const matchingVenues = this.venueMatcher.findMatchingVenues({ venues: sdkCategoryVenues, stopLon: lon, stopLat: lat, categories: venueCategories, radiusMeters: 75, }); if (matchingVenues.length > 0) { const sameCoordVenue = matchingVenues.find((v) => this.isVenueWithin({ venue: v, lon, lat, radiusMeters: SAME_COORD_RADIUS_METERS })); let chosen; if (sameCoordVenue) { chosen = sameCoordVenue; } else if (matchingVenues.length === 1) { chosen = matchingVenues[0]; } else { chosen = await this.selectVenueToMerge({ wmeSDK, matchingVenues }); if (!chosen) return; } const action = await this.promptMergeAction({ wmeSDK, venue: chosen, sameCoord: Boolean(sameCoordVenue), }); if (action === "cancel") return; if (action === "merge") { venuesToUpdate = [chosen]; } else if (action === "merge-with-coords") { venuesToUpdate = [{ ...chosen, _updateCoordinates: true }]; } } } const updatedVenues = await this.createOrUpdateVenue({ wmeSDK, venuesToUpdate, lon, lat, name, aliases, categories: venueCategories, }); for (const venue of updatedVenues) { this.assignVenueCity({ wmeSDK, venueId: venue.id.toString(), localityname: stop.localityname, }); } this.trySelectVenues(wmeSDK, updatedVenues.map((venue) => venue.id.toString())); this.removeFeature({ wmeSDK, featureId }); this.featureKinds.delete(id); this.features.delete(id); this.cachedData = null; } handleZoomRequired(args) { const { wmeSDK, lat, lon } = args; wmeSDK.Map.setMapCenter({ lonLat: { lat, lon }, zoomLevel: ADD_VENUE_ZOOM_IN_LEVEL, }); waitForMapIdle({ wmeSDK, intervalMs: 50, maxTries: 60 }).then(() => { this.refilterFeatures({ wmeSDK }); }); } trySelectVenues(wmeSDK, ids) { if (ids.length === 0) return; try { wmeSDK.Editing.setSelection({ selection: { ids, objectType: "venue" }, }); } catch (error) { console.warn("[PTLayer] could not select venue(s):", ids, error); } } isVenueWithin(args) { return this.stopGeometry.isWithinRadius({ stopPoint: point([args.lon, args.lat]), venueGeometry: args.venue.geometry, radiusMeters: args.radiusMeters, }); } async selectVenueToMerge(args) { const { wmeSDK, matchingVenues } = args; this.trySelectVenues(wmeSDK, matchingVenues.map((venue) => venue.id.toString())); const buttons = matchingVenues.map((venue, index) => ({ label: venue.name?.trim() ? venue.name : `#${index + 1}`, value: String(index), })); buttons.push({ label: instance.t("common:venueMatchDialog.cancel"), value: "cancel", }); const result = await showWmeDialog({ message: instance.t("common:venueMatchDialog.selectMessage"), buttons, }); if (result === "cancel") return undefined; return matchingVenues[Number(result)]; } async promptMergeAction(args) { const { wmeSDK, venue, sameCoord } = args; this.trySelectVenues(wmeSDK, [venue.id.toString()]); const buttons = [ { label: instance.t("common:venueMatchDialog.merge"), value: "merge" }, ]; if (!sameCoord) { buttons.push({ label: instance.t("common:venueMatchDialog.mergeWithCoords"), value: "merge-with-coords", }); } buttons.push({ label: instance.t("common:venueMatchDialog.saveNew"), value: "save", }); buttons.push({ label: instance.t("common:venueMatchDialog.cancel"), value: "cancel", }); const result = await showWmeDialog({ message: instance.t("common:venueMatchDialog.message", { venueCount: 1 }), allowHtml: true, buttons, }); return result; } async createOrUpdateVenue(args) { const { wmeSDK, venuesToUpdate, lon, lat, name, aliases, categories } = args; let venues = venuesToUpdate; if (venues.length === 0) { const geometry = { type: "Point", coordinates: [lon, lat], }; const venueId = wmeSDK.DataModel.Venues.addVenue({ category: "TRANSPORTATION", geometry, }); const newVenue = wmeSDK.DataModel.Venues.getById({ venueId: venueId.toString(), }); if (newVenue) venues = [newVenue]; } for (const venue of venues) { const updateArgs = { venueId: venue.id.toString(), name, aliases, categories: categories, ...(venue._updateCoordinates && { geometry: { type: "Point", coordinates: [lon, lat], }, }), }; wmeSDK.DataModel.Venues.updateVenue(updateArgs); } return venues; } assignVenueCity(args) { const { wmeSDK, venueId, localityname } = args; const city = findCityForStop(localityname, (cityName) => { try { return wmeSDK.DataModel.Cities.getCity({ cityName }); } catch { return null; } }); if (!city) { console.log(`[PTLayer][city] no WME city found for locality "${localityname}"`); return; } let street; try { street = wmeSDK.DataModel.Streets.getStreet({ cityId: city.id, streetName: "", }) ?? wmeSDK.DataModel.Streets.addStreet({ cityId: city.id, streetName: "", }); } catch { return; } wmeSDK.DataModel.Venues.updateAddress({ venueId, streetId: street.id }); } } class LayoutElement { constructor(args) { this.name = args.name; } } class Paragraph extends LayoutElement { constructor(args) { super({ name: args.name || "" }); this.content = args.content; this.cssClass = args.cssClass; } render() { const classAttr = this.cssClass ? ` class="${this.cssClass}"` : ""; return `${this.content}

`; } } class SidebarItem extends LayoutElement { constructor(args) { super({ name: args.name }); this.icon = args.icon; this.content = args.content; } render() { const iconHTML = this.icon ? `` : ""; return `
${iconHTML}${this.name}

${this.content}

`; } } class SidebarSection extends LayoutElement { constructor(args) { super({ name: args.name }); this.children = args.children || []; this.cssClass = args.cssClass; } addChild(child) { this.children.push(child); return this; } render() { const childrenHTML = this.children.map((child) => child.render()).join(""); const classAttr = this.cssClass ? ` ${this.cssClass}` : ""; return `
${this.name}
${childrenHTML}
`; } } class SidebarTab { constructor(args) { this.scriptName = args.scriptName; this.children = args.children || []; } addChild(child) { this.children.push(child); return this; } render() { const childrenHTML = this.children.map((child) => child.render()).join(""); return ``; } } function setImporterEnabled(ctx, enabled, source) { ctx.settings.update({ enabled }); ctx.layer.setVisible(enabled); if (source !== "checkbox") ctx.syncCheckbox(enabled); if (source !== "tab") ctx.syncToggle(enabled); if (enabled) void ctx.controller.refresh(); else ctx.controller.disable(); } const PAGE_SIZE = 200; const IDENTIFY_URL = "https://api3.geo.admin.ch/rest/services/api/MapServer/identify"; const MAX_REQUESTS_PER_MINUTE = 30; function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } class RateLimiter { constructor(maxPerMinute = MAX_REQUESTS_PER_MINUTE) { this.maxPerMinute = maxPerMinute; this.stamps = []; this.queue = Promise.resolve(); } acquire() { const next = this.queue.then(async () => { let now = Date.now(); this.stamps = this.stamps.filter((t) => now - t < 60_000); if (this.stamps.length >= this.maxPerMinute) { const oldest = this.stamps[0] ?? now; await sleep(Math.max(0, oldest + 60_000 - now)); now = Date.now(); this.stamps = this.stamps.filter((t) => now - t < 60_000); } this.stamps.push(Date.now()); }); this.queue = next.catch(() => undefined); return next; } } const rateLimiter = new RateLimiter(); function gmGetJson(url, signal) { return new Promise((resolve, reject) => { if (signal?.aborted) { reject(new DOMException("Scan aborted", "AbortError")); return; } const handle = GM_xmlhttpRequest({ method: "GET", url, responseType: "json", onload: (r) => r.status >= 200 && r.status < 300 ? resolve(r.response) : reject(new Error(`geo.admin.ch HTTP ${r.status}`)), onerror: () => reject(new Error("GM_xmlhttpRequest network error")), ontimeout: () => reject(new Error("GM_xmlhttpRequest timeout")), }); signal?.addEventListener("abort", () => { handle.abort(); reject(new DOMException("Scan aborted", "AbortError")); }); }); } async function httpGetJson(url, signal) { if (typeof GM_xmlhttpRequest === "function") return gmGetJson(url, signal); const res = await fetch(url, { signal }); if (!res.ok) throw new Error(`geo.admin.ch HTTP ${res.status}`); return (await res.json()); } function k0(name) { return name.normalize("NFC").trim(); } const APOSTROPHES = /[’ʼ´`]/g; const DASHES = /[–—−]/g; function k1(name) { let s = k0(name); s = s.replace(APOSTROPHES, "'"); s = s.replace(DASHES, "-"); s = s.replace(/\s+/g, " "); s = s.replace(/\s*-\s*/g, "-"); s = s.toLowerCase(); s = s.replace(/ß/g, "ss"); return s.trim(); } function foldAccents(s) { return s.normalize("NFD").replace(/\p{M}/gu, "").normalize("NFC"); } const ABBREVIATIONS = [ { abbrev: "av", expansions: ["avenue"], firstTokenOnly: true }, { abbrev: "bd", expansions: ["boulevard"] }, { abbrev: "bvd", expansions: ["boulevard"] }, { abbrev: "boul", expansions: ["boulevard"] }, { abbrev: "ch", expansions: ["chemin"], firstTokenOnly: true }, { abbrev: "rte", expansions: ["route"] }, { abbrev: "pl", expansions: ["place", "platz", "piazza"] }, { abbrev: "imp", expansions: ["impasse"] }, { abbrev: "prom", expansions: ["promenade"] }, { abbrev: "pass", expansions: ["passage"] }, { abbrev: "fbg", expansions: ["faubourg"] }, { abbrev: "fg", expansions: ["faubourg"] }, { abbrev: "st", expansions: ["saint", "sankt"] }, { abbrev: "ste", expansions: ["sainte"] }, { abbrev: "str", expansions: ["strasse"] }, { abbrev: "zi", expansions: ["zone industrielle"] }, { abbrev: "za", expansions: ["zone artisanale"] }, { abbrev: "gd", expansions: ["grand"] }, { abbrev: "gde", expansions: ["grande"] }, { abbrev: "all", expansions: ["allee"], firstTokenOnly: true }, { abbrev: "esp", expansions: ["esplanade"], firstTokenOnly: true }, { abbrev: "anc", expansions: ["ancien", "ancienne"] }, { abbrev: "gen", expansions: ["general"] }, { abbrev: "dr", expansions: ["docteur"] }, { abbrev: "pt", expansions: ["petit"] }, { abbrev: "pte", expansions: ["petite"] }, ]; const ABBREV_MAP = new Map(ABBREVIATIONS.map((r) => [r.abbrev, r])); const MAX_VARIANTS = 8; const ARTICLES = new Set([ "de", "du", "des", "la", "le", "les", "di", "da", "del", "della", "delle", "dei", "degli", "al", "alla", "ai", ]); const WAY_TYPE_WORDS = new Set([ "rue", "route", "chemin", "avenue", "boulevard", "impasse", "sentier", "passage", "place", "promenade", "quai", "ruelle", "allee", "faubourg", "esplanade", "montee", "clos", "square", "via", "viale", "vicolo", "piazza", "piazzetta", "strada", "sentiero", "corso", "salita", "riva", ]); const GERMAN_SUFFIXES = /^(.{4,}?)(strasse|weg|gasse|platz)$/; const MULTI_WAY_TYPE_PREFIXES = [ ["zone", "industrielle"], ["zone", "artisanale"], ["zone", "commerciale"], ["zona", "industriale"], ["zona", "artigianale"], ]; function stemKey(key) { const tokens = key.split(" "); let rest = null; const first = tokens[0]; for (const prefix of MULTI_WAY_TYPE_PREFIXES) { if (tokens.length > prefix.length && prefix.every((word, i) => tokens[i] === word)) { rest = tokens.slice(prefix.length); break; } } if (!rest && tokens.length >= 2 && first !== undefined && WAY_TYPE_WORDS.has(first)) { rest = tokens.slice(1); } else if (tokens.length === 1 && first !== undefined) { const m = first.match(GERMAN_SUFFIXES); if (m && m[1] !== undefined) rest = [m[1]]; } if (!rest || rest.length === 0) return null; const cleaned = rest.filter((t) => !ARTICLES.has(t)).map((t) => t.replace(/^[ld]'/, "")); const stem = (cleaned.length > 0 ? cleaned : rest).join(" "); return stem.length >= 3 ? stem : null; } const ROUTE_DESIGNATION = /^[AENHT] ?\d{1,3}[a-z]?$/i; function isRouteDesignation(name) { const parts = name.split(/\s*[-/|]\s*/).filter((p) => p.length > 0); return parts.length > 0 && parts.every((part) => ROUTE_DESIGNATION.test(part.trim())); } function bareStem(key) { const stem = key .split(" ") .filter((token) => !ARTICLES.has(token)) .map((token) => token.replace(/^[ld]'/, "")) .join(" "); return stem.length >= 3 ? stem : null; } function stripArticles(key) { const tokens = key .split(" ") .filter((token) => !ARTICLES.has(token)) .map((token) => token.replace(/^[ld]'/, "")); if (tokens.length < 2) return null; const stripped = tokens.join(" "); return stripped === key ? null : stripped; } function k2(name) { let s = k1(name); s = foldAccents(s); s = s.replace(/(\p{L}{2,})str\.?(?=$|\s|-)/gu, "$1strasse"); s = s.replace(/\b(\p{L})\. ?(\p{L})\.(?=\s|$)/gu, "$1$2"); s = s.replace(/-/g, " "); s = s.replace(/\s+/g, " ").trim(); const tokens = s.split(" ").filter((t) => t.length > 0); let variants = [[]]; tokens.forEach((token, i) => { const bare = token.replace(/\./g, ""); const rule = ABBREV_MAP.get(bare); const options = rule && (!rule.firstTokenOnly || i === 0) ? rule.expansions : [bare]; variants = variants .flatMap((v) => options.map((option) => [...v, option])) .slice(0, MAX_VARIANTS); }); const keys = [...new Set(variants.map((v) => v.join(" ")))]; for (const key of [...keys]) { const stripped = stripArticles(key); if (stripped && !keys.includes(stripped)) keys.push(stripped); } return keys; } const PREFIX$1 = "[CH Names]"; const log$1 = { info: (...args) => console.log(PREFIX$1, ...args), warn: (...args) => console.warn(PREFIX$1, ...args), error: (...args) => console.error(PREFIX$1, ...args), }; const BASE_URL = IDENTIFY_URL; const LAYER_ID$1 = "ch.swisstopo.amtliches-strassenverzeichnis"; const MAX_PAGES_PER_TILE$1 = 15; function extractLines(geometry) { const g = geometry; if (!g || typeof g !== "object") return null; switch (g.type) { case "LineString": return Array.isArray(g.coordinates) ? [g.coordinates] : null; case "MultiLineString": return Array.isArray(g.coordinates) ? g.coordinates : null; case "GeometryCollection": { const lines = (g.geometries ?? []).flatMap((sub) => extractLines(sub) ?? []); return lines.length > 0 ? lines : null; } default: return null; } } function parseAttributes(attrs, geometry) { if (!attrs) return null; const esid = Number(attrs["str_esid"]); const label = attrs["stn_label"]; if (typeof label !== "string" || label.trim() === "" || !Number.isFinite(esid)) return null; const official = attrs["str_official"]; return { esid, label: label.trim(), zipLabel: String(attrs["zip_label"] ?? ""), comName: String(attrs["com_name"] ?? ""), comFosnr: Number(attrs["com_fosnr"] ?? 0), official: official === 1 || official === true || official === "true", status: String(attrs["str_status"] ?? ""), type: String(attrs["str_type"] ?? ""), lines: extractLines(geometry), }; } const FIND_URL = "https://api3.geo.admin.ch/rest/services/api/MapServer/find"; async function findStreetLinesByName(name, signal, limiter = rateLimiter) { const lines = []; for (let page = 0; page < MAX_PAGES_PER_TILE$1; page++) { await limiter.acquire(); if (signal?.aborted) throw new DOMException("Scan aborted", "AbortError"); const params = new URLSearchParams({ layer: LAYER_ID$1, searchField: "stn_label", searchText: name, contains: "false", returnGeometry: "true", geometryFormat: "geojson", sr: "4326", limit: String(PAGE_SIZE), offset: String(page * PAGE_SIZE), }); const data = (await httpGetJson(`${FIND_URL}?${params.toString()}`, signal)); const results = data.results ?? []; for (const r of results) lines.push(...(extractLines(r.geometry) ?? [])); if (results.length < PAGE_SIZE) break; } return lines.length > 0 ? lines : null; } async function fetchOfficialStreets(bbox, signal, limiter = rateLimiter) { const out = []; for (let page = 0; page < MAX_PAGES_PER_TILE$1; page++) { await limiter.acquire(); if (signal?.aborted) throw new DOMException("Scan aborted", "AbortError"); const params = new URLSearchParams({ geometryType: "esriGeometryEnvelope", geometry: bbox.join(","), sr: "4326", layers: `all:${LAYER_ID$1}`, tolerance: "0", returnGeometry: "true", geometryFormat: "geojson", limit: String(PAGE_SIZE), offset: String(page * PAGE_SIZE), }); const data = (await httpGetJson(`${BASE_URL}?${params.toString()}`, signal)); const results = data.results ?? []; for (const r of results) { const street = parseAttributes(r.properties ?? r.attributes, r.geometry); if (street) out.push(street); } if (results.length < PAGE_SIZE) return { streets: out, truncated: false }; } log$1.warn(`Page cap (${MAX_PAGES_PER_TILE$1}) reached for bbox ${bbox.join(",")}; results truncated`); return { streets: out, truncated: true }; } const TILE_SIZE_DEG = 0.02; const CACHE_MAX_TILES$1 = 120; const CACHE_TTL_MS$1 = 24 * 60 * 60 * 1000; function tileKeysForBbox$1(bbox) { const [minLon, minLat, maxLon, maxLat] = bbox; const x0 = Math.floor(minLon / TILE_SIZE_DEG); const x1 = Math.floor(maxLon / TILE_SIZE_DEG); const y0 = Math.floor(minLat / TILE_SIZE_DEG); const y1 = Math.floor(maxLat / TILE_SIZE_DEG); const keys = []; for (let x = x0; x <= x1; x++) { for (let y = y0; y <= y1; y++) { keys.push(`${x}:${y}`); } } return keys; } function tileKeyForPoint(lon, lat) { return `${Math.floor(lon / TILE_SIZE_DEG)}:${Math.floor(lat / TILE_SIZE_DEG)}`; } function tileKeyToBbox$1(key) { const [xs, ys] = key.split(":"); const x = Number(xs); const y = Number(ys); return [ x * TILE_SIZE_DEG, y * TILE_SIZE_DEG, (x + 1) * TILE_SIZE_DEG, (y + 1) * TILE_SIZE_DEG, ]; } let TileCache$1 = class TileCache { constructor(maxTiles = CACHE_MAX_TILES$1, ttlMs = CACHE_TTL_MS$1, now = Date.now) { this.maxTiles = maxTiles; this.ttlMs = ttlMs; this.now = now; this.slots = new Map(); } get(key) { const slot = this.slots.get(key); if (!slot) return null; if (this.now() - slot.fetchedAt > this.ttlMs) { this.slots.delete(key); return null; } this.slots.delete(key); this.slots.set(key, slot); return slot; } set(key, entries, truncated = false, fetchedAt = this.now()) { this.slots.delete(key); this.slots.set(key, { entries, truncated, fetchedAt }); while (this.slots.size > this.maxTiles) { const oldest = this.slots.keys().next().value; if (oldest === undefined) break; this.slots.delete(oldest); } } clear() { this.slots.clear(); } }; class TileFetcher { constructor(cache = new TileCache$1(), fetchTile = fetchOfficialStreets, persistent = null) { this.cache = cache; this.fetchTile = fetchTile; this.persistent = persistent; void this.persistent?.prune(CACHE_TTL_MS$1); } async fetchBbox(bbox, signal, onProgress) { return this.fetchTiles(tileKeysForBbox$1(bbox), signal, onProgress); } async fetchTiles(keys, signal, onProgress) { let done = 0; onProgress?.(0, keys.length); const perTile = await Promise.all(keys.map(async (key) => { const result = await this.resolveTile(key, signal); done++; onProgress?.(done, keys.length); return { key, ...result }; })); const byEsid = new Map(); const truncatedKeys = []; const failedKeys = []; for (const tile of perTile) { for (const e of tile.entries) byEsid.set(e.esid, e); if (tile.truncated) truncatedKeys.push(tile.key); if (tile.failed) failedKeys.push(tile.key); } return { streets: [...byEsid.values()], truncatedKeys, failedKeys }; } async resolveTile(key, signal) { const cached = this.cache.get(key); if (cached) return { ...cached, failed: false }; const persisted = await this.persistent?.get(key); if (persisted && Date.now() - persisted.fetchedAt <= CACHE_TTL_MS$1) { const truncated = persisted.truncated ?? false; this.cache.set(key, persisted.entries, truncated, persisted.fetchedAt); return { entries: persisted.entries, truncated, failed: false }; } try { const { streets, truncated } = await this.fetchTile(tileKeyToBbox$1(key), signal); this.cache.set(key, streets, truncated); void this.persistent?.set({ key, entries: streets, truncated, fetchedAt: Date.now() }); return { entries: streets, truncated, failed: false }; } catch (err) { if (err instanceof DOMException && err.name === "AbortError") throw err; log$1.warn(`Tile ${key} failed to load; its segments will be skipped`, err); return { entries: [], truncated: false, failed: true }; } } clearAll() { this.cache.clear(); void this.persistent?.clear(); } } const i18n$1 = instance.createInstance(); void i18n$1.init({ lng: "en", fallbackLng: "en", resources: { en: { common: enCommon }, fr: { common: frCommon }, it: { common: itCommon }, de: { common: deCommon }, }, interpolation: { escapeValue: false }, }); const LANGUAGE_CHOICES$1 = [ { value: "auto", label: "Auto (WME)" }, { value: "en", label: "English" }, { value: "fr", label: "Français" }, { value: "de", label: "Deutsch" }, { value: "it", label: "Italiano" }, ]; const SUPPORTED$1 = ["en", "fr", "de", "it"]; function normalize$1(code) { const prefix = (code ?? "en").toLowerCase().slice(0, 2); return SUPPORTED$1.includes(prefix) ? prefix : "en"; } function setLocale$1(code) { void i18n$1.changeLanguage(code); } function getLocale() { return normalize$1(i18n$1.language); } function resolveLocale$1(preference, wmeLocaleCode) { if (preference !== "auto") return preference; return normalize$1(wmeLocaleCode); } function t$1(key, params) { return i18n$1.t(`common:streetCheck.${key}`, params); } function damerauLevenshtein(a, b, maxDist) { if (a === b) return 0; const la = a.length; const lb = b.length; if (Math.abs(la - lb) > maxDist) return maxDist + 1; if (la === 0) return lb; if (lb === 0) return la; let prevPrev = new Array(lb + 1).fill(0); let prev = new Array(lb + 1); let curr = new Array(lb + 1).fill(0); for (let j = 0; j <= lb; j++) prev[j] = j; for (let i = 1; i <= la; i++) { curr[0] = i; let rowMin = curr[0]; for (let j = 1; j <= lb; j++) { const cost = a[i - 1] === b[j - 1] ? 0 : 1; let v = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost); if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { v = Math.min(v, prevPrev[j - 2] + 1); } curr[j] = v; if (v < rowMin) rowMin = v; } if (rowMin > maxDist) return maxDist + 1; [prevPrev, prev, curr] = [prev, curr, prevPrev]; } const result = prev[lb]; return result > maxDist ? maxDist + 1 : result; } function queryStem(primaryK2Key) { return stemKey(primaryK2Key) ?? bareStem(primaryK2Key); } function compareNameToCandidate(query, candidate) { if (k0(query) === k0(candidate)) return "exact"; if (k1(query) === k1(candidate)) return "cosmetic"; const queryKeys = k2(query); const candidateKeys = k2(candidate); if (queryKeys.some((key) => candidateKeys.includes(key))) return "variant"; const q = queryKeys[0]; const c = candidateKeys[0]; if (q && c) { const maxDist = q.length < 8 ? 1 : 2; if (damerauLevenshtein(q, c, maxDist) <= maxDist) return "near"; if (stemKey(q) || stemKey(c)) { const qs = queryStem(q); const cs = queryStem(c); if (qs && cs && qs === cs) return "stem"; } } return null; } function localityFromZipLabel(zipLabel) { return k1(zipLabel.replace(/^\d{4}\s*/, "")); } function isExistingStatus(status) { const s = status.toLowerCase(); return s === "bestehend" || s === "real" || s === "existing"; } function rankScore(entry, locality) { let score = 0; if (entry.street.official) score += 8; if (isExistingStatus(entry.street.status)) score += 4; const t = entry.street.type.toLowerCase(); if (t !== "benanntes gebiet" && t !== "area") score += 2; if (locality && entry.locality === locality) score += 1; return score; } function pushTo(map, key, entry) { const list = map.get(key); if (list) list.push(entry); else map.set(key, [entry]); } const FUZZY_LENGTH_SLACK = 2; function otherLanguageLabels(label, primary) { if (!label.includes("/")) return []; return label .split("/") .map((p) => p.trim()) .filter(Boolean) .filter((p) => k1(p) !== k1(primary)); } class OfficialIndex { constructor(streets) { this.byK0 = new Map(); this.byK1 = new Map(); this.byK2 = new Map(); this.fuzzyBuckets = new Map(); this.byStem = new Map(); this.all = []; let entries = 0; for (const street of streets) { const locality = localityFromZipLabel(street.zipLabel); const parts = street.label.includes("/") ? [street.label, ...street.label.split("/").map((p) => p.trim()).filter(Boolean)] : [street.label]; parts.forEach((namePart, i) => { const entry = { street, namePart, isSlashPart: i > 0, locality, }; entries++; this.all.push(entry); pushTo(this.byK0, k0(namePart), entry); pushTo(this.byK1, k1(namePart), entry); const k2Keys = k2(namePart); for (const key of k2Keys) pushTo(this.byK2, key, entry); const primary = k2Keys[0]; if (primary && primary.length > 0) { const bucketKey = primary[0]; const bucket = this.fuzzyBuckets.get(bucketKey); const candidate = { entry, key: primary }; if (bucket) bucket.push(candidate); else this.fuzzyBuckets.set(bucketKey, [candidate]); const stem = stemKey(primary); if (stem) pushTo(this.byStem, stem, entry); } }); } this.entryCount = entries; this.streetCount = streets.length; } get list() { return this.all; } lookup(name, locality) { const exact = this.byK0.get(k0(name)); if (exact) return this.result("exact", exact, locality); const cosmetic = this.byK1.get(k1(name)); if (cosmetic) return this.result("cosmetic", cosmetic, locality); const k2Keys = k2(name); for (const key of k2Keys) { const variant = this.byK2.get(key); if (variant) return this.result("variant", variant, locality); } return this.fuzzyLookup(k2Keys, locality) ?? this.stemLookup(k2Keys, locality); } stemLookup(k2Keys, locality) { const primary = k2Keys[0]; if (!primary) return null; const stem = queryStem(primary); if (!stem) return null; const candidates = this.byStem.get(stem); if (!candidates) return null; const distinctNames = new Set(candidates.map((c) => k1(c.namePart))); if (distinctNames.size !== 1) return null; return this.result("stem", candidates, locality); } fuzzyLookup(k2Keys, locality) { const queryKey = k2Keys[0]; if (!queryKey || queryKey.length < 3) return null; const maxDist = queryKey.length < 8 ? 1 : 2; const bucket = this.fuzzyBuckets.get(foldAccents(queryKey[0])) ?? []; let best = maxDist + 1; const matchesByKey = new Map(); for (const { entry, key } of bucket) { if (Math.abs(key.length - queryKey.length) > FUZZY_LENGTH_SLACK) continue; const d = damerauLevenshtein(queryKey, key, maxDist); if (d > maxDist || d === 0) continue; if (d < best) { best = d; matchesByKey.clear(); } if (d === best) pushTo(matchesByKey, key, entry); } if (best > maxDist) return null; if (matchesByKey.size !== 1) return null; const candidates = [...matchesByKey.values()][0]; const result = this.result("near", candidates, locality); result.distance = best; return result; } result(level, candidates, locality) { const sorted = [...candidates].sort((a, b) => rankScore(b, locality) - rankScore(a, locality)); return { level, entry: sorted[0], candidates: sorted, inLocality: locality ? sorted.some((c) => c.locality === locality) : true, }; } } const M_PER_DEG_LAT = 110_574; const M_PER_DEG_LON_EQUATOR = 111_320; const GRID_DEG = 0.001; const NEAR_STREET_M = 25; const SUGGEST_MAX_M = 20; const FAR_STREET_M = 40; const MAX_BEARING_DIFF_RAD = (35 * Math.PI) / 180; const MIN_COVERAGE = 0.6; const CONTEST_MARGIN_M = 5; const WRONG_STREET_MIN_COVERAGE = 0.8; function distancePointToSegmentM(p, a, b) { const lonScale = M_PER_DEG_LON_EQUATOR * Math.cos((p[1] * Math.PI) / 180); const px = p[0] * lonScale; const py = p[1] * M_PER_DEG_LAT; const ax = a[0] * lonScale; const ay = a[1] * M_PER_DEG_LAT; const bx = b[0] * lonScale; const by = b[1] * M_PER_DEG_LAT; const dx = bx - ax; const dy = by - ay; const lengthSq = dx * dx + dy * dy; let t = 0; if (lengthSq > 0) { t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / lengthSq)); } const cx = ax + t * dx; const cy = ay + t * dy; return Math.hypot(px - cx, py - cy); } function bearingOf(a, b) { const lonScale = Math.cos((a[1] * Math.PI) / 180); const dx = (b[0] - a[0]) * lonScale; const dy = b[1] - a[1]; const angle = Math.atan2(dy, dx); return ((angle % Math.PI) + Math.PI) % Math.PI; } function bearingDiff(b1, b2) { const d = Math.abs(b1 - b2) % Math.PI; return Math.min(d, Math.PI - d); } class SpatialIndex { constructor(entries) { this.grid = new Map(); let count = 0; for (const entry of entries) { if (entry.isSlashPart) continue; const lines = entry.street.lines; if (!lines) continue; for (const line of lines) { for (let i = 0; i + 1 < line.length; i++) { const a = line[i]; const b = line[i + 1]; count++; const seg = { entry, a, b, bearing: bearingOf(a, b) }; const x0 = Math.floor(Math.min(a[0], b[0]) / GRID_DEG); const x1 = Math.floor(Math.max(a[0], b[0]) / GRID_DEG); const y0 = Math.floor(Math.min(a[1], b[1]) / GRID_DEG); const y1 = Math.floor(Math.max(a[1], b[1]) / GRID_DEG); for (let x = x0; x <= x1; x++) { for (let y = y0; y <= y1; y++) { const key = `${x}:${y}`; const cell = this.grid.get(key); if (cell) cell.push(seg); else this.grid.set(key, [seg]); } } } } } this.size = count; } candidatesAt(point, maxMeters, bearing) { const cx = Math.floor(point[0] / GRID_DEG); const cy = Math.floor(point[1] / GRID_DEG); const byEsid = new Map(); for (let x = cx - 1; x <= cx + 1; x++) { for (let y = cy - 1; y <= cy + 1; y++) { for (const seg of this.grid.get(`${x}:${y}`) ?? []) { if (bearing !== undefined && bearingDiff(seg.bearing, bearing) > MAX_BEARING_DIFF_RAD) { continue; } const d = distancePointToSegmentM(point, seg.a, seg.b); if (d > maxMeters) continue; const esid = seg.entry.street.esid; const known = byEsid.get(esid); if (!known || d < known.distanceM) byEsid.set(esid, { entry: seg.entry, distanceM: d }); } } } return byEsid; } } const SAMPLE_FRACTIONS = [0.1, 0.3, 0.5, 0.7, 0.9]; function sampleWithBearings(geometry) { const coords = geometry.coordinates; if (coords.length === 0) return []; if (coords.length === 1) return [{ point: coords[0], bearing: null }]; const lonScale = Math.cos((coords[0][1] * Math.PI) / 180); const planar = (a, b) => Math.hypot((b[0] - a[0]) * lonScale, b[1] - a[1]); const cumulative = [0]; for (let i = 1; i < coords.length; i++) { cumulative.push(cumulative[i - 1] + planar(coords[i - 1], coords[i])); } const total = cumulative[cumulative.length - 1]; if (total === 0) return [{ point: coords[0], bearing: null }]; const fractions = coords.length === 2 ? [0.5] : SAMPLE_FRACTIONS; return fractions.map((fraction) => { const target = fraction * total; let i = 1; while (i < cumulative.length - 1 && cumulative[i] < target) i++; const before = cumulative[i - 1]; const stepLength = cumulative[i] - before; const t = stepLength > 0 ? (target - before) / stepLength : 0; const a = coords[i - 1]; const b = coords[i]; return { point: [ a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, ], bearing: stepLength > 0 || planar(a, b) > 0 ? bearingOf(a, b) : null, }; }); } function samplePoints(geometry) { return sampleWithBearings(geometry).map((sample) => sample.point); } function nearestOfficial(geometry, index, maxMeters = NEAR_STREET_M) { const samples = sampleWithBearings(geometry); if (samples.length === 0) return null; const tallies = new Map(); for (const sample of samples) { const candidates = index.candidatesAt(sample.point, maxMeters, sample.bearing ?? undefined); let best = null; for (const [esid, { entry, distanceM }] of candidates) { let tally = tallies.get(esid); if (!tally) { tally = { entry, wins: 0, presence: 0, minD: Infinity }; tallies.set(esid, tally); } tally.presence++; tally.minD = Math.min(tally.minD, distanceM); if (!best || distanceM < best.d) best = { esid, d: distanceM }; } if (best) tallies.get(best.esid).wins++; } let winner = null; for (const tally of tallies.values()) { if (!winner || tally.wins > winner.wins || (tally.wins === winner.wins && tally.minD < winner.minD)) { winner = tally; } } if (!winner || winner.wins === 0) return null; const coverage = winner.wins / samples.length; if (coverage < MIN_COVERAGE) return null; let runnerUpMarginM = null; for (const tally of tallies.values()) { if (tally === winner) continue; if (tally.presence < 2) continue; const margin = tally.minD - winner.minD; if (margin < CONTEST_MARGIN_M) return null; if (runnerUpMarginM === null || margin < runnerUpMarginM) runnerUpMarginM = margin; } return { entry: winner.entry, distanceM: winner.minD, coverage, runnerUpMarginM }; } function distanceToLinesM(geometry, lines) { let min = Infinity; for (const point of samplePoints(geometry)) { for (const line of lines) { for (let i = 0; i + 1 < line.length; i++) { min = Math.min(min, distancePointToSegmentM(point, line[i], line[i + 1])); } } } return min; } function distanceToEntryM(geometry, entry) { const lines = entry.street.lines; if (!lines) return Infinity; return distanceToLinesM(geometry, lines); } function issueKey(issue) { return `${issue.segmentId} ${issue.status} ${issue.currentName ?? ""}`; } const HIGHWAY_ROAD_TYPES = new Set([3, 4, 6, 7]); function noteFor(entry) { const note = {}; if (!entry.street.official) note.unofficial = true; const status = entry.street.status.toLowerCase(); if (status !== "" && status !== "bestehend" && status !== "real" && status !== "existing") { note.planned = true; } if (entry.isSlashPart) note.fullLabel = entry.street.label; return Object.keys(note).length > 0 ? note : null; } function altPresenceSet(address) { const set = new Set(); for (const alt of address.altStreets) { const name = alt.street?.name?.trim(); if (name) set.add(k1(name)); } return set; } function evaluateSegment(segment, address, index, settings, nearest = null, swissCountryId = null) { if (!settings.checkedRoadTypes.includes(segment.roadType)) return { kind: "skipped" }; if (swissCountryId !== null && address.country && address.country.id !== swissCountryId) { return { kind: "skipped" }; } const currentName = address.street?.name?.trim() || null; const baseIssue = { segmentId: segment.id, currentName, cityId: address.city?.id ?? null, cityName: address.city?.name ?? null, cantonName: address.state?.name ?? null, roadType: segment.roadType, length: segment.length, geometry: segment.geometry, }; if (!currentName) { if (segment.junctionId !== null) return { kind: "skipped" }; const suggestion = nearest && nearest.distanceM <= SUGGEST_MAX_M ? nearest.entry : null; const status = suggestion === null && settings.geometryMatching ? "UNNAMED_NO_MATCH" : "UNNAMED"; return { kind: "issue", issue: { ...baseIssue, status, suggestion: suggestion?.namePart ?? null, note: suggestion ? noteFor(suggestion) : null, fixable: suggestion !== null, }, }; } if (HIGHWAY_ROAD_TYPES.has(segment.roadType) && isRouteDesignation(currentName)) { return { kind: "ok" }; } const locality = settings.cityScoping !== "off" && address.city?.name ? k1(address.city.name) : undefined; const match = index.lookup(currentName, locality); if (match) { const ownDistanceM = nearest && nearest.distanceM <= SUGGEST_MAX_M ? Math.min(...match.candidates.map((c) => distanceToEntryM(segment.geometry, c))) : Infinity; const ownAxisIsFar = Number.isFinite(ownDistanceM) && ownDistanceM > FAR_STREET_M; const currentNameK1 = k1(currentName); const labelHasCurrentName = nearest ? nearest.entry.street.label.split("/").some((part) => k1(part) === currentNameK1) : false; if (nearest && nearest.distanceM <= SUGGEST_MAX_M && nearest.coverage >= WRONG_STREET_MIN_COVERAGE && k1(nearest.entry.namePart) !== currentNameK1 && !labelHasCurrentName && ownAxisIsFar) { return { kind: "issue", issue: { ...baseIssue, status: "WRONG_STREET", suggestion: nearest.entry.namePart, note: { ...(noteFor(nearest.entry) ?? {}), existsIn: match.entry.street.zipLabel, ...(Number.isFinite(ownDistanceM) ? { ownDistanceM: Math.round(ownDistanceM) } : {}), coverage: nearest.coverage, matchDistanceM: Math.round(nearest.distanceM), ...(nearest.runnerUpMarginM !== null ? { runnerUpMarginM: Math.round(nearest.runnerUpMarginM) } : {}), }, fixable: true, }, }; } const e = match.entry; if (e.street.label.includes("/") && !e.isSlashPart) { const parts = e.street.label .split("/") .map((p) => p.trim()) .filter(Boolean); const present = altPresenceSet(address); const altLabels = parts.slice(1).filter((p) => !present.has(k1(p))); return { kind: "issue", issue: { ...baseIssue, status: "BILINGUAL", suggestion: parts[0] ?? e.namePart, note: { fullLabel: e.street.label, ...(altLabels.length > 0 ? { altLabels } : {}) }, fixable: true, }, }; } if (match.level === "exact") { if (locality && !match.inLocality) { return { kind: "issue", issue: { ...baseIssue, status: "WRONG_CITY", suggestion: null, note: { existsIn: match.entry.street.zipLabel }, fixable: false, }, }; } if (e.isSlashPart) { const present = altPresenceSet(address); const missing = otherLanguageLabels(e.street.label, e.namePart).filter((p) => !present.has(k1(p))); if (missing.length > 0) { return { kind: "issue", issue: { ...baseIssue, status: "BILINGUAL", suggestion: e.namePart, note: { fullLabel: e.street.label, altLabels: missing }, fixable: true, }, }; } } return { kind: "ok" }; } const statusByLevel = { cosmetic: "COSMETIC", variant: "VARIANT", near: "NEAR", stem: "WRONG_TYPE", }; return { kind: "issue", issue: { ...baseIssue, status: statusByLevel[match.level], suggestion: match.entry.namePart, note: noteFor(match.entry), fixable: true, }, }; } if (settings.altNameCountsAsOk) { for (const alt of address.altStreets) { const altName = alt.street?.name?.trim(); if (!altName) continue; const altMatch = index.lookup(altName, locality); if (altMatch && (altMatch.level === "exact" || altMatch.level === "cosmetic")) { return { kind: "okAlt" }; } } } if (nearest && nearest.distanceM <= SUGGEST_MAX_M) { const level = compareNameToCandidate(currentName, nearest.entry.namePart); if (level && level !== "exact") { const statusByLevel = { cosmetic: "COSMETIC", variant: "VARIANT", near: "NEAR", stem: "WRONG_TYPE", }; return { kind: "issue", issue: { ...baseIssue, status: statusByLevel[level], suggestion: nearest.entry.namePart, note: noteFor(nearest.entry), fixable: true, }, }; } } return { kind: "issue", issue: { ...baseIssue, status: "NOT_FOUND", suggestion: null, note: null, fixable: false, }, }; } const confirmDialog$1 = async (message) => { const result = await showWmeDialog({ message, buttons: [ { label: t$1("dialogConfirm"), value: "confirm" }, { label: t$1("dialogCancel"), value: "cancel" }, ], cancelValue: "cancel", }); return result === "confirm"; }; const notifyDialog$1 = async (message) => { await showWmeDialog({ message, buttons: [{ label: t$1("dialogOk"), value: "ok" }], cancelValue: "ok", }); }; const GROUP_FIX_CAP = 50; const GROUP_FIX_CONFIRM_THRESHOLD = 20; const GROUP_FIX_MIN_RANK = 2; const LOCK_STATUSES = new Set(["UNDER_LOCK", "OVER_LOCK"]); const GEOMETRY_STATUSES = new Set(["WRONG_STREET"]); function canGroupFix(sdk) { const userRank = sdk.State.getUserInfo()?.rank; return typeof userRank === "number" && userRank >= GROUP_FIX_MIN_RANK; } function formatFixError(outcome) { if (outcome.errorCode) return t$1(outcome.errorCode); return outcome.errorDetail ?? "?"; } function findOrCreateStreet(sdk, streetName, cityId) { const existing = sdk.DataModel.Streets.getStreet({ streetName, cityId }); if (existing) return existing; try { return sdk.DataModel.Streets.addStreet({ streetName, cityId }); } catch { return sdk.DataModel.Streets.getStreet({ streetName, cityId }); } } function fixSegment(sdk, issue, settings) { const segmentId = issue.segmentId; const fail = (errorCode) => ({ segmentId, ok: false, errorCode }); if (LOCK_STATUSES.has(issue.status)) return fixLock(sdk, issue); if (!issue.fixable || !issue.suggestion) return fail("errNotFixable"); if (!sdk.Editing.isEditingAllowed()) return fail("errEditingNotAllowed"); try { const segment = sdk.DataModel.Segments.getById({ segmentId }); if (!segment) return fail("errSegmentUnloaded"); const address = sdk.DataModel.Segments.getAddress({ segmentId }); const cityId = address.city?.id; if (cityId == null) return fail("errNoCity"); const street = findOrCreateStreet(sdk, issue.suggestion, cityId); if (!street) return fail("errStreetCreate"); const alternateStreetIds = [...segment.alternateStreetIds]; if (settings.keepOldNameAsAlt && issue.status !== "NEAR" && segment.primaryStreetId != null && segment.primaryStreetId !== street.id && !alternateStreetIds.includes(segment.primaryStreetId)) { alternateStreetIds.push(segment.primaryStreetId); } if (issue.note?.altLabels) { for (const name of issue.note.altLabels) { const alt = findOrCreateStreet(sdk, name, cityId); if (alt && alt.id !== street.id && !alternateStreetIds.includes(alt.id)) { alternateStreetIds.push(alt.id); } } } const primaryChanged = segment.primaryStreetId !== street.id; const altsChanged = alternateStreetIds.length !== segment.alternateStreetIds.length; if (!primaryChanged && !altsChanged) return { segmentId, ok: true }; sdk.DataModel.Segments.updateAddress({ segmentId, primaryStreetId: street.id, alternateStreetIds, }); return { segmentId, ok: true }; } catch (err) { log$1.error(`Fix failed for segment ${segmentId}`, err); return { segmentId, ok: false, errorDetail: err instanceof Error ? err.message : String(err), }; } } function fixLock(sdk, issue) { const segmentId = issue.segmentId; const fail = (errorCode) => ({ segmentId, ok: false, errorCode }); const expectedLevel = issue.note?.expectedLock; if (expectedLevel == null) return fail("errNotFixable"); if (!sdk.Editing.isEditingAllowed()) return fail("errEditingNotAllowed"); const userRank = sdk.State.getUserInfo()?.rank; if (typeof userRank === "number" && expectedLevel > userRank + 1) { return { segmentId, ok: false, errorDetail: t$1("errLockAboveRank", { expected: expectedLevel, user: userRank + 1 }), }; } try { const segment = sdk.DataModel.Segments.getById({ segmentId }); if (!segment) return fail("errSegmentUnloaded"); const targetRank = expectedLevel - 1; if (segment.lockRank === targetRank) return { segmentId, ok: true }; sdk.DataModel.Segments.updateSegment({ segmentId, lockRank: targetRank }); return { segmentId, ok: true }; } catch (err) { log$1.error(`Lock fix failed for segment ${segmentId}`, err); return { segmentId, ok: false, errorDetail: err instanceof Error ? err.message : String(err), }; } } async function fixGroup(sdk, issues, settings, onProgress) { const outcomes = []; const batch = issues.slice(0, GROUP_FIX_CAP); for (const issue of batch) { const outcome = fixSegment(sdk, issue, settings); outcomes.push(outcome); onProgress?.(outcomes.length, batch.length); if (!outcome.ok) break; await new Promise((resolve) => setTimeout(resolve, 0)); } return outcomes; } let fixInFlight = false; function isFixInFlight() { return fixInFlight; } async function withFixLock(fn) { if (fixInFlight) return null; fixInFlight = true; try { return await fn(); } finally { fixInFlight = false; } } async function runFix(sdk, issue, settings, { button, onComplete, confirm = confirmDialog$1, notify = notifyDialog$1 } = {}) { if (issue.status === "OVER_LOCK" && !(await confirm(t$1("confirmOverLockFix", { n: issue.note?.expectedLock ?? "" })))) { return; } if (GEOMETRY_STATUSES.has(issue.status)) { const detail = issue.note?.coverage !== undefined ? `\n${t$1("noteMatchConfidence", { pct: Math.round(issue.note.coverage * 100), m: issue.note.matchDistanceM ?? 0, })}` : ""; const confirmed = await confirm(t$1("confirmWrongStreetFix", { current: issue.currentName ?? "", suggestion: issue.suggestion ?? "", }) + detail); if (!confirmed) return; } const result = await withFixLock(async () => { if (button) { button.disabled = true; button.textContent = "…"; } const outcome = fixSegment(sdk, issue, settings); if (!outcome.ok) await notify(t$1("fixFailed", { error: formatFixError(outcome) })); return outcome; }); if (result !== null) onComplete?.(); } async function runFixGroup(sdk, issues, header, settings, { button, onComplete, confirm = confirmDialog$1, notify = notifyDialog$1 } = {}) { if (!canGroupFix(sdk)) { await notify(t$1("errGroupFixRank", { level: GROUP_FIX_MIN_RANK + 1 })); return; } const n = Math.min(issues.length, GROUP_FIX_CAP); if (header.status === "OVER_LOCK") { if (!(await confirm(t$1("confirmOverLockFix", { n: header.expectedLock ?? "" })))) return; } else if ((GEOMETRY_STATUSES.has(header.status) || n > GROUP_FIX_CONFIRM_THRESHOLD) && !(await confirm(t$1("confirmGroupFixDetailed", { n, current: header.currentName ?? "", suggestion: header.suggestion ?? "", })))) { return; } const result = await withFixLock(async () => { if (button) button.disabled = true; const outcomes = await fixGroup(sdk, issues, settings, (done, total) => { if (button) button.textContent = `${done}/${total}…`; }); const failed = outcomes.find((o) => !o.ok); if (failed) { await notify(t$1("fixStopped", { done: outcomes.filter((o) => o.ok).length, total: n, error: formatFixError(failed), id: failed.segmentId, })); } return outcomes; }); if (result !== null) onComplete?.(); } function ignoreIssue(settings, issue, onComplete) { const keys = settings.get().ignoredKeys; const key = issueKey(issue); if (!keys.includes(key)) settings.update({ ignoredKeys: [...keys, key] }); onComplete?.(); } async function ignoreIssues(settings, issues, onComplete, confirm = confirmDialog$1) { if (issues.length > GROUP_FIX_CONFIRM_THRESHOLD && !(await confirm(t$1("confirmIgnoreAll", { n: issues.length })))) { return; } const keys = new Set(settings.get().ignoredKeys); for (const issue of issues) keys.add(issueKey(issue)); settings.update({ ignoredKeys: [...keys] }); onComplete?.(); } const MIN_SEGMENT_LENGTH_M = 5; const MIN_NARROW_STREET_LENGTH_M = 50; const NARROW_STREET_TYPE = 22; const DRIVABLE_TYPES = new Set([1, 2, 3, 4, 6, 7, 8, 17, 20, 22]); const EXPECTED_LEVEL_BY_ROAD_TYPE = new Map([ [3, 5], [6, 4], [7, 3], [2, 2], [1, 1], ]); const ROUNDABOUT_MIN_LEVEL = 3; function makeIssue(segment, status, getAddress, swissCountryId) { const address = getAddress(segment.id); if (swissCountryId !== null && address?.country && address.country.id !== swissCountryId) { return null; } return { segmentId: segment.id, status, currentName: address?.street?.name?.trim() || null, suggestion: null, note: null, cityId: address?.city?.id ?? null, cityName: address?.city?.name ?? null, cantonName: address?.state?.name ?? null, roadType: segment.roadType, length: segment.length, geometry: segment.geometry, fixable: false, }; } function isOneWay(segment) { return segment.isAtoB !== segment.isBtoA; } function evaluateGuidelines(segments, getAddress, swissCountryId = null, options = {}) { const { structural = true } = options; const issues = new Map(); const byNodePair = new Map(); for (const segment of segments) { if (!DRIVABLE_TYPES.has(segment.roadType)) continue; const isRoundabout = segment.junctionId !== null; if (structural && !isRoundabout && segment.length < MIN_SEGMENT_LENGTH_M) { const issue = makeIssue(segment, "MICRO_SEGMENT", getAddress, swissCountryId); if (issue) issues.set(segment.id, issue); } if (structural && segment.roadType === NARROW_STREET_TYPE && (isOneWay(segment) || segment.length < MIN_NARROW_STREET_LENGTH_M)) { if (!issues.has(segment.id)) { const issue = makeIssue(segment, "NARROW_MISUSE", getAddress, swissCountryId); if (issue) issues.set(segment.id, issue); } } const baseExpected = EXPECTED_LEVEL_BY_ROAD_TYPE.get(segment.roadType); const expectedLevel = isRoundabout ? Math.max(baseExpected ?? 0, ROUNDABOUT_MIN_LEVEL) : baseExpected; if (expectedLevel !== undefined && typeof segment.lockRank === "number" && !issues.has(segment.id)) { const currentLevel = segment.lockRank + 1; let status = null; if (currentLevel < expectedLevel) status = "UNDER_LOCK"; else if (currentLevel > expectedLevel && !isRoundabout) status = "OVER_LOCK"; if (status) { const issue = makeIssue(segment, status, getAddress, swissCountryId); if (issue) { issue.note = { ...(issue.note ?? {}), currentLock: currentLevel, expectedLock: expectedLevel }; issue.fixable = true; issues.set(segment.id, issue); } } } if (!structural) continue; if (isRoundabout || segment.fromNodeId === null || segment.toNodeId === null) continue; if (segment.fromNodeId === segment.toNodeId) { const issue = makeIssue(segment, "LOOP", getAddress, swissCountryId); if (issue) issues.set(segment.id, issue); continue; } const a = Math.min(segment.fromNodeId, segment.toNodeId); const b = Math.max(segment.fromNodeId, segment.toNodeId); const key = `${a}:${b}`; const list = byNodePair.get(key); if (list) list.push(segment); else byNodePair.set(key, [segment]); } for (const pair of byNodePair.values()) { if (pair.length < 2) continue; for (const segment of pair) { const issue = makeIssue(segment, "LOOP", getAddress, swissCountryId); if (issue) issues.set(segment.id, issue); } } return [...issues.values()]; } const CH_BBOX = [5.9, 45.8, 10.6, 47.9]; function intersectsSwitzerland(bbox) { return (bbox[0] <= CH_BBOX[2] && bbox[2] >= CH_BBOX[0] && bbox[1] <= CH_BBOX[3] && bbox[3] >= CH_BBOX[1]); } function isEditableByRank(lockRank, userRank) { return userRank === null || userRank >= lockRank; } const DEBOUNCE_MS = 800; const BBOX_PADDING_RATIO = 0.2; const MAX_AREA_KM2 = 6; const MAX_SWEEP_AREA_KM2 = 50; const SWEEP_BATCH_TILES = 6; const CONTINUATION_MAX_M = 3000; const CONTINUATION_ROAD_TYPES = new Set([2, 3, 6, 7]); const MAX_CONTINUATION_LOOKUPS_PER_RUN = 10; function padBbox(bbox) { const [minLon, minLat, maxLon, maxLat] = bbox; const padLon = (maxLon - minLon) * BBOX_PADDING_RATIO; const padLat = (maxLat - minLat) * BBOX_PADDING_RATIO; return [minLon - padLon, minLat - padLat, maxLon + padLon, maxLat + padLat]; } function bboxAreaKm2(bbox) { const [minLon, minLat, maxLon, maxLat] = bbox; const midLat = (minLat + maxLat) / 2; const widthKm = (maxLon - minLon) * 111.32 * Math.cos((midLat * Math.PI) / 180); const heightKm = (maxLat - minLat) * 110.57; return widthKm * heightKm; } function chunk(items, size) { const out = []; for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size)); return out; } class Scanner { constructor(sdk, fetcher, settings) { this.sdk = sdk; this.fetcher = fetcher; this.settings = settings; this.generation = 0; this.evalGeneration = 0; this.controller = null; this.lastIndex = null; this.lastSpatialIndex = null; this.coveredTiles = null; this.nameLinesCache = new Map(); this.listeners = []; this.snapshot = { state: "idle", issues: new Map(), nameConformIds: new Set(), stats: { ok: 0, okAlt: 0, skipped: 0, total: 0 }, officialStreetCount: 0, progress: null, sweep: null, sweepEligible: false, truncatedTileCount: 0, failedTileCount: 0, continuationLookupsExhausted: false, error: null, unsavedCount: 0, }; this.paused = false; this.sweepActive = false; this.suppressAutoScanUntil = 0; } start() { const onMove = () => { if (this.sweepActive) return; if (Date.now() < this.suppressAutoScanUntil) return; const s = this.settings.get(); if (!s.enabled || !s.autoScan) return; this.requestScan(); }; this.sdk.Events.on({ eventName: "wme-map-move-end", eventHandler: onMove }); this.sdk.Events.on({ eventName: "wme-map-data-loaded", eventHandler: onMove }); this.sdk.Events.on({ eventName: "wme-after-edit", eventHandler: () => this.reevaluate() }); this.sdk.Events.on({ eventName: "wme-save-finished", eventHandler: () => this.reevaluate() }); this.requestScan(); } suppressAutoScan(ms = 1500) { this.suppressAutoScanUntil = Date.now() + ms; } onUpdate(listener) { this.listeners.push(listener); } getSnapshot() { return this.snapshot; } setPaused(paused) { this.paused = paused; if (paused) { this.controller?.abort(); this.sweepActive = false; this.publish({ state: "paused", sweep: null }); } else { this.requestScan(); } } requestScan() { if (this.paused) return; clearTimeout(this.debounceTimer); this.debounceTimer = setTimeout(() => { void this.scan(); }, DEBOUNCE_MS); } rescan() { this.fetcher.clearAll(); this.lastIndex = null; this.lastSpatialIndex = null; this.coveredTiles = null; this.requestScan(); } disable() { this.controller?.abort(); clearTimeout(this.debounceTimer); this.sweepActive = false; this.publish({ state: "disabled", issues: new Map(), nameConformIds: new Set(), progress: null, sweep: null }); } reevaluate() { if (isFixInFlight()) return; if (this.sweepActive) return; clearTimeout(this.reevalTimer); this.reevalTimer = setTimeout(() => { const index = this.lastIndex; if (isFixInFlight() || this.paused || !this.settings.get().enabled || !index) return; void this.runEvaluation(index).then((completed) => { if (completed) this.publish({ state: "done" }); }); }, 300); } async scan() { if (this.paused) return; if (!this.settings.get().enabled) { this.disable(); return; } const gen = ++this.generation; this.controller?.abort(); const controller = new AbortController(); this.controller = controller; try { const zoom = this.sdk.Map.getZoomLevel(); if (zoom < this.settings.get().minZoom) { this.publish({ state: "zoom-gated", issues: new Map(), nameConformIds: new Set(), progress: null }); return; } const bbox = padBbox(this.sdk.Map.getMapExtent()); if (!intersectsSwitzerland(bbox)) { this.publish({ state: "outside-ch", issues: new Map(), nameConformIds: new Set(), progress: null }); return; } if (bboxAreaKm2(bbox) > MAX_AREA_KM2) { this.publish({ state: "area-gated", issues: new Map(), nameConformIds: new Set(), progress: null, sweepEligible: bboxAreaKm2(bbox) <= MAX_SWEEP_AREA_KM2, }); return; } this.publish({ state: "fetching", error: null, sweep: null }); const { streets, truncatedKeys, failedKeys } = await this.fetcher.fetchBbox(bbox, controller.signal, (done, total) => { if (gen === this.generation) this.publish({ progress: { done, total } }); }); if (gen !== this.generation) return; this.publish({ state: "evaluating", progress: null }); const index = new OfficialIndex(streets); this.lastIndex = index; this.lastSpatialIndex = new SpatialIndex(index.list); const failed = new Set(failedKeys); this.coveredTiles = new Set(tileKeysForBbox$1(bbox).filter((key) => !failed.has(key))); const completed = await this.runEvaluation(index); if (!completed || gen !== this.generation) return; this.publish({ state: "done", officialStreetCount: index.streetCount, truncatedTileCount: truncatedKeys.length, failedTileCount: failedKeys.length, }); } catch (err) { if (controller.signal.aborted || gen !== this.generation) return; log$1.error("Scan failed", err); this.publish({ state: "error", error: err instanceof Error ? err.message : String(err) }); } } async scanArea() { if (this.paused || this.sweepActive || !this.settings.get().enabled) return; clearTimeout(this.debounceTimer); const gen = ++this.generation; this.controller?.abort(); const controller = new AbortController(); this.controller = controller; this.sweepActive = true; try { if (this.sdk.Map.getZoomLevel() < this.settings.get().minZoom) { this.publish({ state: "zoom-gated", issues: new Map(), nameConformIds: new Set(), sweep: null }); return; } const bbox = padBbox(this.sdk.Map.getMapExtent()); if (!intersectsSwitzerland(bbox)) { this.publish({ state: "outside-ch", issues: new Map(), nameConformIds: new Set(), sweep: null }); return; } if (bboxAreaKm2(bbox) > MAX_SWEEP_AREA_KM2) { this.publish({ state: "area-gated", issues: new Map(), nameConformIds: new Set(), sweep: null, sweepEligible: false }); return; } const keys = tileKeysForBbox$1(bbox); const byEsid = new Map(); const covered = new Set(); let truncatedTileCount = 0; let failedTileCount = 0; let tilesDone = 0; this.publish({ state: "sweeping", error: null, progress: null, sweep: { tilesDone: 0, tilesTotal: keys.length }, }); const batches = chunk(keys, SWEEP_BATCH_TILES); for (let b = 0; b < batches.length; b++) { const batch = batches[b]; const result = await this.fetcher.fetchTiles(batch, controller.signal); if (gen !== this.generation) return; for (const street of result.streets) byEsid.set(street.esid, street); truncatedTileCount += result.truncatedKeys.length; failedTileCount += result.failedKeys.length; const failed = new Set(result.failedKeys); for (const key of batch) if (!failed.has(key)) covered.add(key); tilesDone += batch.length; const index = new OfficialIndex([...byEsid.values()]); this.lastIndex = index; this.lastSpatialIndex = new SpatialIndex(index.list); this.coveredTiles = covered; const isLast = b === batches.length - 1; const completed = await this.runEvaluation(index, isLast ? undefined : 0); if (!completed || gen !== this.generation) return; this.publish({ sweep: { tilesDone, tilesTotal: keys.length }, officialStreetCount: index.streetCount, truncatedTileCount, failedTileCount, }); } this.publish({ state: "done", sweep: null }); } catch (err) { if (controller.signal.aborted || gen !== this.generation) return; log$1.error("Area sweep failed", err); this.publish({ state: "error", sweep: null, error: err instanceof Error ? err.message : String(err), }); } finally { this.sweepActive = false; } } cancelSweep() { if (!this.sweepActive) return; this.generation++; this.controller?.abort(); this.sweepActive = false; this.publish({ state: "done", sweep: null }); } resolveSwissCountryId() { if (this.swissCountryId !== undefined) return this.swissCountryId; try { const swiss = this.sdk.DataModel.Countries.getAll().find((country) => { const abbr = (country.abbr ?? "").toUpperCase(); const name = (country.name ?? "").toLowerCase(); return (abbr === "CH" || abbr === "CHE" || name === "switzerland" || name === "schweiz" || name === "suisse" || name === "svizzera"); }); this.swissCountryId = swiss ? swiss.id : null; if (this.swissCountryId === null) { log$1.warn("Switzerland not found in the countries data model; country guard disabled"); } } catch { this.swissCountryId = null; } return this.swissCountryId; } async runEvaluation(index, continuationBudget = MAX_CONTINUATION_LOOKUPS_PER_RUN) { const gen = ++this.evalGeneration; if (!this.controller || this.controller.signal.aborted) { this.controller = new AbortController(); } const signal = this.controller.signal; const settings = this.settings.get(); const issues = new Map(); const nameConformIds = new Set(); const stats = { ok: 0, okAlt: 0, skipped: 0, total: 0 }; const addressCache = new Map(); const allSegments = this.sdk.DataModel.Segments.getAll(); const userRank = settings.editableOnly ? (this.sdk.State.getUserInfo()?.rank ?? null) : null; const segments = userRank === null ? allSegments : allSegments.filter((seg) => isEditableByRank(seg.lockRank, userRank)); const ignored = new Set(settings.ignoredKeys); const spatial = settings.geometryMatching ? this.lastSpatialIndex : null; const swissCountryId = this.resolveSwissCountryId(); for (let i = 0; i < segments.length; i++) { if (i > 0 && i % Scanner.EVAL_CHUNK === 0) { await new Promise((resolve) => setTimeout(resolve, 0)); if (gen !== this.evalGeneration) return false; } const segment = segments[i]; stats.total++; if (!this.isCovered(segment)) { stats.skipped++; continue; } if (!settings.checkedRoadTypes.includes(segment.roadType)) { stats.skipped++; continue; } let verdict; try { const address = this.sdk.DataModel.Segments.getAddress({ segmentId: segment.id }); addressCache.set(segment.id, address); const nearest = spatial ? nearestOfficial(segment.geometry, spatial) : null; verdict = evaluateSegment(segment, address, index, settings, nearest, swissCountryId); } catch { stats.skipped++; continue; } switch (verdict.kind) { case "ok": stats.ok++; nameConformIds.add(segment.id); break; case "okAlt": stats.okAlt++; nameConformIds.add(segment.id); break; case "skipped": stats.skipped++; break; case "issue": if (ignored.has(issueKey(verdict.issue))) { stats.skipped++; } else if (settings.enabledStatuses.includes(verdict.issue.status)) { issues.set(verdict.issue.segmentId, verdict.issue); } else { stats.skipped++; } break; } } const continuation = await this.reclassifyContinuations(issues, stats, gen, signal, continuationBudget, nameConformIds); if (!continuation.completed) return false; if (gen !== this.evalGeneration) return false; const lockEnabled = settings.enabledStatuses.includes("UNDER_LOCK") || settings.enabledStatuses.includes("OVER_LOCK"); if (settings.guidelineChecks || lockEnabled) { const getAddress = (segmentId) => { const cached = addressCache.get(segmentId); if (cached !== undefined) return cached; try { return this.sdk.DataModel.Segments.getAddress({ segmentId }); } catch { return null; } }; const guidelineIssues = evaluateGuidelines(segments, getAddress, swissCountryId, { structural: settings.guidelineChecks, }); for (const issue of guidelineIssues) { if (!issues.has(issue.segmentId) && settings.enabledStatuses.includes(issue.status) && !ignored.has(issueKey(issue))) { issues.set(issue.segmentId, issue); } } } this.publish({ issues, nameConformIds, stats, unsavedCount: this.safeUnsavedCount(), continuationLookupsExhausted: continuation.exhausted, }); return true; } async reclassifyContinuations(issues, stats, gen, signal, budget, nameConformIds) { let lookups = 0; let exhausted = false; for (const issue of [...issues.values()]) { if (issue.status !== "NOT_FOUND" || !issue.currentName) continue; if (!CONTINUATION_ROAD_TYPES.has(issue.roadType)) continue; let lines = this.nameLinesCache.get(issue.currentName); if (lines === undefined) { if (lookups >= budget) { exhausted = true; continue; } lookups++; try { lines = await findStreetLinesByName(issue.currentName, signal); } catch { continue; } if (gen !== this.evalGeneration) return { completed: false, exhausted }; this.nameLinesCache.set(issue.currentName, lines); } if (lines && distanceToLinesM(issue.geometry, lines) <= CONTINUATION_MAX_M) { issues.delete(issue.segmentId); stats.ok++; nameConformIds.add(issue.segmentId); } } return { completed: true, exhausted }; } isCovered(segment) { const covered = this.coveredTiles; if (!covered) return true; return segment.geometry.coordinates.some(([lon, lat]) => covered.has(tileKeyForPoint(lon, lat))); } safeUnsavedCount() { try { return this.sdk.Editing.getUnsavedChangesCount(); } catch { return 0; } } publish(partial) { this.snapshot = { ...this.snapshot, ...partial, unsavedCount: this.safeUnsavedCount() }; for (const listener of this.listeners) { try { listener(this.snapshot); } catch (err) { log$1.error("Listener failed", err); } } } } Scanner.EVAL_CHUNK = 250; const PREFIX = "[CH HN]"; const log = { info: (...args) => console.log(PREFIX, ...args), warn: (...args) => console.warn(PREFIX, ...args), error: (...args) => console.error(PREFIX, ...args), }; function distanceToSegmentM(coordinates, point) { let min = Infinity; for (let i = 0; i + 1 < coordinates.length; i++) { const distance = distancePointToSegmentM([point.lon, point.lat], coordinates[i], coordinates[i + 1]); if (distance < min) min = distance; } return min; } function readSegmentGeometries(sdk, segmentIds) { const geometries = new Map(); for (const segmentId of segmentIds) { try { const coordinates = sdk.DataModel.Segments.getById({ segmentId })?.geometry.coordinates; if (coordinates && coordinates.length > 1) geometries.set(segmentId, coordinates); } catch (err) { log.warn(`Could not read the geometry of segment ${segmentId}`, err); } } return geometries; } function assignToSegments(points, geometries, maxDistanceM) { const assignments = []; const unreachable = []; for (const point of points) { let best = null; for (const [segmentId, coordinates] of geometries) { const distanceM = distanceToSegmentM(coordinates, point); if (!best || distanceM < best.distanceM) best = { point, segmentId, distanceM }; } if (best && best.distanceM <= maxDistanceM) assignments.push(best); else unreachable.push(point); } return { assignments, unreachable }; } function countSegments(assignments) { return new Set(assignments.map((assignment) => assignment.segmentId)).size; } const LOOSE_MAX_DISTANCE = 2; function matchesSegmentStreet(gwrNames, segmentNames, strictness = "strict") { if (gwrNames.length === 0 || segmentNames.length === 0) return false; const segmentK1 = new Set(segmentNames.map(k1)); if (gwrNames.some((name) => segmentK1.has(k1(name)))) return true; const segmentK2 = new Set(segmentNames.flatMap(k2)); const gwrK2 = gwrNames.flatMap(k2); if (gwrK2.some((key) => segmentK2.has(key))) return true; if (strictness === "strict") return false; const segmentKeys = [...segmentK2]; return gwrK2.some((key) => segmentKeys.some((candidate) => damerauLevenshtein(key, candidate, LOOSE_MAX_DISTANCE) <= LOOSE_MAX_DISTANCE)); } function normalizeNumber(value) { return value.replace(/\s+/g, "").toUpperCase(); } function computeStatuses(input) { const { points, segmentNames, existingNumbers, strictness = "strict" } = input; if (!segmentNames || segmentNames.length === 0) { return points.map((point) => ({ point, status: "NEUTRAL" })); } return points.map((point) => { if (!matchesSegmentStreet(point.streetNames, segmentNames, strictness)) { return { point, status: "OTHER_STREET" }; } if (!existingNumbers) return { point, status: "NEUTRAL" }; const status = existingNumbers.has(normalizeNumber(point.number)) ? "PRESENT" : "MISSING"; return { point, status }; }); } function missingPoints(statused) { return statused .filter((entry) => entry.status === "MISSING") .map((entry) => entry.point) .sort((a, b) => compareHouseNumbers(a.number, b.number)); } function compareHouseNumbers(a, b) { const numericA = Number.parseInt(a, 10); const numericB = Number.parseInt(b, 10); if (Number.isFinite(numericA) && Number.isFinite(numericB) && numericA !== numericB) { return numericA - numericB; } return normalizeNumber(a).localeCompare(normalizeNumber(b)); } const NEIGHBOUR_PADDING_DEG = 0.0008; const MAX_SCOPED_SEGMENTS = 40; function segmentStreetNames(sdk, segmentId) { try { const address = sdk.DataModel.Segments.getAddress({ segmentId }); const names = [address.street?.name, ...address.altStreets.map((alt) => alt.street?.name)]; return names.filter((name) => typeof name === "string" && name.trim() !== ""); } catch (err) { log.warn(`Could not read the address of segment ${segmentId}`, err); return []; } } function bboxOfLine(coordinates) { if (coordinates.length === 0) return null; let minLon = Infinity; let minLat = Infinity; let maxLon = -Infinity; let maxLat = -Infinity; for (const [lon, lat] of coordinates) { if (lon < minLon) minLon = lon; if (lat < minLat) minLat = lat; if (lon > maxLon) maxLon = lon; if (lat > maxLat) maxLat = lat; } return [minLon, minLat, maxLon, maxLat]; } function intersects(a, b, padding) { const overlapsLon = a[0] - padding <= b[2] && a[2] + padding >= b[0]; const overlapsLat = a[1] - padding <= b[3] && a[3] + padding >= b[1]; return overlapsLon && overlapsLat; } function collectStreetScopedSegmentIds(sdk, selectedSegmentId, area) { const names = segmentStreetNames(sdk, selectedSegmentId); if (names.length === 0) return [selectedSegmentId]; const keys = new Set(names.map(k1)); const scoped = []; for (const segment of sdk.DataModel.Segments.getAll()) { if (segment.id === selectedSegmentId) continue; if (scoped.length >= MAX_SCOPED_SEGMENTS - 1) break; const bounds = bboxOfLine(segment.geometry.coordinates); if (!bounds || !intersects(bounds, area, NEIGHBOUR_PADDING_DEG)) continue; if (!segmentStreetNames(sdk, segment.id).some((name) => keys.has(k1(name)))) continue; scoped.push(segment.id); } return [selectedSegmentId, ...scoped]; } async function fetchExistingNumbers(sdk, segmentIds) { if (segmentIds.length === 0) return new Set(); try { const houseNumbers = await sdk.DataModel.HouseNumbers.fetchHouseNumbers({ segmentIds }); return new Set(houseNumbers.map((houseNumber) => normalizeNumber(houseNumber.number))); } catch (err) { log.warn("Could not read the existing house numbers", err); throw err; } } const DEFAULT_MAX_RECORDS = 2000; let IdbTileStore$1 = class IdbTileStore { constructor(options) { this.options = options; this.dbPromise = null; this.broken = false; this.maxRecords = options.maxRecords ?? DEFAULT_MAX_RECORDS; } open() { if (!this.dbPromise) { this.dbPromise = new Promise((resolve, reject) => { const { dbName, storeName, version } = this.options; const request = indexedDB.open(dbName, version); request.onupgradeneeded = () => { if (request.result.objectStoreNames.contains(storeName)) { request.result.deleteObjectStore(storeName); } request.result.createObjectStore(storeName, { keyPath: "key" }); }; request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error ?? new Error("IndexedDB open failed")); }); } return this.dbPromise; } async run(mode, operation) { if (this.broken) return undefined; try { const db = await this.open(); const { storeName } = this.options; return await new Promise((resolve, reject) => { const request = operation(db.transaction(storeName, mode).objectStore(storeName)); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed")); }); } catch (err) { if (!this.broken) { this.broken = true; console.warn(`[${this.options.dbName}] IndexedDB unavailable; falling back to in-memory tile cache only`, err); } return undefined; } } async get(key) { return this.run("readonly", (store) => store.get(key)); } async set(tile) { await this.run("readwrite", (store) => store.put(tile)); } async clear() { await this.run("readwrite", (store) => store.clear()); } async prune(ttlMs) { const all = await this.run("readonly", (store) => store.getAll()); if (!all) return; const now = Date.now(); const expired = all.filter((tile) => now - tile.fetchedAt > ttlMs).map((tile) => tile.key); const alive = all .filter((tile) => now - tile.fetchedAt <= ttlMs) .sort((a, b) => a.fetchedAt - b.fetchedAt); const overflow = alive.slice(0, Math.max(0, alive.length - this.maxRecords)); for (const key of [...expired, ...overflow.map((tile) => tile.key)]) { await this.run("readwrite", (store) => store.delete(key)); } } }; const GSTAT_EXISTING = 1004; const DEFAULT_PARSE_OPTIONS = { existingBuildingsOnly: true }; function isSubEntryNumber(value) { return /^\d+[A-Za-z]*\.\d+$/.test(value.trim()); } function parseStreetNames(raw) { const values = Array.isArray(raw) ? raw : [raw]; const names = []; for (const value of values) { if (typeof value !== "string") continue; const name = value.trim(); if (name !== "" && !names.includes(name)) names.push(name); } return names; } function asRecord(value) { return typeof value === "object" && value !== null ? value : null; } function readPoint(geometry) { const geom = asRecord(geometry); if (!geom || geom.type !== "Point" || !Array.isArray(geom.coordinates)) return null; const [lon, lat] = geom.coordinates; if (typeof lon !== "number" || typeof lat !== "number") return null; return Number.isFinite(lon) && Number.isFinite(lat) ? { lon, lat } : null; } const COMBINED = /^(.*?)[\s,]+(\d+[A-Za-z]?(?:[-/]\d+[A-Za-z]?)?)$/; function splitCombined(value) { if (typeof value !== "string") return null; const match = COMBINED.exec(value.trim()); return match ? { street: match[1].trim(), number: match[2].trim() } : null; } function parseGwrFeature(raw, options = DEFAULT_PARSE_OPTIONS) { const feature = asRecord(raw); if (!feature) return null; const props = asRecord(feature.properties) ?? asRecord(feature.attributes); if (!props) return null; const status = props.gstat; const statusKnown = status !== undefined && status !== null; if (options.existingBuildingsOnly && statusKnown && Number(status) !== GSTAT_EXISTING) { return null; } const coordinates = readPoint(feature.geometry); if (!coordinates) return null; const combined = splitCombined(props.strname_deinr); const rawNumber = props.deinr; let number = typeof rawNumber === "string" || typeof rawNumber === "number" ? String(rawNumber).trim() : ""; if (number === "" && combined) number = combined.number; if (number === "" || isSubEntryNumber(number)) return null; let streetNames = parseStreetNames(props.strname); if (streetNames.length === 0 && combined) streetNames = [combined.street]; if (streetNames.length === 0) return null; const esid = Number(props.esid); const egid = props.egid; const hasBuildingId = egid !== undefined && egid !== null && String(egid) !== ""; const id = hasBuildingId ? `${String(egid)}:${String(props.edid ?? 0)}` : `${coordinates.lon.toFixed(6)}:${coordinates.lat.toFixed(6)}:${number}`; return { id, number, streetNames, esid: Number.isFinite(esid) ? esid : 0, lon: coordinates.lon, lat: coordinates.lat, officialAddress: Number(props.doffadr) === 1, }; } function dedupePoints(points) { const byKey = new Map(); for (const point of points) { const key = `${point.esid}|${point.number.toUpperCase()}`; const kept = byKey.get(key); if (!kept || (!kept.officialAddress && point.officialAddress)) byKey.set(key, point); } return [...byKey.values()]; } const LAYER_ID = "ch.bfs.gebaeude_wohnungs_register"; const MAX_PAGES_PER_TILE = 8; async function fetchGwrPoints(bbox, signal, limiter = rateLimiter, parseOptions = DEFAULT_PARSE_OPTIONS) { const points = []; for (let page = 0; page < MAX_PAGES_PER_TILE; page++) { await limiter.acquire(); if (signal?.aborted) throw new DOMException("Fetch aborted", "AbortError"); const params = new URLSearchParams({ geometryType: "esriGeometryEnvelope", geometry: bbox.join(","), sr: "4326", layers: `all:${LAYER_ID}`, tolerance: "0", returnGeometry: "true", geometryFormat: "geojson", limit: String(PAGE_SIZE), offset: String(page * PAGE_SIZE), }); const data = (await httpGetJson(`${IDENTIFY_URL}?${params.toString()}`, signal)); const results = data.results ?? []; for (const result of results) { const point = parseGwrFeature(result, parseOptions); if (point) points.push(point); } if (results.length < PAGE_SIZE) return { points: dedupePoints(points), truncated: false }; } log.warn(`Page cap (${MAX_PAGES_PER_TILE}) reached for bbox ${bbox.join(",")}; results truncated`); return { points: dedupePoints(points), truncated: true }; } const GWR_TILE_SIZE_DEG = 0.005; const CACHE_MAX_TILES = 400; const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; const GWR_DB_NAME = "wme-ch-hn-import"; const GWR_STORE_NAME = "gwr-tiles"; function createGwrTileStore() { return new IdbTileStore$1({ dbName: GWR_DB_NAME, storeName: GWR_STORE_NAME, version: 1, maxRecords: 4000, }); } function tileKeysForBbox(bbox) { const [minLon, minLat, maxLon, maxLat] = bbox; const x0 = Math.floor(minLon / GWR_TILE_SIZE_DEG); const x1 = Math.floor(maxLon / GWR_TILE_SIZE_DEG); const y0 = Math.floor(minLat / GWR_TILE_SIZE_DEG); const y1 = Math.floor(maxLat / GWR_TILE_SIZE_DEG); const keys = []; for (let x = x0; x <= x1; x++) { for (let y = y0; y <= y1; y++) { keys.push(`${x}:${y}`); } } return keys; } function tileKeyToBbox(key) { const [xs, ys] = key.split(":"); const x = Number(xs); const y = Number(ys); return [ x * GWR_TILE_SIZE_DEG, y * GWR_TILE_SIZE_DEG, (x + 1) * GWR_TILE_SIZE_DEG, (y + 1) * GWR_TILE_SIZE_DEG, ]; } class TileCache { constructor(maxTiles = CACHE_MAX_TILES, ttlMs = CACHE_TTL_MS, now = Date.now) { this.maxTiles = maxTiles; this.ttlMs = ttlMs; this.now = now; this.slots = new Map(); } get(key) { const slot = this.slots.get(key); if (!slot) return null; if (this.now() - slot.fetchedAt > this.ttlMs) { this.slots.delete(key); return null; } this.slots.delete(key); this.slots.set(key, slot); return slot; } set(key, entries, truncated = false, fetchedAt = this.now()) { this.slots.delete(key); this.slots.set(key, { entries, truncated, fetchedAt }); while (this.slots.size > this.maxTiles) { const oldest = this.slots.keys().next().value; if (oldest === undefined) break; this.slots.delete(oldest); } } clear() { this.slots.clear(); } } class GwrTileFetcher { constructor(cache = new TileCache(), fetchTile = fetchGwrPoints, persistent = null) { this.cache = cache; this.fetchTile = fetchTile; this.persistent = persistent; void this.persistent?.prune(CACHE_TTL_MS); } async fetchBbox(bbox, signal, onProgress) { return this.fetchTiles(tileKeysForBbox(bbox), signal, onProgress); } async fetchTiles(keys, signal, onProgress) { let done = 0; onProgress?.(0, keys.length); const perTile = await Promise.all(keys.map(async (key) => { const result = await this.resolveTile(key, signal); done++; onProgress?.(done, keys.length); return { key, ...result }; })); const byId = new Map(); const truncatedKeys = []; const failedKeys = []; for (const tile of perTile) { for (const point of tile.entries) byId.set(point.id, point); if (tile.truncated) truncatedKeys.push(tile.key); if (tile.failed) failedKeys.push(tile.key); } return { points: [...byId.values()], truncatedKeys, failedKeys }; } async resolveTile(key, signal) { const cached = this.cache.get(key); if (cached) return { ...cached, failed: false }; const persisted = await this.persistent?.get(key); if (persisted && Date.now() - persisted.fetchedAt <= CACHE_TTL_MS) { const truncated = persisted.truncated ?? false; this.cache.set(key, persisted.entries, truncated, persisted.fetchedAt); return { entries: persisted.entries, truncated, failed: false }; } try { const { points, truncated } = await this.fetchTile(tileKeyToBbox(key), signal); this.cache.set(key, points, truncated); void this.persistent?.set({ key, entries: points, truncated, fetchedAt: Date.now() }); return { entries: points, truncated, failed: false }; } catch (err) { if (err instanceof DOMException && err.name === "AbortError") throw err; log.warn(`Tile ${key} failed to load; its addresses will be missing`, err); return { entries: [], truncated: false, failed: true }; } } clearAll() { this.cache.clear(); void this.persistent?.clear(); } } let provider = null; function registerStreetNameProvider(next) { provider = next; } function getStreetNameVerdict(segmentId) { if (!provider) return { kind: "unknown" }; try { return provider(segmentId); } catch { return { kind: "unknown" }; } } const i18n = instance.createInstance(); void i18n.init({ lng: "en", fallbackLng: "en", resources: { en: { common: enCommon }, fr: { common: frCommon }, it: { common: itCommon }, de: { common: deCommon }, }, interpolation: { escapeValue: false }, }); const LANGUAGE_CHOICES = [ { value: "auto", label: "Auto (WME)" }, { value: "en", label: "English" }, { value: "fr", label: "Français" }, { value: "de", label: "Deutsch" }, { value: "it", label: "Italiano" }, ]; const SUPPORTED = ["en", "fr", "de", "it"]; function normalize(code) { const prefix = (code ?? "en").toLowerCase().slice(0, 2); return SUPPORTED.includes(prefix) ? prefix : "en"; } function setLocale(code) { void i18n.changeLanguage(code); } function resolveLocale(preference, wmeLocaleCode) { if (preference !== "auto") return preference; return normalize(wmeLocaleCode); } function t(key, params) { return i18n.t(`common:hnImport.${key}`, params); } const confirmDialog = async (message) => { const result = await showWmeDialog({ message, buttons: [ { label: t("dialogConfirm"), value: "confirm" }, { label: t("dialogCancel"), value: "cancel" }, ], cancelValue: "cancel", }); return result === "confirm"; }; const notifyDialog = async (message) => { await showWmeDialog({ message, buttons: [{ label: t("dialogOk"), value: "ok" }], cancelValue: "ok", }); }; const IMPORT_CAP = 50; const MAX_SNAP_DISTANCE_M = 150; const CONFIRM_THRESHOLD = 2; function segmentGeometry(sdk, segmentId) { try { return sdk.DataModel.Segments.getById({ segmentId })?.geometry.coordinates ?? null; } catch { return null; } } function importPoint(sdk, point, segmentId) { const base = { pointId: point.id, number: point.number }; if (!sdk.Editing.isEditingAllowed()) return { ...base, ok: false, error: "errNotAllowed" }; const coordinates = segmentGeometry(sdk, segmentId); if (!coordinates) return { ...base, ok: false, error: "errSegmentNotFound" }; const distance = distanceToSegmentM(coordinates, point); if (distance > MAX_SNAP_DISTANCE_M) { return { ...base, ok: false, error: "errTooFar", distance: Math.round(distance), }; } try { sdk.DataModel.HouseNumbers.addHouseNumber({ number: point.number, point: { type: "Point", coordinates: [point.lon, point.lat] }, segmentId, }); return { ...base, ok: true }; } catch (err) { const name = err instanceof Error ? err.name : ""; if (name === "DataModelNotFoundError") { return { ...base, ok: false, error: "errSegmentNotFound" }; } if (name === "InvalidStateError") return { ...base, ok: false, error: "errInvalidState" }; log.warn(`Could not create house number ${point.number}`, err); return { ...base, ok: false, error: "errUnknown" }; } } async function importPoints(sdk, assignments, onProgress, alreadyPresent = new Set()) { const batch = assignments.slice(0, IMPORT_CAP); const outcomes = []; const created = new Set(); for (const [index, assignment] of batch.entries()) { const key = normalizeNumber(assignment.point.number); if (alreadyPresent.has(key) || created.has(key)) { continue; } const outcome = importPoint(sdk, assignment.point, assignment.segmentId); outcomes.push(outcome); if (!outcome.ok) break; created.add(key); await new Promise((resolve) => setTimeout(resolve, 0)); } return outcomes; } let importInFlight = false; function isImportInFlight() { return importInFlight; } async function withImportLock(fn) { if (importInFlight) return null; importInFlight = true; try { return await fn(); } finally { importInFlight = false; } } function describeFailure(outcome) { if (outcome.error === "errTooFar") { return t("errTooFar", { distance: outcome.distance ?? 0 }); } return t(outcome.error ?? "errUnknown"); } async function runImportPoint(sdk, point, segmentId, streetName, options = { confirmSingle: false, }) { const confirm = options.confirm ?? confirmDialog; const notify = options.notify ?? notifyDialog; await withImportLock(async () => { if (options.confirmSingle && !(await confirm(t("confirmSingleImport", { number: point.number, street: streetName })))) { return; } const outcome = importPoint(sdk, point, segmentId); if (!outcome.ok) await notify(describeFailure(outcome)); options.onComplete?.([outcome]); }); } async function runImportPoints(sdk, assignments, selectedSegmentId, streetName, hooks = {}) { const confirm = hooks.confirm ?? confirmDialog; const notify = hooks.notify ?? notifyDialog; if (assignments.length === 0) return; await withImportLock(async () => { const batch = assignments.slice(0, IMPORT_CAP); const numbers = [...batch] .sort((a, b) => compareHouseNumbers(a.point.number, b.point.number)) .map((assignment) => assignment.point.number) .join(", "); const capped = assignments.length > IMPORT_CAP; const base = capped ? t("confirmMassImportCapped", { cap: IMPORT_CAP, count: assignments.length, street: streetName, numbers, }) : t("confirmMassImport", { count: batch.length, street: streetName, numbers, }); const segments = countSegments(batch); const spread = segments > 1 ? `\n\n${t("confirmMassImportSegments", { segments })}` : ""; const verdict = getStreetNameVerdict(selectedSegmentId); const warning = verdict.kind === "mismatch" ? `\n\n${t("confirmMassImportUnverifiedName")}` : ""; const review = `\n\n${t("confirmMassImportReview")}`; if (batch.length >= CONFIRM_THRESHOLD && !(await confirm(`${base}${spread}${warning}${review}`))) { return; } const outcomes = await importPoints(sdk, assignments, undefined, hooks.alreadyPresent); const created = outcomes.filter((outcome) => outcome.ok).length; const failure = outcomes.find((outcome) => !outcome.ok); if (failure) { await notify(t("importStopped", { done: created, total: batch.length, message: describeFailure(failure), })); } else { await notify(t("importedCount", { count: created })); } hooks.onComplete?.(outcomes); }); } const DEFAULT_SETTINGS$1 = { version: 1, enabled: false, minZoom: 17, showMapLabels: true, strictMatching: true, existingBuildingsOnly: true, confirmSingleImport: false, language: "auto", }; function strictnessOf(settings) { return settings.strictMatching ? "strict" : "loose"; } const STORAGE_KEY$1 = "wme-ch-hn-import.settings"; function migrateSettings$1(parsed) { return { ...DEFAULT_SETTINGS$1, ...parsed, version: 1 }; } function loadSettings$1() { try { const raw = localStorage.getItem(STORAGE_KEY$1); if (!raw) return { ...DEFAULT_SETTINGS$1 }; return migrateSettings$1(JSON.parse(raw)); } catch (err) { log.warn("Failed to load settings, using defaults", err); return { ...DEFAULT_SETTINGS$1 }; } } function saveSettings$1(settings) { try { localStorage.setItem(STORAGE_KEY$1, JSON.stringify(settings)); } catch (err) { log.warn("Failed to save settings", err); } } let SettingsStore$1 = class SettingsStore { constructor() { this.settings = loadSettings$1(); } get() { return this.settings; } update(partial) { this.settings = { ...this.settings, ...partial }; saveSettings$1(this.settings); return this.settings; } }; const KEY_SEPARATOR = "\u0000"; function optimisticKey(streetName, normalizedNumber) { return `${k1(streetName)}${KEY_SEPARATOR}${normalizedNumber}`; } function numberOfKey(key, streetName) { const prefix = `${k1(streetName)}${KEY_SEPARATOR}`; return key.startsWith(prefix) ? key.slice(prefix.length) : null; } const MOVE_DEBOUNCE_MS = 400; const EDIT_DEBOUNCE_MS = 300; const MAX_TILES_PER_FETCH = 20; function canBulkImport(snapshot) { return (snapshot.segmentId !== null && !snapshot.truncated && !snapshot.incomplete && snapshot.missing.length > 0); } const EMPTY = { state: "idle", points: [], segmentId: null, streetName: "", missing: [], truncated: false, incomplete: false, progress: null, error: null, }; class Controller { constructor(sdk, fetcher, settings, layer, prompts = {}) { this.sdk = sdk; this.fetcher = fetcher; this.settings = settings; this.layer = layer; this.prompts = prompts; this.snapshot = EMPTY; this.listeners = []; this.generation = 0; this.moveTimer = null; this.editTimer = null; this.points = []; this.existingNumbers = null; this.existingForSegmentId = null; this.optimisticKeys = new Set(); this.geometries = new Map(); } start() { this.sdk.Events.on({ eventName: "wme-map-move-end", eventHandler: () => this.scheduleRefresh(MOVE_DEBOUNCE_MS), }); this.sdk.Events.on({ eventName: "wme-selection-changed", eventHandler: () => void this.refresh(), }); for (const eventName of [ "wme-house-number-added", "wme-house-number-updated", "wme-house-number-moved", ]) { this.sdk.Events.on({ eventName, eventHandler: () => this.scheduleReclassify(EDIT_DEBOUNCE_MS), }); } for (const eventName of ["wme-no-edits", "wme-save-finished"]) { this.sdk.Events.on({ eventName, eventHandler: () => { this.optimisticKeys.clear(); this.scheduleReclassify(EDIT_DEBOUNCE_MS); }, }); } for (const eventName of ["wme-after-undo", "wme-house-number-deleted"]) { this.sdk.Events.on({ eventName, eventHandler: () => { this.forgetLastCreation(); this.scheduleReclassify(EDIT_DEBOUNCE_MS); }, }); } this.sdk.Events.on({ eventName: "wme-layer-feature-clicked", eventHandler: ({ featureId }) => void this.onFeatureClicked(featureId), }); void this.refresh(); } onUpdate(listener) { this.listeners.push(listener); } getSnapshot() { return this.snapshot; } publish(partial) { this.snapshot = { ...this.snapshot, ...partial }; this.layer.sync(this.snapshot.points); for (const listener of this.listeners) listener(this.snapshot); } scheduleRefresh(delayMs) { if (this.moveTimer) clearTimeout(this.moveTimer); this.moveTimer = setTimeout(() => void this.refresh(), delayMs); } scheduleReclassify(delayMs) { if (this.editTimer) clearTimeout(this.editTimer); this.editTimer = setTimeout(() => void this.refresh({ refetchExisting: true }), delayMs); } selectedSegmentId() { const selection = this.sdk.Editing.getSelection(); if (selection?.objectType !== "segment" || selection.ids.length !== 1) return null; const id = selection.ids[0]; return typeof id === "number" ? id : null; } viewport() { try { const extent = this.sdk.Map.getMapExtent(); return [extent[0], extent[1], extent[2], extent[3]]; } catch { return null; } } async refresh(options = {}) { const generation = ++this.generation; const settings = this.settings.get(); if (!settings.enabled) { this.points = []; this.publish({ ...EMPTY, state: "disabled" }); return; } const bbox = this.viewport(); if (!bbox) return; if (this.sdk.Map.getZoomLevel() < settings.minZoom) { this.points = []; this.publish({ ...EMPTY, state: "zoom-gated" }); return; } if (!intersectsSwitzerland(bbox)) { this.points = []; this.publish({ ...EMPTY, state: "outside-ch" }); return; } if (tileKeysForBbox(bbox).length > MAX_TILES_PER_FETCH) { this.points = []; this.publish({ ...EMPTY, state: "area-gated" }); return; } let truncated = false; let incomplete = false; try { this.publish({ state: "fetching", error: null, progress: { done: 0, total: 0 }, }); const result = await this.fetcher.fetchBbox(bbox, undefined, (done, total) => { if (generation === this.generation) this.publish({ progress: { done, total } }); }); if (generation !== this.generation) return; this.points = result.points; truncated = result.truncatedKeys.length > 0; incomplete = result.failedKeys.length > 0; } catch (err) { if (generation !== this.generation) return; log.error("Could not load address points", err); this.publish({ state: "error", error: String(err), progress: null }); return; } const segmentId = this.selectedSegmentId(); if (segmentId === null) { this.existingNumbers = null; this.existingForSegmentId = null; this.classify(generation, { segmentId: null, streetName: "", truncated, incomplete, state: "idle", }); return; } const names = segmentStreetNames(this.sdk, segmentId); const streetName = names[0] ?? ""; if (options.refetchExisting || segmentId !== this.existingForSegmentId) { this.existingNumbers = null; } this.existingForSegmentId = segmentId; this.classify(generation, { segmentId, streetName, truncated, incomplete, state: "checking-existing", names, }); try { const segmentIds = collectStreetScopedSegmentIds(this.sdk, segmentId, bbox); this.geometries = readSegmentGeometries(this.sdk, segmentIds); const existing = await fetchExistingNumbers(this.sdk, segmentIds); if (generation !== this.generation) return; for (const key of [...this.optimisticKeys]) { const number = numberOfKey(key, streetName); if (number === null) continue; if (existing.has(number)) this.optimisticKeys.delete(key); else existing.add(number); } this.existingNumbers = existing; this.classify(generation, { segmentId, streetName, truncated, incomplete, state: "idle", names, }); } catch (err) { if (generation !== this.generation) return; this.publish({ state: "error", error: String(err), progress: null }); } } classify(generation, context) { if (generation !== this.generation) return; const settings = this.settings.get(); const segmentNames = context.segmentId === null ? null : (context.names ?? segmentStreetNames(this.sdk, context.segmentId)); const statused = computeStatuses({ points: this.points, segmentNames, existingNumbers: this.existingNumbers, strictness: strictnessOf(settings), }); const { assignments } = assignToSegments(missingPoints(statused), this.geometries, MAX_SNAP_DISTANCE_M); this.publish({ state: context.state, points: statused, segmentId: context.segmentId, streetName: context.streetName, missing: assignments, truncated: context.truncated, incomplete: context.incomplete, progress: null, error: null, }); } async onFeatureClicked(featureId) { const point = this.layer.pointOf(featureId); if (!point) return; const { segmentId, streetName } = this.snapshot; if (segmentId === null || this.existingNumbers === null) return; const entry = this.snapshot.points.find((candidate) => candidate.point.id === point.id); if (entry?.status !== "MISSING") return; const target = this.snapshot.missing.find((assignment) => assignment.point.id === point.id)?.segmentId ?? segmentId; await runImportPoint(this.sdk, point, target, streetName, { ...this.prompts, confirmSingle: this.settings.get().confirmSingleImport, onComplete: (outcomes) => this.markImported(outcomes), }); } async importMissing() { if (!canBulkImport(this.snapshot)) return; const { segmentId, streetName, missing } = this.snapshot; if (segmentId === null) return; await runImportPoints(this.sdk, missing, segmentId, streetName, { ...this.prompts, alreadyPresent: this.existingNumbers ?? this.optimisticNumbersFor(streetName), onComplete: (outcomes) => this.markImported(outcomes), }); } markImported(outcomes) { const streetName = this.snapshot.streetName; for (const outcome of outcomes) { if (!outcome.ok) continue; const number = normalizeNumber(outcome.number); this.optimisticKeys.add(optimisticKey(streetName, number)); this.existingNumbers?.add(number); } this.classify(this.generation, { segmentId: this.snapshot.segmentId, streetName, truncated: this.snapshot.truncated, incomplete: this.snapshot.incomplete, state: "idle", }); } optimisticNumbersFor(streetName) { const numbers = new Set(); for (const key of this.optimisticKeys) { const number = numberOfKey(key, streetName); if (number !== null) numbers.add(number); } return numbers; } forgetLastCreation() { let last; for (const key of this.optimisticKeys) last = key; if (last !== undefined) this.optimisticKeys.delete(last); } async reload() { this.fetcher.clearAll(); await this.refresh({ refetchExisting: true }); } disable() { this.generation++; this.points = []; this.existingNumbers = null; this.existingForSegmentId = null; this.layer.clear(); this.publish({ ...EMPTY, state: "disabled" }); } } const GLYPH_PATHS = { plus: "M24 14v20M14 24h20", check: "M15 24.5l6.5 6.5L33 19", }; function statusIcon({ color, opacity, glyph }) { const pictogram = glyph ? `` : ""; const svg = `` + `` + `${pictogram}`; return `data:image/svg+xml;base64,${btoa(svg)}`; } let cachedLayerName$1 = null; function getLayerName$1() { return (cachedLayerName$1 ??= t("layerName")); } const LABEL_MIN_ZOOM$1 = 18; const STATUS_STYLES$1 = { MISSING: { color: "#00c853", opacity: 1, pointRadius: 8, clickable: true, glyph: "plus" }, PRESENT: { color: "#455a64", opacity: 0.8, pointRadius: 8, clickable: false, glyph: "check" }, OTHER_STREET: { color: "#b0bec5", opacity: 0.55, pointRadius: 4, clickable: false }, NEUTRAL: { color: "#78909c", opacity: 0.55, pointRadius: 5, clickable: false }, }; const STATUS_ICONS = Object.fromEntries(Object.keys(STATUS_STYLES$1).map((status) => [ status, statusIcon(STATUS_STYLES$1[status]), ])); const FEATURE_PREFIX = "hn-"; function toFeature$1(entry) { return { type: "Feature", id: `${FEATURE_PREFIX}${entry.point.id}`, geometry: { type: "Point", coordinates: [entry.point.lon, entry.point.lat] }, properties: { status: entry.status, number: entry.point.number }, }; } class AddressPointLayer { constructor(sdk, settings) { this.sdk = sdk; this.settings = settings; this.rendered = new Map(); this.points = new Map(); } init() { try { this.sdk.Map.addLayer({ layerName: getLayerName$1(), styleContext: { getLabel: ({ feature, zoomLevel }) => { if (!this.settings.get().showMapLabels || zoomLevel < LABEL_MIN_ZOOM$1) return ""; const number = feature?.properties.number; return typeof number === "string" ? number : ""; }, }, styleRules: Object.keys(STATUS_STYLES$1).map((status) => ({ predicate: (properties) => properties.status === status, style: { externalGraphic: STATUS_ICONS[status], fillOpacity: 1, pointRadius: STATUS_STYLES$1[status].pointRadius, cursor: STATUS_STYLES$1[status].clickable ? "pointer" : "default", hoverPointRadius: STATUS_STYLES$1[status].pointRadius + 2, label: "${getLabel}", fontColor: "#1b1d20", fontSize: "11px", fontWeight: "bold", labelOutlineColor: "#ffffff", labelOutlineWidth: 3, labelYOffset: -13, }, })), }); this.sdk.Events.trackLayerEvents({ layerName: getLayerName$1() }); } catch (err) { log.error("Could not create the map layer", err); } } sync(entries) { const layerName = getLayerName$1(); const next = new Map(); for (const entry of entries) { const feature = toFeature$1(entry); const signature = `${entry.status}|${entry.point.number}|${entry.point.lon}|${entry.point.lat}`; next.set(String(feature.id), { signature, feature, point: entry.point }); } const featureIds = []; for (const [id, signature] of this.rendered) { if (next.get(id)?.signature !== signature) featureIds.push(id); } const features = []; for (const [id, entry] of next) { if (this.rendered.get(id) !== entry.signature) features.push(entry.feature); } try { if (featureIds.length > 0) this.sdk.Map.removeFeaturesFromLayer({ layerName, featureIds }); if (features.length > 0) this.sdk.Map.addFeaturesToLayer({ layerName, features }); } catch (err) { log.warn("Could not update the map layer", err); return; } this.rendered = new Map([...next].map(([id, entry]) => [id, entry.signature])); this.points = new Map([...next].map(([id, entry]) => [id, entry.point])); } pointOf(featureId) { return this.points.get(String(featureId)) ?? null; } clear() { this.sync([]); } setVisible(visible) { try { this.sdk.Map.setLayerVisibility({ layerName: getLayerName$1(), visibility: visible }); } catch (err) { log.warn("Could not toggle the map layer", err); } } } function registerLayerCheckbox$1(sdk, isChecked, onToggle) { sdk.LayerSwitcher.addLayerCheckbox({ name: getLayerName$1(), isChecked }); sdk.Events.on({ eventName: "wme-layer-checkbox-toggled", eventHandler: (payload) => { if (payload.name === getLayerName$1()) onToggle(payload.checked); }, }); } function setLayerCheckbox$1(sdk, isChecked) { sdk.LayerSwitcher.setLayerCheckboxChecked({ name: getLayerName$1(), isChecked }); } function registerShortcuts$1(sdk, controller, settings, actions) { const create = (shortcutId, description, keys, callback) => { try { sdk.Shortcuts.createShortcut({ shortcutId, description, shortcutKeys: keys, callback }); } catch (err) { log.warn(`Shortcut keys "${keys}" unavailable for ${shortcutId}; registering unbound`, err); try { sdk.Shortcuts.createShortcut({ shortcutId, description, shortcutKeys: null, callback }); } catch (collision) { log.warn(`Shortcut id "${shortcutId}" already registered; keeping the binding`, collision); } } }; create("hn-import-missing", t("shortcutImportMissing"), "A+h", () => { if (settings.get().enabled) void controller.importMissing(); }); create("hn-toggle-layer", t("shortcutToggleLayer"), "A+j", () => actions.toggleLayer()); } function el(tag, className, text) { const node = document.createElement(tag); if (className) node.className = className; if (text !== undefined) node.textContent = text; return node; } function icon(name, className = "") { const node = el("i", `w-icon w-icon-${name}${className ? ` ${className}` : ""}`); node.setAttribute("aria-hidden", "true"); return node; } function toggleSwitch(p, text, checked, onChange, title) { const label = el("label", `${p}-switch`); if (title) label.title = title; const input = el("input"); input.type = "checkbox"; input.checked = checked; input.addEventListener("change", () => onChange(input.checked)); const track = el("span", `${p}-switch-track`); track.appendChild(el("span", `${p}-switch-knob`)); label.append(input, track, el("span", `${p}-switch-label`, text)); return label; } function button(text, onClick, className = "") { const node = el("button", className, text); node.type = "button"; node.addEventListener("click", onClick); return node; } function numberInput(value, onChange, bounds) { const input = el("input"); input.type = "number"; input.min = String(bounds.min); input.max = String(bounds.max); input.value = String(value); input.style.width = "60px"; input.addEventListener("change", () => { const parsed = Number.parseInt(input.value, 10); const clamped = Math.min(bounds.max, Math.max(bounds.min, parsed)); input.value = String(Number.isFinite(clamped) ? clamped : value); onChange(Number(input.value)); }); return input; } function buildSection(p, iconName, title, children, open = false) { const details = el("details", `${p}-section`); details.open = open; const summary = el("summary"); summary.append(icon(iconName, `${p}-section-icon`), el("span", "", title)); details.appendChild(summary); const body = el("div", `${p}-section-body`); for (const child of children) body.appendChild(child); details.appendChild(body); return details; } function buildSubsection(p, iconName, title, children) { const details = el("details", `${p}-subsection`); const summary = el("summary"); summary.append(icon(iconName, `${p}-section-icon`), el("span", "", title)); details.appendChild(summary); const body = el("div", `${p}-subsection-body`); for (const child of children) body.appendChild(child); details.appendChild(body); return details; } const CONTAINER_ID$1 = "wmech-edit-panel-host"; const INJECT_RETRY_DELAYS_MS = [0, 120, 250, 400, 750, 900]; function orderedSlots(slots) { const byId = new Map(); for (const slot of slots) byId.set(slot.id, slot); return [...byId.values()].sort((a, b) => a.rank - b.rank || a.id.localeCompare(b.id)); } const registry = []; let retryTimers = []; let warnedMissingPanel = false; let hostTitleText = "Switzerland"; function registerEditPanelSlot(slot) { registry.push(slot); } function setEditPanelHostTitle(title) { hostTitleText = title; } function refreshEditPanelHost() { for (const timer of retryTimers) clearTimeout(timer); retryTimers = []; for (const delay of INJECT_RETRY_DELAYS_MS) { retryTimers.push(setTimeout(mount, delay)); } } function mount() { const rendered = []; for (const slot of orderedSlots(registry)) { const node = slot.render({ siblings: rendered.map((entry) => entry.id) }); if (node) rendered.push({ id: slot.id, node }); } const existing = document.getElementById(CONTAINER_ID$1); if (rendered.length === 0) { existing?.remove(); return; } const panel = document.querySelector("#edit-panel"); if (!panel) { if (!warnedMissingPanel) { warnedMissingPanel = true; console.warn("[wme-ch] #edit-panel not found; the edit-panel box is unavailable in this WME version"); } return; } const host = existing ?? el("div", "wmech-edit-host"); host.id = CONTAINER_ID$1; const head = el("div", "wmech-edit-host-head"); head.append(icon("location"), el("span", "", hostTitleText)); const children = [head]; for (const { node } of rendered) { const wrapper = el("div", "wmech-slot"); wrapper.appendChild(node); children.push(wrapper); } host.replaceChildren(...children); if (!existing) panel.prepend(host); } const STATE_KEYS$1 = { disabled: "stateIdle", idle: "stateIdle", "zoom-gated": "stateZoomGated", "area-gated": "stateAreaGated", "outside-ch": "stateOutsideCh", fetching: "stateFetching", "checking-existing": "stateCheckingExisting", error: "stateError", }; const LEGEND_KEYS$1 = { MISSING: "legendMissing", PRESENT: "legendPresent", OTHER_STREET: "legendOtherStreet", NEUTRAL: "legendNeutral", }; function formatState(snapshot) { if (snapshot.state === "fetching" && snapshot.progress) { return t("stateFetching", { done: snapshot.progress.done, total: snapshot.progress.total, }); } if (snapshot.state === "error") return t("stateError", { message: snapshot.error ?? "" }); return t(STATE_KEYS$1[snapshot.state]); } function countByStatus(points) { const counts = { total: points.length, missing: 0, present: 0, otherStreet: 0, }; for (const entry of points) { if (entry.status === "MISSING") counts.missing++; else if (entry.status === "PRESENT") counts.present++; else if (entry.status === "OTHER_STREET") counts.otherStreet++; } return counts; } function formatCounts(counts) { const parts = [ t("countMissing", { count: counts.missing }), t("countPresent", { count: counts.present }), t("countOtherStreet", { count: counts.otherStreet }), ]; return `${t("countGwr", { count: counts.total })} · ${parts.join(" · ")}`; } function formatImportButton(missingCount) { return missingCount > IMPORT_CAP ? t("btnImportMissingCapped", { cap: IMPORT_CAP, count: missingCount }) : t("btnImportMissing", { count: missingCount }); } function formatVerdict(verdict) { if (verdict.kind === "conform") return { text: t("verdictOk"), className: "hn-verdict-ok" }; if (verdict.kind === "mismatch") { return { text: t("verdictMismatch", { suggestion: verdict.suggestion ?? "?" }), className: "hn-verdict-mismatch", }; } return null; } function dataWarning(snapshot) { if (snapshot.truncated) return t("warnTruncated"); if (snapshot.incomplete) return t("warnIncomplete"); return null; } const EDIT_PANEL_HOST_CSS = ` .wmech-edit-host { margin: 8px; border: 1px solid var(--chk-border); border-radius: var(--chk-radius); background: var(--chk-surface); color: var(--chk-text); overflow: hidden; font-size: 12px; } .wmech-edit-host-head { display: flex; align-items: center; gap: 6px; padding: 6px 10px; font-size: 10px; font-weight: 700; letter-spacing: .5px; text-transform: uppercase; color: var(--chk-muted); border-bottom: 1px solid var(--chk-border); } .wmech-slot { padding: 8px 10px; display: flex; flex-direction: column; gap: 5px; } .wmech-slot + .wmech-slot { border-top: 1px solid var(--chk-border); } /* The slots bring their own pane class for typography; the host owns the spacing. */ .wmech-slot > .chk-helper, .wmech-slot > .hn-pane { margin: 0; padding: 0; border: none; background: none; } `; function componentRules(p) { return ` .${p}-pane { font-family: var(--${p}-font); font-size: 12px; padding: 8px; display: flex; flex-direction: column; gap: 10px; color: var(--${p}-text); } .${p}-pane button { cursor: pointer; font-family: inherit; } .${p}-pane :is(button, a, summary):focus-visible { outline: 2px solid var(--${p}-primary); outline-offset: 1px; } .${p}-pane label { display: flex; align-items: center; gap: 5px; font-weight: normal; cursor: pointer; } .${p}-pane select, .${p}-pane input[type="number"] { background: var(--${p}-bg); color: var(--${p}-text); border: 1px solid var(--${p}-border); border-radius: 5px; padding: 2px 5px; font-size: 11px; } .${p}-muted { color: var(--${p}-muted); } .${p}-note { font-size: 11px; color: var(--${p}-muted); line-height: 1.4; } .${p}-brand { display: flex; align-items: center; gap: 8px; } .${p}-brand-icon { font-size: 16px; line-height: 1; flex-shrink: 0; } /* The title is the only thing on this line allowed to give way, and it ellipsizes rather than wrapping: a wrapped brand row pushes the switch onto a line of its own, flush right, which reads as a stray control. Both labels are short enough that this never triggers in the four languages; it is the safety net, not the plan. */ .${p}-brand-title { font-weight: 700; font-size: 14px; color: var(--${p}-text); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* The master switch rides on the title line rather than owning a block below it. It never shrinks and its label never breaks: it was the flex item giving way, so "Activé" rendered as "Act". The title yields first now, and the row wraps before either is clipped. */ .${p}-brand-switch { margin-left: auto; flex-shrink: 0; } .${p}-brand-switch .${p}-switch-label { white-space: nowrap; } /* Buttons. Neutral is the default; primary carries the one positive action of the panel. Hover is a brightness filter rather than a second colour token to maintain. */ .${p}-btn { font-size: 11px; padding: 4px 10px; border: 1px solid var(--${p}-border); border-radius: 6px; background: var(--${p}-surface); color: var(--${p}-text); } .${p}-btn:hover { border-color: var(--${p}-primary); color: var(--${p}-primary); } .${p}-btn-primary { border: none; background: var(--${p}-fix); color: #fff; font-weight: 600; padding: 5px 12px; } .${p}-btn-primary:hover { border: none; filter: brightness(1.08); color: #fff; } .${p}-btn:disabled { opacity: .6; cursor: default; } /* WME's design system styles every