@oboapp/source-toplo-bg 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +12 -2
- package/dist/cjs/content.d.ts +3 -0
- package/dist/cjs/content.js +38 -0
- package/dist/cjs/geometry.d.ts +4 -0
- package/dist/cjs/geometry.js +104 -0
- package/dist/cjs/index.d.ts +2 -0
- package/dist/cjs/index.js +9 -0
- package/dist/cjs/metadata.d.ts +2 -0
- package/dist/cjs/metadata.js +10 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/parser.d.ts +12 -0
- package/dist/cjs/parser.js +49 -0
- package/dist/cjs/toplo.d.ts +9 -0
- package/dist/cjs/toplo.js +60 -0
- package/dist/esm/content.d.ts +3 -0
- package/dist/esm/content.js +35 -0
- package/dist/esm/geometry.d.ts +4 -0
- package/dist/esm/geometry.js +101 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/metadata.d.ts +2 -0
- package/dist/esm/metadata.js +7 -0
- package/dist/esm/parser.d.ts +12 -0
- package/dist/esm/parser.js +46 -0
- package/dist/esm/toplo.d.ts +9 -0
- package/dist/esm/toplo.js +57 -0
- package/package.json +59 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
This is free and unencumbered software released into the public domain.
|
|
2
|
+
|
|
3
|
+
Anyone is free to copy, modify, publish, use, compile, sell, or
|
|
4
|
+
distribute this software, either in source code form or as a compiled
|
|
5
|
+
binary, for any purpose, commercial or non-commercial, and by any
|
|
6
|
+
means.
|
|
7
|
+
|
|
8
|
+
In jurisdictions that recognize copyright laws, the author or authors
|
|
9
|
+
of this software dedicate any and all copyright interest in the
|
|
10
|
+
software to the public domain. We make this dedication for the benefit
|
|
11
|
+
of the public at large and to the detriment of our heirs and
|
|
12
|
+
successors. We intend this dedication to be an overt act of
|
|
13
|
+
relinquishment in perpetuity of all present and future rights to this
|
|
14
|
+
software under copyright law.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
19
|
+
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
|
20
|
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
|
21
|
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
22
|
+
OTHER DEALINGS IN THE SOFTWARE.
|
|
23
|
+
|
|
24
|
+
For more information, please refer to <https://unlicense.org>
|
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @oboapp/source-toplo-bg
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Collects heating incidents from the HTML listing at `https://toplo.bg/accidents-and-maintenance`. The incident JSON is already embedded in the server response, so the package reads it with HTTP and parses the data without executing page JavaScript. Each discovery makes one request with a 30-second timeout and supports the SDK cancellation signal. The runtime requires Node.js 20.3 or later.
|
|
4
|
+
|
|
5
|
+
Pass `createSource` and the isolated `metadata` entrypoint to Obo's scheduled source runner. Create one instance per scan. `discoverItems` emits the exact historical synthetic identifiers, such as `https://toplo.bg/incidents/item-1`. `fetchItem` reads content from that instance's listing cache and makes no request to the synthetic URL. Discovery items have no payload, so large geometries remain available without exceeding the SDK's 256 KiB discovery payload limit. `close` clears the cache and cancels active requests.
|
|
6
|
+
|
|
7
|
+
The package preserves Bulgarian content formatting, publication dates, heating categories, empty detail links, timespan fallback rules, and precomputed geometry. It keeps the legacy handling of Point, LineString and Polygon features: fix swapped Sofia coordinates, discard invalid features, retain other valid features, and skip incidents whose features are all invalid. An empty FeatureCollection remains valid. The same Sofia bounds as the legacy validator are used to recognize swapped coordinates. Malformed incident blocks, invalid geometry and coordinate corrections emit warnings.
|
|
8
|
+
|
|
9
|
+
Dates in text use the process timezone, matching the existing crawler. Invalid or pre-2025 starts fall back to the current time for the timespan; missing or invalid ends fall back to the start. The original `datePublished` and title remain unchanged. Obo's content validator rejects malformed publication dates and empty titles before storage.
|
|
10
|
+
|
|
11
|
+
The frozen listing and expected content fixtures come from Obo's pre-refactor Toplo contract. Tests cover literal identity, content, geometry cleanup, large cached incidents, failure handling, cancellation, and ESM/CommonJS entrypoints.
|
|
12
|
+
|
|
13
|
+
Obo owns deduplication, storage, scheduling, source ID and locality validation. Keep the existing `toplo-bg` job and emergent schedule when integrating. Publish this package through the reviewed release process in the repository's `RELEASING.md`, then install the exact npm version in a separate Obo integration PR. Roll back the integration by restoring the previous crawler entrypoint and redeploying; stored identifiers stay compatible.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildContent = buildContent;
|
|
4
|
+
const MINIMUM_DATE = Date.UTC(2025, 0, 1);
|
|
5
|
+
function formatDate(value) {
|
|
6
|
+
return new Date(value).toLocaleString("bg-BG", {
|
|
7
|
+
year: "numeric",
|
|
8
|
+
month: "long",
|
|
9
|
+
day: "numeric",
|
|
10
|
+
hour: "2-digit",
|
|
11
|
+
minute: "2-digit",
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
function timespanDate(value, fallback) {
|
|
15
|
+
const parsed = value ? new Date(value) : fallback;
|
|
16
|
+
return parsed.getTime() >= MINIMUM_DATE ? parsed : fallback;
|
|
17
|
+
}
|
|
18
|
+
function buildContent(incident) {
|
|
19
|
+
const parts = [incident.name, "", formatDate(incident.fromDate), incident.addresses];
|
|
20
|
+
if (incident.untilDate) {
|
|
21
|
+
parts.push("", `Очаквано възстановяване на ${formatDate(incident.untilDate)}`);
|
|
22
|
+
}
|
|
23
|
+
const message = parts.join("\n");
|
|
24
|
+
const timespanStart = timespanDate(incident.fromDate, new Date());
|
|
25
|
+
const timespanEnd = timespanDate(incident.untilDate, timespanStart);
|
|
26
|
+
return {
|
|
27
|
+
title: incident.name,
|
|
28
|
+
message,
|
|
29
|
+
markdownText: message,
|
|
30
|
+
datePublished: incident.fromDate,
|
|
31
|
+
timespanStart: timespanStart.toISOString(),
|
|
32
|
+
timespanEnd: timespanEnd.toISOString(),
|
|
33
|
+
deepLinkUrl: "",
|
|
34
|
+
geoJson: incident.geoJson,
|
|
35
|
+
categories: ["heating"],
|
|
36
|
+
isRelevant: true,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { JsonValue } from "@oboapp/source-sdk";
|
|
2
|
+
export type ToploWarning = (message: string) => void;
|
|
3
|
+
/** Preserve legacy feature filtering, coordinate correction and property defaults. */
|
|
4
|
+
export declare function normalizeGeoJson(value: JsonValue, warn: ToploWarning): JsonValue | undefined;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normalizeGeoJson = normalizeGeoJson;
|
|
4
|
+
function isRecord(value) {
|
|
5
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
6
|
+
}
|
|
7
|
+
// These are the legacy bg.sofia bounds used only to recognize swapped coordinates.
|
|
8
|
+
function isWithinSofia(longitude, latitude) {
|
|
9
|
+
return longitude >= 23.188 && longitude <= 23.528 && latitude >= 42.605 && latitude <= 42.83;
|
|
10
|
+
}
|
|
11
|
+
function normalizePosition(value, corrected) {
|
|
12
|
+
if (!Array.isArray(value) || value.length !== 2 ||
|
|
13
|
+
typeof value[0] !== "number" || typeof value[1] !== "number") {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
let [longitude, latitude] = value;
|
|
17
|
+
if (!isWithinSofia(longitude, latitude) && isWithinSofia(latitude, longitude)) {
|
|
18
|
+
[longitude, latitude] = [latitude, longitude];
|
|
19
|
+
corrected();
|
|
20
|
+
}
|
|
21
|
+
if (!Number.isFinite(longitude) || !Number.isFinite(latitude) ||
|
|
22
|
+
longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
return [longitude, latitude];
|
|
26
|
+
}
|
|
27
|
+
function normalizeLine(value, minimumLength, corrected) {
|
|
28
|
+
if (!Array.isArray(value) || value.length < minimumLength) {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
const positions = [];
|
|
32
|
+
for (const position of value) {
|
|
33
|
+
const normalized = normalizePosition(position, corrected);
|
|
34
|
+
if (!normalized) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
positions.push(normalized);
|
|
38
|
+
}
|
|
39
|
+
return positions;
|
|
40
|
+
}
|
|
41
|
+
function normalizeGeometry(value, corrected) {
|
|
42
|
+
if (!isRecord(value)) {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
if (value.type === "Point") {
|
|
46
|
+
const coordinates = normalizePosition(value.coordinates, corrected);
|
|
47
|
+
if (coordinates) {
|
|
48
|
+
return { type: "Point", coordinates };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (value.type === "LineString") {
|
|
52
|
+
const coordinates = normalizeLine(value.coordinates, 2, corrected);
|
|
53
|
+
if (coordinates) {
|
|
54
|
+
return { type: "LineString", coordinates };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (value.type === "Polygon" && Array.isArray(value.coordinates) && value.coordinates.length > 0) {
|
|
58
|
+
const coordinates = [];
|
|
59
|
+
for (const ring of value.coordinates) {
|
|
60
|
+
const normalized = normalizeLine(ring, 4, corrected);
|
|
61
|
+
const first = normalized?.[0];
|
|
62
|
+
const last = normalized?.at(-1);
|
|
63
|
+
if (!normalized || !first || !last || first[0] !== last[0] || first[1] !== last[1]) {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
coordinates.push(normalized);
|
|
67
|
+
}
|
|
68
|
+
return { type: "Polygon", coordinates };
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
/** Preserve legacy feature filtering, coordinate correction and property defaults. */
|
|
73
|
+
function normalizeGeoJson(value, warn) {
|
|
74
|
+
const collection = Array.isArray(value) ? { type: "FeatureCollection", features: value } : value;
|
|
75
|
+
if (!isRecord(collection) || collection.type !== "FeatureCollection" || !Array.isArray(collection.features)) {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
const features = [];
|
|
79
|
+
for (const feature of collection.features) {
|
|
80
|
+
if (!isRecord(feature) || feature.type !== "Feature") {
|
|
81
|
+
warn("Discarded invalid Toplo feature");
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
let coordinatesCorrected = false;
|
|
85
|
+
const geometry = normalizeGeometry(feature.geometry, () => {
|
|
86
|
+
coordinatesCorrected = true;
|
|
87
|
+
});
|
|
88
|
+
if (!geometry) {
|
|
89
|
+
warn("Discarded invalid Toplo feature geometry");
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (coordinatesCorrected) {
|
|
93
|
+
warn("Corrected swapped coordinates in Toplo feature");
|
|
94
|
+
}
|
|
95
|
+
const properties = feature.properties !== null && typeof feature.properties === "object"
|
|
96
|
+
? Object.fromEntries(Object.entries(feature.properties))
|
|
97
|
+
: {};
|
|
98
|
+
features.push({ type: "Feature", geometry, properties });
|
|
99
|
+
}
|
|
100
|
+
if (features.length === 0 && collection.features.length > 0) {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
return { type: "FeatureCollection", features };
|
|
104
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createSource = void 0;
|
|
4
|
+
const toplo_js_1 = require("./toplo.js");
|
|
5
|
+
const createSource = (context) => (0, toplo_js_1.createToploSource)({
|
|
6
|
+
fetch: (...args) => globalThis.fetch(...args),
|
|
7
|
+
...(context.signal === undefined ? {} : { signal: context.signal }),
|
|
8
|
+
});
|
|
9
|
+
exports.createSource = createSource;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.metadata = void 0;
|
|
4
|
+
exports.metadata = {
|
|
5
|
+
id: "toplo-bg",
|
|
6
|
+
url: "https://toplo.bg/accidents-and-maintenance",
|
|
7
|
+
name: "Топлофикация София",
|
|
8
|
+
localities: ["bg.sofia"],
|
|
9
|
+
emergent: true,
|
|
10
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { JsonValue } from "@oboapp/source-sdk";
|
|
2
|
+
import { type ToploWarning } from "./geometry.js";
|
|
3
|
+
export interface ToploIncident {
|
|
4
|
+
identifier: string;
|
|
5
|
+
name: string;
|
|
6
|
+
addresses: string;
|
|
7
|
+
fromDate: string;
|
|
8
|
+
untilDate: string | null;
|
|
9
|
+
geoJson: JsonValue;
|
|
10
|
+
}
|
|
11
|
+
/** Parse provider JSON without evaluating the surrounding JavaScript. */
|
|
12
|
+
export declare function parseIncidents(html: string, warn?: ToploWarning): ToploIncident[];
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseIncidents = parseIncidents;
|
|
4
|
+
const geometry_js_1 = require("./geometry.js");
|
|
5
|
+
function isIncidentInfo(value) {
|
|
6
|
+
if (value === null || typeof value !== "object") {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
return "ContentItemId" in value && typeof value.ContentItemId === "string" &&
|
|
10
|
+
"Name" in value && typeof value.Name === "string" &&
|
|
11
|
+
"Addresses" in value && typeof value.Addresses === "string" &&
|
|
12
|
+
"FromDate" in value && typeof value.FromDate === "string" &&
|
|
13
|
+
"UntilDate" in value && (value.UntilDate === null || typeof value.UntilDate === "string");
|
|
14
|
+
}
|
|
15
|
+
/** Parse provider JSON without evaluating the surrounding JavaScript. */
|
|
16
|
+
function parseIncidents(html, warn = (message) => globalThis.console.warn(message)) {
|
|
17
|
+
const script = html.match(/<script[^>]*>([\s\S]*?)<\/script>/gi)?.find((candidate) => {
|
|
18
|
+
return candidate.includes("function parseAll()");
|
|
19
|
+
});
|
|
20
|
+
if (!script) {
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
const incidents = [];
|
|
24
|
+
const pattern = /var geoJsonString = '(.+?)'\s*var info = ({[\s\S]+?})\s*if \(geoJsonString/g;
|
|
25
|
+
for (const match of script.matchAll(pattern)) {
|
|
26
|
+
try {
|
|
27
|
+
const info = JSON.parse(match[2]);
|
|
28
|
+
const geoJson = (0, geometry_js_1.normalizeGeoJson)(JSON.parse(match[1]), warn);
|
|
29
|
+
if (!isIncidentInfo(info) || geoJson === undefined) {
|
|
30
|
+
warn("Skipped Toplo incident with invalid info or geometry");
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
incidents.push({
|
|
34
|
+
identifier: `https://toplo.bg/incidents/${info.ContentItemId}`,
|
|
35
|
+
name: info.Name,
|
|
36
|
+
addresses: info.Addresses,
|
|
37
|
+
fromDate: info.FromDate,
|
|
38
|
+
untilDate: info.UntilDate,
|
|
39
|
+
geoJson,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
warn(`Failed to parse Toplo incident: ${error instanceof Error ? error.message : String(error)}`);
|
|
44
|
+
// A malformed provider block must not hide other listing incidents.
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return incidents;
|
|
49
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { DataSource } from "@oboapp/source-sdk";
|
|
2
|
+
import type { ToploWarning } from "./geometry.js";
|
|
3
|
+
export interface ToploDependencies {
|
|
4
|
+
fetch: typeof globalThis.fetch;
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
warn?: ToploWarning;
|
|
7
|
+
}
|
|
8
|
+
/** Listing content stays in this scan's instance, including large geometries. */
|
|
9
|
+
export declare function createToploSource(dependencies?: ToploDependencies): DataSource;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createToploSource = createToploSource;
|
|
4
|
+
const content_js_1 = require("./content.js");
|
|
5
|
+
const parser_js_1 = require("./parser.js");
|
|
6
|
+
const TARGET_URL = "https://toplo.bg/accidents-and-maintenance";
|
|
7
|
+
const defaults = {
|
|
8
|
+
fetch: (...args) => globalThis.fetch(...args),
|
|
9
|
+
};
|
|
10
|
+
/** Listing content stays in this scan's instance, including large geometries. */
|
|
11
|
+
function createToploSource(dependencies = defaults) {
|
|
12
|
+
const controller = new globalThis.AbortController();
|
|
13
|
+
const signal = dependencies.signal === undefined
|
|
14
|
+
? controller.signal
|
|
15
|
+
: AbortSignal.any([controller.signal, dependencies.signal]);
|
|
16
|
+
let closed = false;
|
|
17
|
+
const incidents = new Map();
|
|
18
|
+
return {
|
|
19
|
+
async discoverItems() {
|
|
20
|
+
if (closed) {
|
|
21
|
+
throw new Error("Toplo source is closed");
|
|
22
|
+
}
|
|
23
|
+
incidents.clear();
|
|
24
|
+
const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(30_000)]);
|
|
25
|
+
requestSignal.throwIfAborted();
|
|
26
|
+
const response = await dependencies.fetch(TARGET_URL, {
|
|
27
|
+
headers: { Accept: "text/html" },
|
|
28
|
+
signal: requestSignal,
|
|
29
|
+
});
|
|
30
|
+
if (!response.ok) {
|
|
31
|
+
throw new Error(`Toplo listing returned HTTP ${response.status}`);
|
|
32
|
+
}
|
|
33
|
+
const html = await response.text();
|
|
34
|
+
requestSignal.throwIfAborted();
|
|
35
|
+
for (const incident of (0, parser_js_1.parseIncidents)(html, dependencies.warn)) {
|
|
36
|
+
if (!incidents.has(incident.identifier)) {
|
|
37
|
+
incidents.set(incident.identifier, incident);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (incidents.size === 0) {
|
|
41
|
+
throw new Error("No incidents found in HTML");
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
items: [...incidents.keys()].map((identifier) => ({ identifier })),
|
|
45
|
+
};
|
|
46
|
+
},
|
|
47
|
+
async fetchItem(item) {
|
|
48
|
+
const incident = incidents.get(item.identifier);
|
|
49
|
+
if (!incident || closed) {
|
|
50
|
+
throw new Error(`Missing listing incident for ${item.identifier}`);
|
|
51
|
+
}
|
|
52
|
+
return (0, content_js_1.buildContent)(incident);
|
|
53
|
+
},
|
|
54
|
+
async close() {
|
|
55
|
+
closed = true;
|
|
56
|
+
incidents.clear();
|
|
57
|
+
controller.abort();
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const MINIMUM_DATE = Date.UTC(2025, 0, 1);
|
|
2
|
+
function formatDate(value) {
|
|
3
|
+
return new Date(value).toLocaleString("bg-BG", {
|
|
4
|
+
year: "numeric",
|
|
5
|
+
month: "long",
|
|
6
|
+
day: "numeric",
|
|
7
|
+
hour: "2-digit",
|
|
8
|
+
minute: "2-digit",
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
function timespanDate(value, fallback) {
|
|
12
|
+
const parsed = value ? new Date(value) : fallback;
|
|
13
|
+
return parsed.getTime() >= MINIMUM_DATE ? parsed : fallback;
|
|
14
|
+
}
|
|
15
|
+
export function buildContent(incident) {
|
|
16
|
+
const parts = [incident.name, "", formatDate(incident.fromDate), incident.addresses];
|
|
17
|
+
if (incident.untilDate) {
|
|
18
|
+
parts.push("", `Очаквано възстановяване на ${formatDate(incident.untilDate)}`);
|
|
19
|
+
}
|
|
20
|
+
const message = parts.join("\n");
|
|
21
|
+
const timespanStart = timespanDate(incident.fromDate, new Date());
|
|
22
|
+
const timespanEnd = timespanDate(incident.untilDate, timespanStart);
|
|
23
|
+
return {
|
|
24
|
+
title: incident.name,
|
|
25
|
+
message,
|
|
26
|
+
markdownText: message,
|
|
27
|
+
datePublished: incident.fromDate,
|
|
28
|
+
timespanStart: timespanStart.toISOString(),
|
|
29
|
+
timespanEnd: timespanEnd.toISOString(),
|
|
30
|
+
deepLinkUrl: "",
|
|
31
|
+
geoJson: incident.geoJson,
|
|
32
|
+
categories: ["heating"],
|
|
33
|
+
isRelevant: true,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { JsonValue } from "@oboapp/source-sdk";
|
|
2
|
+
export type ToploWarning = (message: string) => void;
|
|
3
|
+
/** Preserve legacy feature filtering, coordinate correction and property defaults. */
|
|
4
|
+
export declare function normalizeGeoJson(value: JsonValue, warn: ToploWarning): JsonValue | undefined;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
function isRecord(value) {
|
|
2
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3
|
+
}
|
|
4
|
+
// These are the legacy bg.sofia bounds used only to recognize swapped coordinates.
|
|
5
|
+
function isWithinSofia(longitude, latitude) {
|
|
6
|
+
return longitude >= 23.188 && longitude <= 23.528 && latitude >= 42.605 && latitude <= 42.83;
|
|
7
|
+
}
|
|
8
|
+
function normalizePosition(value, corrected) {
|
|
9
|
+
if (!Array.isArray(value) || value.length !== 2 ||
|
|
10
|
+
typeof value[0] !== "number" || typeof value[1] !== "number") {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
let [longitude, latitude] = value;
|
|
14
|
+
if (!isWithinSofia(longitude, latitude) && isWithinSofia(latitude, longitude)) {
|
|
15
|
+
[longitude, latitude] = [latitude, longitude];
|
|
16
|
+
corrected();
|
|
17
|
+
}
|
|
18
|
+
if (!Number.isFinite(longitude) || !Number.isFinite(latitude) ||
|
|
19
|
+
longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
return [longitude, latitude];
|
|
23
|
+
}
|
|
24
|
+
function normalizeLine(value, minimumLength, corrected) {
|
|
25
|
+
if (!Array.isArray(value) || value.length < minimumLength) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
const positions = [];
|
|
29
|
+
for (const position of value) {
|
|
30
|
+
const normalized = normalizePosition(position, corrected);
|
|
31
|
+
if (!normalized) {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
positions.push(normalized);
|
|
35
|
+
}
|
|
36
|
+
return positions;
|
|
37
|
+
}
|
|
38
|
+
function normalizeGeometry(value, corrected) {
|
|
39
|
+
if (!isRecord(value)) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
if (value.type === "Point") {
|
|
43
|
+
const coordinates = normalizePosition(value.coordinates, corrected);
|
|
44
|
+
if (coordinates) {
|
|
45
|
+
return { type: "Point", coordinates };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (value.type === "LineString") {
|
|
49
|
+
const coordinates = normalizeLine(value.coordinates, 2, corrected);
|
|
50
|
+
if (coordinates) {
|
|
51
|
+
return { type: "LineString", coordinates };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (value.type === "Polygon" && Array.isArray(value.coordinates) && value.coordinates.length > 0) {
|
|
55
|
+
const coordinates = [];
|
|
56
|
+
for (const ring of value.coordinates) {
|
|
57
|
+
const normalized = normalizeLine(ring, 4, corrected);
|
|
58
|
+
const first = normalized?.[0];
|
|
59
|
+
const last = normalized?.at(-1);
|
|
60
|
+
if (!normalized || !first || !last || first[0] !== last[0] || first[1] !== last[1]) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
coordinates.push(normalized);
|
|
64
|
+
}
|
|
65
|
+
return { type: "Polygon", coordinates };
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
/** Preserve legacy feature filtering, coordinate correction and property defaults. */
|
|
70
|
+
export function normalizeGeoJson(value, warn) {
|
|
71
|
+
const collection = Array.isArray(value) ? { type: "FeatureCollection", features: value } : value;
|
|
72
|
+
if (!isRecord(collection) || collection.type !== "FeatureCollection" || !Array.isArray(collection.features)) {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
const features = [];
|
|
76
|
+
for (const feature of collection.features) {
|
|
77
|
+
if (!isRecord(feature) || feature.type !== "Feature") {
|
|
78
|
+
warn("Discarded invalid Toplo feature");
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
let coordinatesCorrected = false;
|
|
82
|
+
const geometry = normalizeGeometry(feature.geometry, () => {
|
|
83
|
+
coordinatesCorrected = true;
|
|
84
|
+
});
|
|
85
|
+
if (!geometry) {
|
|
86
|
+
warn("Discarded invalid Toplo feature geometry");
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (coordinatesCorrected) {
|
|
90
|
+
warn("Corrected swapped coordinates in Toplo feature");
|
|
91
|
+
}
|
|
92
|
+
const properties = feature.properties !== null && typeof feature.properties === "object"
|
|
93
|
+
? Object.fromEntries(Object.entries(feature.properties))
|
|
94
|
+
: {};
|
|
95
|
+
features.push({ type: "Feature", geometry, properties });
|
|
96
|
+
}
|
|
97
|
+
if (features.length === 0 && collection.features.length > 0) {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
return { type: "FeatureCollection", features };
|
|
101
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { JsonValue } from "@oboapp/source-sdk";
|
|
2
|
+
import { type ToploWarning } from "./geometry.js";
|
|
3
|
+
export interface ToploIncident {
|
|
4
|
+
identifier: string;
|
|
5
|
+
name: string;
|
|
6
|
+
addresses: string;
|
|
7
|
+
fromDate: string;
|
|
8
|
+
untilDate: string | null;
|
|
9
|
+
geoJson: JsonValue;
|
|
10
|
+
}
|
|
11
|
+
/** Parse provider JSON without evaluating the surrounding JavaScript. */
|
|
12
|
+
export declare function parseIncidents(html: string, warn?: ToploWarning): ToploIncident[];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { normalizeGeoJson } from "./geometry.js";
|
|
2
|
+
function isIncidentInfo(value) {
|
|
3
|
+
if (value === null || typeof value !== "object") {
|
|
4
|
+
return false;
|
|
5
|
+
}
|
|
6
|
+
return "ContentItemId" in value && typeof value.ContentItemId === "string" &&
|
|
7
|
+
"Name" in value && typeof value.Name === "string" &&
|
|
8
|
+
"Addresses" in value && typeof value.Addresses === "string" &&
|
|
9
|
+
"FromDate" in value && typeof value.FromDate === "string" &&
|
|
10
|
+
"UntilDate" in value && (value.UntilDate === null || typeof value.UntilDate === "string");
|
|
11
|
+
}
|
|
12
|
+
/** Parse provider JSON without evaluating the surrounding JavaScript. */
|
|
13
|
+
export function parseIncidents(html, warn = (message) => globalThis.console.warn(message)) {
|
|
14
|
+
const script = html.match(/<script[^>]*>([\s\S]*?)<\/script>/gi)?.find((candidate) => {
|
|
15
|
+
return candidate.includes("function parseAll()");
|
|
16
|
+
});
|
|
17
|
+
if (!script) {
|
|
18
|
+
return [];
|
|
19
|
+
}
|
|
20
|
+
const incidents = [];
|
|
21
|
+
const pattern = /var geoJsonString = '(.+?)'\s*var info = ({[\s\S]+?})\s*if \(geoJsonString/g;
|
|
22
|
+
for (const match of script.matchAll(pattern)) {
|
|
23
|
+
try {
|
|
24
|
+
const info = JSON.parse(match[2]);
|
|
25
|
+
const geoJson = normalizeGeoJson(JSON.parse(match[1]), warn);
|
|
26
|
+
if (!isIncidentInfo(info) || geoJson === undefined) {
|
|
27
|
+
warn("Skipped Toplo incident with invalid info or geometry");
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
incidents.push({
|
|
31
|
+
identifier: `https://toplo.bg/incidents/${info.ContentItemId}`,
|
|
32
|
+
name: info.Name,
|
|
33
|
+
addresses: info.Addresses,
|
|
34
|
+
fromDate: info.FromDate,
|
|
35
|
+
untilDate: info.UntilDate,
|
|
36
|
+
geoJson,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
warn(`Failed to parse Toplo incident: ${error instanceof Error ? error.message : String(error)}`);
|
|
41
|
+
// A malformed provider block must not hide other listing incidents.
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return incidents;
|
|
46
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { DataSource } from "@oboapp/source-sdk";
|
|
2
|
+
import type { ToploWarning } from "./geometry.js";
|
|
3
|
+
export interface ToploDependencies {
|
|
4
|
+
fetch: typeof globalThis.fetch;
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
warn?: ToploWarning;
|
|
7
|
+
}
|
|
8
|
+
/** Listing content stays in this scan's instance, including large geometries. */
|
|
9
|
+
export declare function createToploSource(dependencies?: ToploDependencies): DataSource;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { buildContent } from "./content.js";
|
|
2
|
+
import { parseIncidents } from "./parser.js";
|
|
3
|
+
const TARGET_URL = "https://toplo.bg/accidents-and-maintenance";
|
|
4
|
+
const defaults = {
|
|
5
|
+
fetch: (...args) => globalThis.fetch(...args),
|
|
6
|
+
};
|
|
7
|
+
/** Listing content stays in this scan's instance, including large geometries. */
|
|
8
|
+
export function createToploSource(dependencies = defaults) {
|
|
9
|
+
const controller = new globalThis.AbortController();
|
|
10
|
+
const signal = dependencies.signal === undefined
|
|
11
|
+
? controller.signal
|
|
12
|
+
: AbortSignal.any([controller.signal, dependencies.signal]);
|
|
13
|
+
let closed = false;
|
|
14
|
+
const incidents = new Map();
|
|
15
|
+
return {
|
|
16
|
+
async discoverItems() {
|
|
17
|
+
if (closed) {
|
|
18
|
+
throw new Error("Toplo source is closed");
|
|
19
|
+
}
|
|
20
|
+
incidents.clear();
|
|
21
|
+
const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(30_000)]);
|
|
22
|
+
requestSignal.throwIfAborted();
|
|
23
|
+
const response = await dependencies.fetch(TARGET_URL, {
|
|
24
|
+
headers: { Accept: "text/html" },
|
|
25
|
+
signal: requestSignal,
|
|
26
|
+
});
|
|
27
|
+
if (!response.ok) {
|
|
28
|
+
throw new Error(`Toplo listing returned HTTP ${response.status}`);
|
|
29
|
+
}
|
|
30
|
+
const html = await response.text();
|
|
31
|
+
requestSignal.throwIfAborted();
|
|
32
|
+
for (const incident of parseIncidents(html, dependencies.warn)) {
|
|
33
|
+
if (!incidents.has(incident.identifier)) {
|
|
34
|
+
incidents.set(incident.identifier, incident);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (incidents.size === 0) {
|
|
38
|
+
throw new Error("No incidents found in HTML");
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
items: [...incidents.keys()].map((identifier) => ({ identifier })),
|
|
42
|
+
};
|
|
43
|
+
},
|
|
44
|
+
async fetchItem(item) {
|
|
45
|
+
const incident = incidents.get(item.identifier);
|
|
46
|
+
if (!incident || closed) {
|
|
47
|
+
throw new Error(`Missing listing incident for ${item.identifier}`);
|
|
48
|
+
}
|
|
49
|
+
return buildContent(incident);
|
|
50
|
+
},
|
|
51
|
+
async close() {
|
|
52
|
+
closed = true;
|
|
53
|
+
incidents.clear();
|
|
54
|
+
controller.abort();
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oboapp/source-toplo-bg",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Listing-only heating incidents from Toplofikatsia Sofia",
|
|
5
|
+
"license": "Unlicense",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/cjs/index.js",
|
|
8
|
+
"types": "./dist/cjs/index.d.ts",
|
|
9
|
+
"typesVersions": {
|
|
10
|
+
"*": {
|
|
11
|
+
"metadata": [
|
|
12
|
+
"dist/cjs/metadata.d.ts"
|
|
13
|
+
]
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/oboapp/sources.git",
|
|
19
|
+
"directory": "packages/source-toplo-bg"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"LICENSE",
|
|
24
|
+
"README.md"
|
|
25
|
+
],
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"import": {
|
|
29
|
+
"types": "./dist/esm/index.d.ts",
|
|
30
|
+
"default": "./dist/esm/index.js"
|
|
31
|
+
},
|
|
32
|
+
"require": {
|
|
33
|
+
"types": "./dist/cjs/index.d.ts",
|
|
34
|
+
"default": "./dist/cjs/index.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"./metadata": {
|
|
38
|
+
"import": {
|
|
39
|
+
"types": "./dist/esm/metadata.d.ts",
|
|
40
|
+
"default": "./dist/esm/metadata.js"
|
|
41
|
+
},
|
|
42
|
+
"require": {
|
|
43
|
+
"types": "./dist/cjs/metadata.d.ts",
|
|
44
|
+
"default": "./dist/cjs/metadata.js"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"sideEffects": false,
|
|
49
|
+
"engines": {
|
|
50
|
+
"node": ">=20.3.0"
|
|
51
|
+
},
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"@oboapp/source-sdk": "0.1.1"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node scripts/finalize-build.mjs",
|
|
60
|
+
"test": "tsc -p test/tsconfig.json && tsx --test test/*.test.ts"
|
|
61
|
+
}
|
|
6
62
|
}
|