@tilda-geo/bicycle-infrastructure 0.1.2

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/dist/index.js ADDED
@@ -0,0 +1,1909 @@
1
+ // src/types.ts
2
+ var DISALLOWED = "DISALLOWED_VALUE";
3
+
4
+ // src/helpers/highway-classes.ts
5
+ var TRUNK_MOTORWAY_CLASSES = ["motorway", "motorway_link", "trunk", "trunk_link"];
6
+ var MAJOR_ROAD_CLASSES = [
7
+ "primary",
8
+ "primary_link",
9
+ "secondary",
10
+ "secondary_link",
11
+ "tertiary",
12
+ "tertiary_link"
13
+ ];
14
+ var MINOR_ROAD_CLASSES = [
15
+ "unclassified",
16
+ "residential",
17
+ "road",
18
+ "living_street",
19
+ "pedestrian",
20
+ "service"
21
+ ];
22
+ var PATH_CLASSES = ["track", "path", "footway", "cycleway", "steps"];
23
+ var SIDEPATH_HIGHWAY_CLASSES = /* @__PURE__ */ new Set([...PATH_CLASSES, "pedestrian"]);
24
+ var ALLOWED_HIGHWAYS = /* @__PURE__ */ new Set([
25
+ ...TRUNK_MOTORWAY_CLASSES,
26
+ ...MAJOR_ROAD_CLASSES,
27
+ ...MINOR_ROAD_CLASSES,
28
+ ...PATH_CLASSES
29
+ ]);
30
+
31
+ // src/transform/transformations.ts
32
+ var SIDES = ["left", "right"];
33
+ var META_PREFIXES = ["source:", "note:"];
34
+ function unnestPrefixedTags(tags, prefix, infix, dest, metaPrefix) {
35
+ const metaPrefixString = metaPrefix ?? "";
36
+ const fullPrefix = metaPrefixString + prefix + infix;
37
+ const prefixLen = fullPrefix.length;
38
+ for (const key of Object.keys(tags)) {
39
+ const val = tags[key];
40
+ if (val === void 0) continue;
41
+ if (!key.startsWith(fullPrefix)) continue;
42
+ if (key === fullPrefix) {
43
+ const destinationKey = metaPrefix ? metaPrefixString.slice(0, -1) : prefix;
44
+ dest[destinationKey] = val;
45
+ dest._infix = infix;
46
+ } else {
47
+ const extractedSuffix = key.slice(prefixLen + 1);
48
+ const suffixKey = extractedSuffix.match(/^[^:]*/)[0];
49
+ if (infix !== "" || !(suffixKey === "left" || suffixKey === "right" || suffixKey === "both")) {
50
+ const destinationKey = metaPrefix ? metaPrefixString + extractedSuffix : extractedSuffix;
51
+ dest[destinationKey] = val;
52
+ dest._infix = infix;
53
+ }
54
+ }
55
+ }
56
+ return dest;
57
+ }
58
+ var DIRECTED_PARENT_TAGS = ["cycleway:lanes", "bicycle:lanes"];
59
+ var DIRECTED_SELF_TAGS = ["traffic_sign"];
60
+ var SIDE_TO_DIRECTION = {
61
+ "": "",
62
+ both: "",
63
+ left: ":backward",
64
+ right: ":forward"
65
+ };
66
+ function convertDirectedTags(cycleway, directionReference) {
67
+ const parent = cycleway._parent;
68
+ const side = cycleway._side ?? "";
69
+ for (const key of DIRECTED_PARENT_TAGS) {
70
+ const directedKey = key + SIDE_TO_DIRECTION[side];
71
+ cycleway[key] = cycleway[key] ?? parent[key] ?? parent[directedKey];
72
+ }
73
+ for (const key of DIRECTED_SELF_TAGS) {
74
+ if (directionReference === "self") {
75
+ cycleway[key] = cycleway[key] ?? cycleway[`${key}:forward`];
76
+ } else {
77
+ const directedKey = key + SIDE_TO_DIRECTION[side];
78
+ cycleway[key] = cycleway[key] ?? cycleway[directedKey];
79
+ }
80
+ }
81
+ return cycleway;
82
+ }
83
+ function getTransformedObjects(tags, transformations) {
84
+ const center = { ...tags, _side: "self" };
85
+ if (tags.highway != null && SIDEPATH_HIGHWAY_CLASSES.has(tags.highway)) {
86
+ unnestPrefixedTags(tags, "cycleway", "", center);
87
+ for (const mp of META_PREFIXES) unnestPrefixedTags(tags, "cycleway", "", center, mp);
88
+ if (center.oneway === "yes" && tags["oneway:bicycle"] !== "no") {
89
+ center.traffic_sign = center.traffic_sign ?? center["traffic_sign:forward"];
90
+ }
91
+ return [center];
92
+ }
93
+ const results = [center];
94
+ for (const transformation of transformations) {
95
+ for (const side of SIDES) {
96
+ if (tags.highway === transformation.highway) continue;
97
+ const prefix = transformation.prefix;
98
+ const newObj = {
99
+ _prefix: prefix,
100
+ _side: side,
101
+ _parent_highway: tags.highway,
102
+ highway: transformation.highway
103
+ };
104
+ newObj._parent = tags;
105
+ unnestPrefixedTags(tags, prefix, "", newObj);
106
+ unnestPrefixedTags(tags, prefix, ":both", newObj);
107
+ unnestPrefixedTags(tags, prefix, `:${side}`, newObj);
108
+ for (const mp of META_PREFIXES) {
109
+ unnestPrefixedTags(tags, prefix, "", newObj, mp);
110
+ unnestPrefixedTags(tags, prefix, ":both", newObj, mp);
111
+ unnestPrefixedTags(tags, prefix, `:${side}`, newObj, mp);
112
+ }
113
+ if (newObj._infix !== void 0 && transformation.filter(newObj)) {
114
+ convertDirectedTags(newObj, transformation.direction_reference);
115
+ results.push(newObj);
116
+ }
117
+ }
118
+ }
119
+ return results;
120
+ }
121
+ var BIKELANE_TRANSFORMATIONS = [
122
+ { highway: "cycleway", prefix: "cycleway", direction_reference: "self", filter: () => true },
123
+ {
124
+ highway: "footway",
125
+ prefix: "sidewalk",
126
+ direction_reference: "parent",
127
+ filter: (t) => !(t.footway === "no" || t.footway === "separate")
128
+ }
129
+ ];
130
+
131
+ // src/helpers/strings.ts
132
+ function containsSubstring(str, subStr) {
133
+ if (str == null || subStr == null) return false;
134
+ return str.includes(subStr);
135
+ }
136
+ function hasPrefix(str, prefix) {
137
+ if (str == null) return false;
138
+ return str.startsWith(prefix);
139
+ }
140
+ function hasSuffix(str, suffix) {
141
+ if (str == null) return false;
142
+ if (suffix === "") return true;
143
+ return str.endsWith(suffix);
144
+ }
145
+ function hasTagWithPrefix(tags, prefix) {
146
+ if (tags == null || prefix == null) return false;
147
+ for (const key of Object.keys(tags)) {
148
+ if (key.startsWith(prefix)) return true;
149
+ }
150
+ return false;
151
+ }
152
+
153
+ // src/transform/prepare-tags.ts
154
+ function toSemicolonList(parts) {
155
+ return parts.filter((p) => p != null && p !== "").join("; ");
156
+ }
157
+ function restrictedAccessTags(tags) {
158
+ const restricted = [];
159
+ if (tags.access === "no") restricted.push("access");
160
+ if (tags.highway === "cycleway" && tags.bicycle === "no") restricted.push("bicycle");
161
+ if (tags.highway === "footway" && tags.foot === "no") restricted.push("foot");
162
+ return restricted;
163
+ }
164
+ function transformLifecycleTags(tags) {
165
+ if (!tags.highway) return;
166
+ if (tags.construction != null && ALLOWED_HIGHWAYS.has(tags.construction)) {
167
+ tags.highway = tags.construction;
168
+ tags.lifecycle = "construction";
169
+ tags.construction = void 0;
170
+ }
171
+ const constructionRestricted = restrictedAccessTags(tags);
172
+ if (constructionRestricted.length > 0) {
173
+ const text = `${tags["access:reason"] ?? ""} ${tags.description ?? ""} ${tags.note ?? ""}`.toLowerCase();
174
+ if (containsSubstring(text, "construction") || containsSubstring(text, "baustelle")) {
175
+ tags.lifecycle = "construction_no_access";
176
+ tags.description = toSemicolonList([tags.description, "TILDA-Hinweis: Weg gesperrt aufgrund einer Baustelle."]);
177
+ for (const t of constructionRestricted) tags[t] = void 0;
178
+ }
179
+ }
180
+ const blockedTerms = ["sperrung", "gesperrt", "blockiert", "blocked", "closure", "closed", "blocked off"];
181
+ const blockedRestricted = restrictedAccessTags(tags);
182
+ if (blockedRestricted.length > 0) {
183
+ const text = `${tags.description ?? ""} ${tags.note ?? ""}`.toLowerCase();
184
+ if (blockedTerms.some((term) => containsSubstring(text, term))) {
185
+ tags.lifecycle = "blocked";
186
+ tags.description = toSemicolonList([tags.description, "TILDA-Hinweis: Weg gesperrt (Sperrung)."]);
187
+ for (const t of blockedRestricted) tags[t] = void 0;
188
+ }
189
+ }
190
+ }
191
+ function transformCyclewayOppositeSchema(tags) {
192
+ if (tags.oneway !== "yes") return;
193
+ if (tags.cycleway === "opposite") {
194
+ tags.cycleway = "no";
195
+ tags["oneway:bicycle"] = "no";
196
+ return;
197
+ }
198
+ if (tags.cycleway === "opposite_lane") {
199
+ tags.cycleway = void 0;
200
+ tags["cycleway:right"] = "no";
201
+ tags["cycleway:left"] = "lane";
202
+ tags["oneway:bicycle"] = "no";
203
+ return;
204
+ }
205
+ if (tags.cycleway === "opposite_track") {
206
+ tags.cycleway = void 0;
207
+ tags["cycleway:right"] = "no";
208
+ tags["cycleway:left"] = "track";
209
+ tags["oneway:bicycle"] = "no";
210
+ }
211
+ }
212
+ function transformConstructionPrefix(tags) {
213
+ const constructionKeys = [];
214
+ for (const key of Object.keys(tags)) {
215
+ const value = tags[key];
216
+ if (value !== void 0 && key.startsWith("construction:")) constructionKeys.push([key, value]);
217
+ }
218
+ for (const [key, value] of constructionKeys) {
219
+ const baseTag = key.slice("construction:".length);
220
+ tags[baseTag] = value;
221
+ tags[key] = void 0;
222
+ if (baseTag.startsWith("cycleway:") || baseTag.startsWith("sidewalk:")) {
223
+ tags[`${baseTag}:lifecycle`] = "construction";
224
+ } else {
225
+ tags.lifecycle = "construction";
226
+ }
227
+ }
228
+ }
229
+ function transformCyclewayBothPostfix(tags) {
230
+ if (tags.cycleway === "no" && tags["cycleway:both"] == null && tags["cycleway:left"] == null && tags["cycleway:right"] == null) {
231
+ tags["cycleway:both"] = "no";
232
+ tags.cycleway = void 0;
233
+ }
234
+ }
235
+ function prepareTags(tags) {
236
+ transformLifecycleTags(tags);
237
+ transformCyclewayOppositeSchema(tags);
238
+ transformConstructionPrefix(tags);
239
+ transformCyclewayBothPostfix(tags);
240
+ }
241
+
242
+ // src/helpers/sanitize-for-logging.ts
243
+ function sanitizeForLogging(value, allowed, ignored = []) {
244
+ if (value == null) return void 0;
245
+ if (allowed.includes(value)) return value;
246
+ if (ignored.includes(value)) return void 0;
247
+ return DISALLOWED;
248
+ }
249
+ function removeDisallowedValue(value) {
250
+ return value === DISALLOWED ? void 0 : value;
251
+ }
252
+
253
+ // src/helpers/parse-length.ts
254
+ function splitUnit(str) {
255
+ if (str == null) return null;
256
+ const m = str.match(/^(-?[0-9.]+) ?([A-Za-z]*)$/);
257
+ if (!m) return null;
258
+ const val = Number(m[1]);
259
+ if (Number.isNaN(val)) return null;
260
+ const unit = m[2] === "" ? "m" : m[2];
261
+ return [val, unit];
262
+ }
263
+ function parseLength(length) {
264
+ if (length == null) return void 0;
265
+ const parsed = splitUnit(String(length));
266
+ if (!parsed) return void 0;
267
+ const [val, unit] = parsed;
268
+ if (unit === "cm") return val / 100;
269
+ if (unit === "m") return val;
270
+ if (unit === "km") return val * 1e3;
271
+ return void 0;
272
+ }
273
+
274
+ // src/sanitize/sanitize-road-tags.ts
275
+ var SEPARATION_ALLOWED = [
276
+ "no",
277
+ "bollard",
278
+ "flex_post",
279
+ "vertical_panel",
280
+ "studs",
281
+ "bump",
282
+ "planter",
283
+ "kerb",
284
+ "fence",
285
+ "jersey_barrier",
286
+ "guard_rail",
287
+ "structure",
288
+ "ditch",
289
+ "greenery",
290
+ "hedge",
291
+ "tree_row",
292
+ "cone",
293
+ "kerb;parking_lane",
294
+ "kerb;bollard",
295
+ "yes"
296
+ ];
297
+ var MARKING_ALLOWED = [
298
+ "solid_line",
299
+ "dashed_line",
300
+ "double_solid_line",
301
+ "barred_area",
302
+ "pictogram",
303
+ "surface"
304
+ ];
305
+ var TRAFFIC_MODE_ALLOWED = ["no", "motor_vehicle", "parking", "psv", "bicycle", "foot"];
306
+ var SURFACE_COLOR_ALLOWED = ["red", "green", "red;green", "no"];
307
+ function sided(tags, base, side) {
308
+ let value = tags[`${base}:${side}`] ?? tags[`${base}:both`];
309
+ if (side === "left") value = value ?? tags[base];
310
+ return value;
311
+ }
312
+ function surfaceColor(tags) {
313
+ const raw = tags["surface:colour"] ?? tags["surface:color"];
314
+ if (raw == null) return void 0;
315
+ const transformations = {
316
+ none: "no",
317
+ grey: "no",
318
+ gray: "no",
319
+ "#888888": "no",
320
+ silver: "no",
321
+ dimgray: "no",
322
+ "#b5565a": "red",
323
+ orange: "red",
324
+ "green;red": "red;green"
325
+ };
326
+ const value = transformations[raw] ?? raw;
327
+ return sanitizeForLogging(value, SURFACE_COLOR_ALLOWED);
328
+ }
329
+ function separation(tags, side) {
330
+ const raw = sided(tags, "separation", side);
331
+ if (raw == null) return void 0;
332
+ const transformations = {
333
+ separation_kerb: "bump",
334
+ lane_separator: "bump",
335
+ surface: "no",
336
+ "tree_row;kerb": "tree_row",
337
+ "kerb;tree_row": "tree_row",
338
+ "tree_row;kerb;parking_lane": "tree_row",
339
+ "grass_verge;tree_row": "tree_row",
340
+ "kerb;greenery": "kerb",
341
+ "parking_lane;kerb": "parking_lane",
342
+ "solid_line;parking_lane": "parking_lane"
343
+ };
344
+ const value = transformations[raw] ?? raw;
345
+ return sanitizeForLogging(value, SEPARATION_ALLOWED);
346
+ }
347
+ function marking(tags, side) {
348
+ const raw = sided(tags, "marking", side);
349
+ if (raw == null) return void 0;
350
+ return sanitizeForLogging(raw, MARKING_ALLOWED);
351
+ }
352
+ function trafficMode(tags, side) {
353
+ const raw = sided(tags, "traffic_mode", side);
354
+ if (raw == null) return void 0;
355
+ const transformations = {
356
+ "foot;bicycle": "foot",
357
+ motorized: "motor_vehicle",
358
+ none: "no"
359
+ };
360
+ const value = transformations[raw] ?? raw;
361
+ return sanitizeForLogging(value, TRAFFIC_MODE_ALLOWED);
362
+ }
363
+ function buffer(tags, side) {
364
+ const raw = sided(tags, "buffer", side);
365
+ if (raw == null) return void 0;
366
+ if (raw === "no" || raw === "none") return 0;
367
+ return parseLength(raw);
368
+ }
369
+ var SIDED_SANITIZERS = {
370
+ separation,
371
+ marking,
372
+ traffic_mode: trafficMode,
373
+ buffer
374
+ };
375
+
376
+ // src/categories/decision-view.ts
377
+ var IS_DECISION_VIEW = /* @__PURE__ */ Symbol("isDecisionView");
378
+ function resolveSided(source, key) {
379
+ let base;
380
+ let side;
381
+ if (key.endsWith("_left")) {
382
+ base = key.slice(0, -"_left".length);
383
+ side = "left";
384
+ } else if (key.endsWith("_right")) {
385
+ base = key.slice(0, -"_right".length);
386
+ side = "right";
387
+ }
388
+ if (base === void 0 || side === void 0) return { handled: false };
389
+ const sanitizer = SIDED_SANITIZERS[base];
390
+ if (!sanitizer) return { handled: false };
391
+ const value = sanitizer(source, side);
392
+ if (value === DISALLOWED) return { handled: true, value: void 0 };
393
+ return { handled: true, value };
394
+ }
395
+ function decisionTagsView(source) {
396
+ if (source[IS_DECISION_VIEW]) return source;
397
+ return new Proxy(source, {
398
+ get(target, key) {
399
+ if (key === IS_DECISION_VIEW) return true;
400
+ if (typeof key !== "string") return target[key];
401
+ const sided2 = resolveSided(target, key);
402
+ if (sided2.handled) return sided2.value;
403
+ const value = target[key];
404
+ return value === DISALLOWED ? void 0 : value;
405
+ },
406
+ set(target, key, value) {
407
+ if (typeof key === "string") target[key] = value;
408
+ else target[key] = value;
409
+ return true;
410
+ }
411
+ });
412
+ }
413
+
414
+ // src/categories/tag-predicate.ts
415
+ var pred = {
416
+ eq: (key, value) => ({ op: "eq", key, value }),
417
+ neq: (key, value) => ({ op: "neq", key, value }),
418
+ in: (key, values) => ({ op: "in", key, values }),
419
+ notIn: (key, values) => ({ op: "notIn", key, values }),
420
+ exists: (key) => ({ op: "exists", key }),
421
+ notExists: (key) => ({ op: "notExists", key }),
422
+ includes: (key, substring) => ({ op: "includes", key, substring }),
423
+ hasPrefix: (key, prefix) => ({ op: "hasPrefix", key, prefix }),
424
+ hasSuffix: (key, suffix) => ({ op: "hasSuffix", key, suffix }),
425
+ hasTagWithPrefix: (prefix) => ({ op: "hasTagWithPrefix", prefix }),
426
+ and: (...predicates) => ({ op: "and", predicates }),
427
+ or: (...predicates) => ({ op: "or", predicates }),
428
+ not: (predicate) => ({ op: "not", predicate }),
429
+ macro: (name) => ({ op: "macro", name }),
430
+ literal: (value) => ({ op: "literal", value })
431
+ };
432
+ function tagValue(tags, key) {
433
+ return tags[key];
434
+ }
435
+ function evalPredicate(tags, predicate, macros) {
436
+ switch (predicate.op) {
437
+ case "eq":
438
+ return tagValue(tags, predicate.key) === predicate.value || void 0;
439
+ case "neq":
440
+ return tagValue(tags, predicate.key) !== predicate.value || void 0;
441
+ case "in": {
442
+ const v = tagValue(tags, predicate.key);
443
+ return v != null && predicate.values.includes(v) || void 0;
444
+ }
445
+ case "notIn": {
446
+ const v = tagValue(tags, predicate.key);
447
+ return v != null && !predicate.values.includes(v) || void 0;
448
+ }
449
+ case "exists":
450
+ return tagValue(tags, predicate.key) != null || void 0;
451
+ case "notExists":
452
+ return tagValue(tags, predicate.key) == null || void 0;
453
+ case "includes":
454
+ return containsSubstring(tagValue(tags, predicate.key), predicate.substring) || void 0;
455
+ case "hasPrefix":
456
+ return hasPrefix(tagValue(tags, predicate.key), predicate.prefix) || void 0;
457
+ case "hasSuffix":
458
+ return hasSuffix(tagValue(tags, predicate.key), predicate.suffix) || void 0;
459
+ case "hasTagWithPrefix":
460
+ return hasTagWithPrefix(tags, predicate.prefix) || void 0;
461
+ case "and": {
462
+ let hasUndefined = false;
463
+ for (const child of predicate.predicates) {
464
+ const r = evalPredicate(tags, child, macros);
465
+ if (r === false) return false;
466
+ if (r !== true) hasUndefined = true;
467
+ }
468
+ return hasUndefined ? void 0 : true;
469
+ }
470
+ case "or": {
471
+ let hasUndefined = false;
472
+ for (const child of predicate.predicates) {
473
+ const r = evalPredicate(tags, child, macros);
474
+ if (r === true) return true;
475
+ if (r !== false) hasUndefined = true;
476
+ }
477
+ return hasUndefined ? void 0 : false;
478
+ }
479
+ case "not": {
480
+ const r = evalPredicate(tags, predicate.predicate, macros);
481
+ if (r === true) return false;
482
+ if (r === false) return true;
483
+ return void 0;
484
+ }
485
+ case "macro": {
486
+ const fn = macros[predicate.name];
487
+ if (!fn) throw new Error(`Unknown predicate macro: ${predicate.name}`);
488
+ return fn(tags);
489
+ }
490
+ case "literal":
491
+ return predicate.value;
492
+ default: {
493
+ const _exhaustive = predicate;
494
+ throw new Error(`Unknown predicate op: ${_exhaustive.op}`);
495
+ }
496
+ }
497
+ }
498
+ function evalPredicateStrict(tags, predicate, macros) {
499
+ const r = evalPredicate(tags, predicate, macros);
500
+ return r === true;
501
+ }
502
+
503
+ // src/helpers/extract-value-from-lanes.ts
504
+ function parseLanesValue(lanesValue) {
505
+ return lanesValue.split("|");
506
+ }
507
+ function findLaneIndex(tags) {
508
+ const cyclewayLanes = tags["cycleway:lanes"];
509
+ if (cyclewayLanes != null) {
510
+ const i = parseLanesValue(cyclewayLanes).indexOf("lane");
511
+ if (i !== -1) return i;
512
+ }
513
+ const bicycleLanes = tags["bicycle:lanes"];
514
+ if (bicycleLanes != null) {
515
+ const i = parseLanesValue(bicycleLanes).indexOf("designated");
516
+ if (i !== -1) return i;
517
+ }
518
+ return null;
519
+ }
520
+ function extractValueFromLanes(lanesTag, tags) {
521
+ const laneIndex = findLaneIndex(tags);
522
+ if (laneIndex == null) return void 0;
523
+ const raw = tags[lanesTag];
524
+ if (raw != null) {
525
+ const values = parseLanesValue(raw);
526
+ if (values[laneIndex] != null && values[laneIndex] !== "") return values[laneIndex];
527
+ }
528
+ return void 0;
529
+ }
530
+ function extractLastValueFromLanes(lanesValue) {
531
+ if (lanesValue == null) return void 0;
532
+ const lanes = parseLanesValue(lanesValue);
533
+ if (lanes.length > 0) return lanes[lanes.length - 1];
534
+ return void 0;
535
+ }
536
+
537
+ // src/helpers/sanitize-string.ts
538
+ function sanitizeString(value) {
539
+ if (value == null) return void 0;
540
+ let out = value.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
541
+ out = out.replace(/<\s*\/?\s*[A-Za-z][^>]*?>/g, (tag) => tag.replace(/</g, "(").replace(/>/g, ")"));
542
+ return out;
543
+ }
544
+
545
+ // src/helpers/sanitize-traffic-sign.ts
546
+ function stripWhitespaces(trafficSign) {
547
+ return trafficSign.replace(/, /g, ",").replace(/; /g, ";");
548
+ }
549
+ function sanitizeValue(value) {
550
+ return sanitizeString(stripWhitespaces(value));
551
+ }
552
+ function sanitizeTrafficSign(trafficSign) {
553
+ if (trafficSign == null) return void 0;
554
+ if (trafficSign === "no" || trafficSign === "none") return "none";
555
+ if (/^DE:\S/.test(trafficSign)) {
556
+ return sanitizeValue(trafficSign);
557
+ }
558
+ const substitutions = [
559
+ [/^DE: /, "DE:"],
560
+ [/^DE\./, "DE:"],
561
+ [/^D:/, "DE:"],
562
+ [/^D\./, "DE:"],
563
+ [/^de:/, "DE:"],
564
+ [/^DE1/, "DE:1"],
565
+ [/^DE2/, "DE:2"],
566
+ [/^2/, "DE:2"],
567
+ [/^1/, "DE:1"]
568
+ ];
569
+ for (const [pattern, replacement] of substitutions) {
570
+ if (pattern.test(trafficSign)) {
571
+ return sanitizeValue(trafficSign.replace(pattern, replacement));
572
+ }
573
+ }
574
+ return sanitizeString(trafficSign);
575
+ }
576
+
577
+ // src/derive/derive-traffic-signs.ts
578
+ function deriveTrafficSigns(tags) {
579
+ if (tags == null) {
580
+ return { traffic_sign: void 0, "traffic_sign:forward": void 0, "traffic_sign:backward": void 0 };
581
+ }
582
+ return {
583
+ traffic_sign: sanitizeTrafficSign(tags.traffic_sign ?? tags["traffic_sign:both"]),
584
+ "traffic_sign:forward": sanitizeTrafficSign(tags["traffic_sign:forward"]),
585
+ "traffic_sign:backward": sanitizeTrafficSign(tags["traffic_sign:backward"])
586
+ };
587
+ }
588
+
589
+ // src/categories/refine-predicates.ts
590
+ var CATEGORY_IS_SIDEPATH_PRED = pred.or(
591
+ pred.eq("is_sidepath", "yes"),
592
+ pred.exists("_parent_highway"),
593
+ pred.eq("footway", "sidewalk"),
594
+ pred.eq("path", "sidewalk"),
595
+ pred.eq("path", "sidepath"),
596
+ pred.eq("cycleway", "sidepath"),
597
+ pred.eq("steps", "sidewalk")
598
+ );
599
+ var SIDEPATH_ADJOINING_PRED = pred.and(
600
+ CATEGORY_IS_SIDEPATH_PRED,
601
+ pred.neq("is_sidepath", "no")
602
+ );
603
+ var SIDEPATH_ISOLATED_PRED = pred.or(
604
+ pred.eq("is_sidepath", "no"),
605
+ pred.eq("highway", "service"),
606
+ pred.eq("highway", "track")
607
+ );
608
+ var SIDEPATH_UNKNOWN_PRED = pred.and(
609
+ pred.neq("is_sidepath", "yes"),
610
+ pred.notExists("_parent_highway"),
611
+ pred.neq("footway", "sidewalk"),
612
+ pred.neq("path", "sidewalk"),
613
+ pred.neq("path", "sidepath"),
614
+ pred.neq("cycleway", "sidepath"),
615
+ pred.neq("steps", "sidewalk"),
616
+ pred.neq("is_sidepath", "no"),
617
+ pred.notIn("highway", ["service", "track"])
618
+ );
619
+ function advisoryOrExclusiveRefining(laneKey = "lane") {
620
+ return [
621
+ { idSuffix: "_advisory", match: pred.eq(laneKey, "advisory"), implicitOneWayConfidence: "high" },
622
+ { idSuffix: "_exclusive", match: pred.eq(laneKey, "exclusive"), implicitOneWayConfidence: "high" },
623
+ {
624
+ idSuffix: "_advisoryOrExclusive",
625
+ match: pred.or(pred.notExists(laneKey), pred.notIn(laneKey, ["advisory", "exclusive"]))
626
+ }
627
+ ];
628
+ }
629
+ var ADJOINING_OR_ISOLATED_REFINING = [
630
+ { idSuffix: "_adjoining", match: SIDEPATH_ADJOINING_PRED },
631
+ { idSuffix: "_isolated", match: SIDEPATH_ISOLATED_PRED },
632
+ { idSuffix: "_adjoiningOrIsolated", match: SIDEPATH_UNKNOWN_PRED }
633
+ ];
634
+
635
+ // src/categories/category-is-sidepath.ts
636
+ function categoryIsSidepath(tags) {
637
+ return tags.is_sidepath === "yes" || Boolean(tags._parent_highway) || // split off a centerline => treated as sidepath
638
+ tags.footway === "sidewalk" || tags.path === "sidewalk" || tags.path === "sidepath" || tags.cycleway === "sidepath" || tags.steps === "sidewalk";
639
+ }
640
+
641
+ // src/categories/predicates.ts
642
+ function hasBetweenLanesConditions(tags) {
643
+ if (tags._side === "left" || tags._side === "right") {
644
+ if (containsSubstring(tags["cycleway:lanes"], "|lane|")) return true;
645
+ if (containsSubstring(tags["bicycle:lanes"], "|designated|")) return true;
646
+ if (containsSubstring(tags.lanes, "|lane|")) return true;
647
+ if (tags._parent && containsSubstring(tags._parent["bicycle:lanes"], "|designated|")) return true;
648
+ }
649
+ return false;
650
+ }
651
+ function isCrossingPattern(tags) {
652
+ if (tags.highway === "cycleway" && tags.cycleway === "lane" && tags.lane === "crossing") return true;
653
+ if (tags.highway === "cycleway" && (tags.cycleway === "crossing" || tags.cycleway === "traffic_island")) return true;
654
+ if (tags.highway === "path" && (tags.path === "crossing" || tags.path === "traffic_island") && (tags.bicycle === "yes" || tags.bicycle === "designated")) return true;
655
+ if (tags.highway === "footway" && (tags.footway === "crossing" || tags.footway === "traffic_island") && (tags.bicycle === "yes" || tags.bicycle === "designated")) return true;
656
+ return false;
657
+ }
658
+ function bicycleRoadBase(tags) {
659
+ if (tags.bicycle_road === "yes") return true;
660
+ const trafficSign = sanitizeTrafficSign(tags.traffic_sign);
661
+ if (hasPrefix(trafficSign, "DE:244")) return true;
662
+ return void 0;
663
+ }
664
+ function bicycleRoadVehicleDestination(tags) {
665
+ if (!bicycleRoadBase(tags)) return void 0;
666
+ const trafficSign = sanitizeTrafficSign(tags.traffic_sign);
667
+ if (containsSubstring(trafficSign, "1020-30")) return true;
668
+ if (containsSubstring(trafficSign, "Kraftfahrzeuge-frei") || containsSubstring(trafficSign, "Kfz-Verkehr frei") || containsSubstring(trafficSign, "KFZ frei")) return true;
669
+ if (tags.vehicle === "destination" || tags.motor_vehicle === "destination" || tags.vehicle === "yes" || tags.motor_vehicle === "yes") return true;
670
+ return void 0;
671
+ }
672
+ function footwayBicycleYes(tags) {
673
+ if (isCrossingPattern(tags)) return false;
674
+ if (tags.highway !== "footway" && tags.highway !== "path") return void 0;
675
+ const hasBicycleAccess = tags.bicycle === "yes" || containsSubstring(sanitizeTrafficSign(tags.traffic_sign), "1022-10");
676
+ if (!hasBicycleAccess) return void 0;
677
+ if (tags["mtb:scale"] != null) {
678
+ const cleaned = tags["mtb:scale"].replace(/[+\-\s]/g, "");
679
+ const numeric = cleaned === "" ? NaN : Number(cleaned);
680
+ if (Number.isNaN(numeric)) return void 0;
681
+ if (numeric > 1) return void 0;
682
+ if (tags.traffic_sign == null && tags.is_sidepath == null) return void 0;
683
+ }
684
+ return true;
685
+ }
686
+ function crossing(tags) {
687
+ if (tags._length != null && tags._length > 100) return false;
688
+ return isCrossingPattern(tags) || void 0;
689
+ }
690
+ function implicitOneWay(tags) {
691
+ let result = tags._prefix === "cycleway" && tags._infix === "";
692
+ result = result && tags._parent?.oneway === "yes" && tags._parent?.["oneway:bicycle"] !== "no";
693
+ result = result && tags._side === "left";
694
+ return result || void 0;
695
+ }
696
+ function cyclewayOnHighwayAdvisoryOrExclusiveBase(tags) {
697
+ if (tags.highway === "cycleway") {
698
+ if (hasBetweenLanesConditions(tags)) {
699
+ if (containsSubstring(tags.lanes, "|lane|") && !hasSuffix(tags.lanes, "|lane")) return false;
700
+ if (tags._parent != null && containsSubstring(tags._parent["bicycle:lanes"], "|designated|") && !hasSuffix(tags._parent["bicycle:lanes"], "|designated")) return false;
701
+ const sourceWidth = tags._parent ? extractLastValueFromLanes(tags._parent["width:lanes"]) : void 0;
702
+ tags.width = tags.width ?? sourceWidth;
703
+ }
704
+ if (tags.cycleway === "lane" || tags.cycleway === "opposite_lane") return true;
705
+ }
706
+ return void 0;
707
+ }
708
+ function cyclewayOnHighwayBetweenLanes(tags) {
709
+ if (tags._side === "self") {
710
+ if (containsSubstring(tags["cycleway:lanes"], "|lane|")) return true;
711
+ if (containsSubstring(tags["bicycle:lanes"], "|designated|")) return true;
712
+ }
713
+ return void 0;
714
+ }
715
+ function cyclewayOnHighwayProtected(tags) {
716
+ if (isCrossingPattern(tags)) return false;
717
+ if (!categoryIsSidepath(tags)) return false;
718
+ if (tags.lane === "advisory") return false;
719
+ if (tags.cycleway === "share_busway" || tags.cycleway === "opposite_share_busway") return false;
720
+ const allowedSeparation = /* @__PURE__ */ new Set([
721
+ "bollard",
722
+ "flex_post",
723
+ "vertical_panel",
724
+ "studs",
725
+ "bump",
726
+ "planter",
727
+ "fence",
728
+ "jersey_barrier",
729
+ "guard_rail"
730
+ ]);
731
+ const trafficModeRight = tags.traffic_mode_right;
732
+ const separationLeft = tags.separation_left;
733
+ if (separationLeft != null && allowedSeparation.has(separationLeft)) {
734
+ if (trafficModeRight === "motor_vehicle") return false;
735
+ if (tags.segregated != null) return false;
736
+ return true;
737
+ }
738
+ const trafficModeLeft = tags.traffic_mode_left;
739
+ if (trafficModeLeft === "parking") {
740
+ if (tags.segregated != null) return false;
741
+ return true;
742
+ }
743
+ const separationRight = tags.separation_right;
744
+ if (trafficModeRight === "motor_vehicle" && separationRight != null && allowedSeparation.has(separationRight)) {
745
+ return true;
746
+ }
747
+ return void 0;
748
+ }
749
+ function sharedBusLaneBusWithBike(tags) {
750
+ if (isCrossingPattern(tags)) return false;
751
+ if (tags.highway !== "cycleway") return void 0;
752
+ const trafficSign = sanitizeTrafficSign(tags.traffic_sign);
753
+ const parentTrafficSign = tags._parent ? sanitizeTrafficSign(tags._parent.traffic_sign) : void 0;
754
+ if (tags.cycleway === "share_busway" || tags.cycleway === "opposite_share_busway" || hasPrefix(trafficSign, "DE:245") && (containsSubstring(trafficSign, "1022-10") || containsSubstring(trafficSign, "1022-14")) || hasPrefix(parentTrafficSign, "DE:245") && (containsSubstring(parentTrafficSign, "1022-10") || containsSubstring(parentTrafficSign, "1022-14"))) return true;
755
+ return void 0;
756
+ }
757
+ function sharedBusLaneBikeWithBus(tags) {
758
+ if (isCrossingPattern(tags)) return false;
759
+ if (tags.highway !== "cycleway") return void 0;
760
+ const trafficSign = sanitizeTrafficSign(tags.traffic_sign);
761
+ const parentTrafficSign = tags._parent ? sanitizeTrafficSign(tags._parent.traffic_sign) : void 0;
762
+ if (tags.lane === "share_busway" || hasPrefix(trafficSign, "DE:237") && (containsSubstring(trafficSign, "1024-14") || containsSubstring(trafficSign, "1026-32")) || hasPrefix(parentTrafficSign, "DE:237") && (containsSubstring(parentTrafficSign, "1024-14") || containsSubstring(parentTrafficSign, "1026-32"))) return true;
763
+ return void 0;
764
+ }
765
+ function needsClarification(tags) {
766
+ if (hasBetweenLanesConditions(tags)) return false;
767
+ if (tags.cycleway === "shared") return false;
768
+ if (tags.highway === "cycleway") return true;
769
+ if (tags.highway === "path" && tags.bicycle === "designated") {
770
+ if (tags.foot === "no") {
771
+ const excludedSurfaces = /* @__PURE__ */ new Set(["ground", "dirt", "fine_gravel", "gravel", "pebblestone", "earth"]);
772
+ if (hasTagWithPrefix(tags, "mtb:") || tags.mtb === "yes" || tags.surface != null && excludedSurfaces.has(tags.surface)) {
773
+ return false;
774
+ }
775
+ return true;
776
+ }
777
+ return true;
778
+ }
779
+ if (tags.highway === "footway" && tags.bicycle === "designated") return true;
780
+ return void 0;
781
+ }
782
+
783
+ // src/categories/category-specs.ts
784
+ function footAndCyclewaySharedProcess(tags) {
785
+ if (tags.highway === "service") {
786
+ tags.description = [tags.description, "TILDA-Hinweis: Radinfrastruktur auf einem Zufahrtsweg."].filter(Boolean).join("; ");
787
+ }
788
+ if (tags.highway === "track" || containsSubstring(tags.traffic_sign, "1026-36") || containsSubstring(tags.traffic_sign, "1026-37") || containsSubstring(tags.traffic_sign, "1026-38") || containsSubstring(tags.access, "agricultural") || containsSubstring(tags.motor_vehicle, "agricultural") || containsSubstring(tags.vehicle, "agricultural") || containsSubstring(tags.access, "forestry") || containsSubstring(tags.motor_vehicle, "forestry") || containsSubstring(tags.vehicle, "forestry")) {
789
+ tags.description = [tags.description, "TILDA-Hinweis: Radinfrastruktur geteilt mit land- und/oder forstwirtschaftlichem Verkehr."].filter(Boolean).join("; ");
790
+ }
791
+ }
792
+ function cyclewayOnHighwayBetweenLanesProcess(tags) {
793
+ const width = extractValueFromLanes("width:lanes", tags);
794
+ if (width) tags.width = width;
795
+ const surface = extractValueFromLanes("surface:lanes", tags);
796
+ if (surface) tags.surface = surface;
797
+ const surfaceColour = extractValueFromLanes("surface:colour:lanes", tags);
798
+ if (surfaceColour) tags["surface:colour"] = surfaceColour;
799
+ const smoothness = extractValueFromLanes("smoothness:lanes", tags);
800
+ if (smoothness) tags.smoothness = smoothness;
801
+ const sourceWidth = extractValueFromLanes("source:width:lanes", tags);
802
+ if (sourceWidth) tags["source:width"] = sourceWidth;
803
+ const trafficSign = extractValueFromLanes("traffic_sign:lanes", tags);
804
+ tags.traffic_sign = trafficSign ?? "never";
805
+ }
806
+ function sharedBusLaneBusWithBikeProcess(tags) {
807
+ const r = deriveTrafficSigns(tags._parent);
808
+ tags.traffic_sign = tags.traffic_sign ?? r.traffic_sign;
809
+ tags["traffic_sign:forward"] = tags["traffic_sign:forward"] ?? r["traffic_sign:forward"];
810
+ tags["traffic_sign:backward"] = tags["traffic_sign:backward"] ?? r["traffic_sign:backward"];
811
+ }
812
+ function sharedBusLaneBikeWithBusProcess(tags) {
813
+ tags.traffic_sign = tags.traffic_sign ?? (tags._parent ? tags._parent.traffic_sign : void 0);
814
+ }
815
+ var SIDEpath_GAP = [
816
+ {
817
+ key: "is_sidepath",
818
+ values: ["yes", "no"],
819
+ unlocksCategory: "_adjoining",
820
+ reason: "yes \u2192 adjoining (runs along a road); no \u2192 isolated (standalone path)"
821
+ }
822
+ ];
823
+ var LANE_GAP = [
824
+ {
825
+ key: "lane",
826
+ values: ["advisory", "exclusive"],
827
+ unlocksCategory: "_advisory",
828
+ reason: "advisory \u2192 Schutzstreifen; exclusive \u2192 Radfahrstreifen (transformed from cycleway:{side}:lane)"
829
+ }
830
+ ];
831
+ var NEEDS_CLARIFICATION_GAP_DISCRIMINATORS = [
832
+ { key: "segregated", values: ["yes"], unlocksCategory: "footAndCyclewaySegregated", reason: "Segregated foot/cycle path" },
833
+ { key: "traffic_sign", values: ["DE:241"], unlocksCategory: "footAndCyclewaySegregated", reason: "German segregated foot/cycle sign" },
834
+ { key: "segregated", values: ["no"], unlocksCategory: "footAndCyclewayShared", reason: "Shared foot/cycle path" },
835
+ { key: "traffic_sign", values: ["DE:240"], unlocksCategory: "footAndCyclewayShared", reason: "German shared foot/cycle sign" },
836
+ { key: "traffic_sign", values: ["DE:237"], unlocksCategory: "cycleway", reason: "German cycleway sign" },
837
+ { key: "cycleway", values: ["track", "opposite_track"], unlocksCategory: "cycleway", reason: "Separated cycle track tagging" },
838
+ { key: "cycleway", values: ["lane", "opposite_lane"], unlocksCategory: "cyclewayOnHighway_advisoryOrExclusive", reason: "On-highway cycle lane" },
839
+ { key: "bicycle", values: ["yes"], unlocksCategory: "footwayBicycleYes", reason: "Bicycle allowed on footway" }
840
+ ];
841
+ var FOOT_AND_CYCLEWAY_HIGHWAYS = ["cycleway", "path", "footway", "service", "track"];
842
+ var FOOT_AND_CYCLEWAY_SHARED_MATCH = pred.or(
843
+ pred.and(
844
+ pred.eq("highway", "cycleway"),
845
+ pred.eq("cycleway", "track"),
846
+ pred.or(pred.eq("segregated", "no"), pred.includes("traffic_sign", "240"))
847
+ ),
848
+ pred.and(
849
+ pred.in("highway", [...FOOT_AND_CYCLEWAY_HIGHWAYS]),
850
+ pred.or(
851
+ pred.and(pred.eq("segregated", "no"), pred.eq("bicycle", "designated"), pred.eq("foot", "designated")),
852
+ pred.and(pred.eq("segregated", "no"), pred.eq("bicycle", "yes"), pred.eq("foot", "yes")),
853
+ pred.includes("traffic_sign", "240")
854
+ )
855
+ )
856
+ );
857
+ var FOOT_AND_CYCLEWAY_SEGREGATED_MATCH = pred.or(
858
+ pred.and(
859
+ pred.eq("highway", "cycleway"),
860
+ pred.eq("cycleway", "track"),
861
+ pred.or(pred.eq("segregated", "yes"), pred.includes("traffic_sign", "241"))
862
+ ),
863
+ pred.and(
864
+ pred.in("highway", ["cycleway", "path", "footway"]),
865
+ pred.or(
866
+ pred.and(pred.eq("segregated", "yes"), pred.eq("bicycle", "designated"), pred.eq("foot", "designated")),
867
+ pred.and(pred.eq("segregated", "yes"), pred.eq("bicycle", "yes"), pred.eq("foot", "yes")),
868
+ pred.and(pred.includes("traffic_sign", "241"), pred.neq("highway", "footway"))
869
+ )
870
+ ),
871
+ pred.macro("foot_and_cycleway_segregated_separation")
872
+ );
873
+ var CYCLEWAY_SEPARATED_BASE_MATCH = pred.or(
874
+ pred.and(
875
+ pred.eq("highway", "cycleway"),
876
+ pred.or(
877
+ pred.eq("cycleway", "track"),
878
+ pred.eq("cycleway", "opposite_track"),
879
+ pred.exists("is_sidepath")
880
+ )
881
+ ),
882
+ pred.and(
883
+ pred.in("highway", [
884
+ "living_street",
885
+ "pedestrian",
886
+ "service",
887
+ "track",
888
+ "bridleway",
889
+ "path",
890
+ "footway",
891
+ "cycleway"
892
+ ]),
893
+ pred.includes("traffic_sign", "237")
894
+ )
895
+ );
896
+ var CATEGORY_SPECS = [
897
+ {
898
+ id: "data_no",
899
+ infrastructureExists: false,
900
+ implicitOneWay: false,
901
+ implicitOneWayConfidence: "not_applicable",
902
+ copySurfaceSmoothnessFromParent: false,
903
+ match: pred.in("cycleway", ["no", "none"])
904
+ },
905
+ {
906
+ id: "separate_geometry",
907
+ infrastructureExists: false,
908
+ implicitOneWay: false,
909
+ implicitOneWayConfidence: "not_applicable",
910
+ copySurfaceSmoothnessFromParent: false,
911
+ match: pred.eq("cycleway", "separate")
912
+ },
913
+ {
914
+ id: "not_expected",
915
+ infrastructureExists: false,
916
+ implicitOneWay: false,
917
+ implicitOneWayConfidence: "not_applicable",
918
+ copySurfaceSmoothnessFromParent: false,
919
+ // Uses transform-time _prefix/_parent fields not expressible as tag predicates.
920
+ match: pred.macro("implicit_one_way")
921
+ },
922
+ {
923
+ id: "cyclewayOnHighwayProtected",
924
+ infrastructureExists: true,
925
+ implicitOneWay: true,
926
+ implicitOneWayConfidence: "medium",
927
+ copySurfaceSmoothnessFromParent: true,
928
+ // Complex separation/traffic_mode matrix with allowedSeparation set.
929
+ match: pred.macro("cycleway_on_highway_protected")
930
+ },
931
+ {
932
+ id: "cyclewayLink",
933
+ infrastructureExists: true,
934
+ implicitOneWay: true,
935
+ implicitOneWayConfidence: "low",
936
+ copySurfaceSmoothnessFromParent: false,
937
+ match: pred.and(pred.eq("highway", "cycleway"), pred.eq("cycleway", "link"))
938
+ },
939
+ {
940
+ id: "crossing",
941
+ infrastructureExists: true,
942
+ implicitOneWay: true,
943
+ implicitOneWayConfidence: "low",
944
+ copySurfaceSmoothnessFromParent: true,
945
+ // Applies _length > 100 exclusion before crossing pattern check.
946
+ match: pred.macro("crossing")
947
+ },
948
+ {
949
+ id: "bicycleRoad_vehicleDestination",
950
+ infrastructureExists: true,
951
+ implicitOneWay: false,
952
+ implicitOneWayConfidence: "high",
953
+ copySurfaceSmoothnessFromParent: true,
954
+ // Requires sanitizeTrafficSign for DE:244 prefix and German text variants.
955
+ match: pred.macro("bicycle_road_vehicle_destination")
956
+ },
957
+ {
958
+ id: "bicycleRoad",
959
+ infrastructureExists: true,
960
+ implicitOneWay: false,
961
+ implicitOneWayConfidence: "high",
962
+ copySurfaceSmoothnessFromParent: true,
963
+ // Requires sanitizeTrafficSign for DE:244 prefix.
964
+ match: pred.macro("bicycle_road_base")
965
+ },
966
+ {
967
+ id: "sharedBusLaneBikeWithBus",
968
+ infrastructureExists: true,
969
+ implicitOneWay: true,
970
+ implicitOneWayConfidence: "high",
971
+ copySurfaceSmoothnessFromParent: true,
972
+ // Parent traffic_sign sanitization and DE:237/1024-14/1026-32 combos.
973
+ match: pred.macro("shared_bus_lane_bike_with_bus"),
974
+ process: sharedBusLaneBikeWithBusProcess
975
+ },
976
+ {
977
+ id: "sharedBusLaneBusWithBike",
978
+ infrastructureExists: true,
979
+ implicitOneWay: true,
980
+ implicitOneWayConfidence: "high",
981
+ copySurfaceSmoothnessFromParent: true,
982
+ // Parent traffic_sign sanitization and DE:245/1022 combos.
983
+ match: pred.macro("shared_bus_lane_bus_with_bike"),
984
+ process: sharedBusLaneBusWithBikeProcess
985
+ },
986
+ {
987
+ id: "pedestrianAreaBicycleYes",
988
+ infrastructureExists: true,
989
+ implicitOneWay: false,
990
+ implicitOneWayConfidence: "high",
991
+ copySurfaceSmoothnessFromParent: false,
992
+ match: pred.and(
993
+ pred.eq("highway", "pedestrian"),
994
+ pred.in("bicycle", ["yes", "designated"])
995
+ )
996
+ },
997
+ {
998
+ id: "sharedMotorVehicleLane",
999
+ infrastructureExists: true,
1000
+ implicitOneWay: false,
1001
+ implicitOneWayConfidence: "high",
1002
+ copySurfaceSmoothnessFromParent: true,
1003
+ match: pred.and(pred.eq("highway", "cycleway"), pred.eq("cycleway", "shared_lane"))
1004
+ },
1005
+ {
1006
+ id: "cyclewayOnHighwayBetweenLanes",
1007
+ infrastructureExists: true,
1008
+ implicitOneWay: true,
1009
+ implicitOneWayConfidence: "high",
1010
+ copySurfaceSmoothnessFromParent: true,
1011
+ // Pipe-delimited lane substring checks on _side=self only.
1012
+ match: pred.macro("cycleway_on_highway_between_lanes"),
1013
+ process: cyclewayOnHighwayBetweenLanesProcess
1014
+ },
1015
+ {
1016
+ id: "footAndCyclewayShared",
1017
+ infrastructureExists: true,
1018
+ implicitOneWay: true,
1019
+ implicitOneWayConfidence: "low",
1020
+ copySurfaceSmoothnessFromParent: false,
1021
+ excludes: [pred.macro("is_crossing_pattern")],
1022
+ match: FOOT_AND_CYCLEWAY_SHARED_MATCH,
1023
+ process: footAndCyclewaySharedProcess,
1024
+ refining: [...ADJOINING_OR_ISOLATED_REFINING],
1025
+ gapDiscriminators: SIDEpath_GAP
1026
+ },
1027
+ {
1028
+ id: "footAndCyclewaySegregated",
1029
+ infrastructureExists: true,
1030
+ implicitOneWay: true,
1031
+ implicitOneWayConfidence: "low",
1032
+ copySurfaceSmoothnessFromParent: false,
1033
+ excludes: [pred.macro("is_crossing_pattern")],
1034
+ match: FOOT_AND_CYCLEWAY_SEGREGATED_MATCH,
1035
+ refining: [...ADJOINING_OR_ISOLATED_REFINING],
1036
+ gapDiscriminators: SIDEpath_GAP
1037
+ },
1038
+ {
1039
+ id: "cycleway",
1040
+ infrastructureExists: true,
1041
+ implicitOneWay: false,
1042
+ implicitOneWayConfidence: "low",
1043
+ copySurfaceSmoothnessFromParent: false,
1044
+ excludes: [pred.macro("is_crossing_pattern"), pred.eq("cycleway", "lane")],
1045
+ match: CYCLEWAY_SEPARATED_BASE_MATCH,
1046
+ refining: [...ADJOINING_OR_ISOLATED_REFINING],
1047
+ gapDiscriminators: SIDEpath_GAP
1048
+ },
1049
+ {
1050
+ id: "cyclewayOnHighway_advisoryOrExclusive",
1051
+ infrastructureExists: true,
1052
+ implicitOneWay: true,
1053
+ implicitOneWayConfidence: "medium",
1054
+ copySurfaceSmoothnessFromParent: true,
1055
+ // Side-effect: may copy width from parent width:lanes when between-lanes.
1056
+ match: pred.macro("cycleway_on_highway_advisory_or_exclusive_base"),
1057
+ refining: advisoryOrExclusiveRefining(),
1058
+ gapDiscriminators: LANE_GAP
1059
+ },
1060
+ {
1061
+ id: "footwayBicycleYes",
1062
+ infrastructureExists: true,
1063
+ implicitOneWay: true,
1064
+ implicitOneWayConfidence: "low",
1065
+ copySurfaceSmoothnessFromParent: false,
1066
+ // mtb:scale numeric parsing and sanitizeTrafficSign for 1022-10.
1067
+ match: pred.macro("footway_bicycle_yes"),
1068
+ refining: [...ADJOINING_OR_ISOLATED_REFINING],
1069
+ gapDiscriminators: SIDEpath_GAP
1070
+ },
1071
+ {
1072
+ id: "needsClarification",
1073
+ infrastructureExists: true,
1074
+ implicitOneWay: false,
1075
+ implicitOneWayConfidence: "low",
1076
+ copySurfaceSmoothnessFromParent: false,
1077
+ // Complex highway/path/footway fallback with mtb: surface exclusions.
1078
+ match: pred.macro("needs_clarification"),
1079
+ gapDiscriminators: NEEDS_CLARIFICATION_GAP_DISCRIMINATORS
1080
+ }
1081
+ ];
1082
+ var CATEGORY_MACROS = {
1083
+ implicit_one_way: implicitOneWay,
1084
+ bicycle_road_base: bicycleRoadBase,
1085
+ bicycle_road_vehicle_destination: bicycleRoadVehicleDestination,
1086
+ is_crossing_pattern: (tags) => isCrossingPattern(tags) || void 0,
1087
+ foot_and_cycleway_segregated_separation: footAndCyclewaySegregatedSeparation,
1088
+ crossing,
1089
+ cycleway_on_highway_advisory_or_exclusive_base: cyclewayOnHighwayAdvisoryOrExclusiveBase,
1090
+ cycleway_on_highway_between_lanes: cyclewayOnHighwayBetweenLanes,
1091
+ cycleway_on_highway_protected: cyclewayOnHighwayProtected,
1092
+ shared_bus_lane_bus_with_bike: sharedBusLaneBusWithBike,
1093
+ shared_bus_lane_bike_with_bus: sharedBusLaneBikeWithBus,
1094
+ needs_clarification: needsClarification,
1095
+ footway_bicycle_yes: footwayBicycleYes
1096
+ };
1097
+ function footAndCyclewaySegregatedSeparation(tags) {
1098
+ const separationRight = tags.separation_right;
1099
+ let separationCondition = true;
1100
+ if (separationRight != null) separationCondition = separationRight === "no";
1101
+ const trafficModeCondition = tags.traffic_mode_right === "foot";
1102
+ if (tags.highway === "cycleway" && trafficModeCondition && separationCondition) return true;
1103
+ return void 0;
1104
+ }
1105
+ function specByCategoryId(id) {
1106
+ for (const spec of CATEGORY_SPECS) {
1107
+ if (spec.id === id) return spec;
1108
+ if (spec.refining?.some((c) => resolveRefinedId(spec, c) === id)) {
1109
+ return { ...spec, id };
1110
+ }
1111
+ }
1112
+ return void 0;
1113
+ }
1114
+ function resolveRefinedId(spec, child) {
1115
+ if (child.idSuffix === "_advisoryOrExclusive" && spec.id.endsWith("_advisoryOrExclusive")) {
1116
+ return spec.id;
1117
+ }
1118
+ const base = spec.id.replace(/_advisoryOrExclusive$/, "");
1119
+ return `${base}${child.idSuffix}`;
1120
+ }
1121
+ function isIncompleteCategoryId(categoryId) {
1122
+ return categoryId === "needsClarification" || categoryId.endsWith("_adjoiningOrIsolated") || categoryId.endsWith("_advisoryOrExclusive");
1123
+ }
1124
+ function specsWithGapDiscriminators() {
1125
+ return CATEGORY_SPECS.filter((s) => s.gapDiscriminators != null && s.gapDiscriminators.length > 0);
1126
+ }
1127
+
1128
+ // src/categories/compile-category-specs.ts
1129
+ var MACROS = { ...CATEGORY_MACROS };
1130
+ function compileMatch(spec) {
1131
+ if (!spec.match) return () => void 0;
1132
+ const excludes = spec.excludes ?? [];
1133
+ return (tags) => {
1134
+ for (const ex of excludes) {
1135
+ if (evalPredicateStrict(tags, ex, MACROS)) return false;
1136
+ }
1137
+ return evalPredicate(tags, spec.match, MACROS);
1138
+ };
1139
+ }
1140
+ function compileRefiningMatch(predicate) {
1141
+ return (tags) => evalPredicateStrict(tags, predicate, MACROS);
1142
+ }
1143
+ function mkCategory(spec, id, condition, copyFromParent) {
1144
+ return {
1145
+ id,
1146
+ infrastructureExists: spec.infrastructureExists,
1147
+ implicitOneWay: spec.implicitOneWay,
1148
+ implicitOneWayConfidence: spec.implicitOneWayConfidence,
1149
+ copySurfaceSmoothnessFromParent: copyFromParent ?? spec.copySurfaceSmoothnessFromParent,
1150
+ condition,
1151
+ process: spec.process
1152
+ };
1153
+ }
1154
+ function resolveRefinedId2(spec, child) {
1155
+ if (child.idSuffix === "_advisoryOrExclusive" && spec.id.endsWith("_advisoryOrExclusive")) {
1156
+ return spec.id;
1157
+ }
1158
+ const base = spec.id.replace(/_advisoryOrExclusive$/, "");
1159
+ return `${base}${child.idSuffix}`;
1160
+ }
1161
+ function expandRefining(spec, baseMatch) {
1162
+ return spec.refining.map((child) => {
1163
+ const refineMatch = compileRefiningMatch(child.match);
1164
+ const condition = (tags) => baseMatch(tags) && refineMatch(tags) || void 0;
1165
+ const childSpec = child.implicitOneWayConfidence ? { ...spec, implicitOneWayConfidence: child.implicitOneWayConfidence } : spec;
1166
+ const copyFromParent = ["_adjoining", "_isolated", "_adjoiningOrIsolated"].includes(child.idSuffix) ? false : void 0;
1167
+ return mkCategory(childSpec, resolveRefinedId2(spec, child), condition, copyFromParent);
1168
+ });
1169
+ }
1170
+ function expandSpec(spec) {
1171
+ const baseMatch = compileMatch(spec);
1172
+ if (!spec.refining?.length) {
1173
+ return [mkCategory(spec, spec.id, baseMatch)];
1174
+ }
1175
+ return expandRefining(spec, baseMatch);
1176
+ }
1177
+ var COMPILED_CATEGORY_DEFINITIONS = CATEGORY_SPECS.flatMap(expandSpec);
1178
+ function sidepathDiscriminatorKnown(tags) {
1179
+ if (tags.is_sidepath === "yes" || tags.is_sidepath === "no") return true;
1180
+ if (tags.highway === "service" || tags.highway === "track") return true;
1181
+ return false;
1182
+ }
1183
+ function laneDiscriminatorKnown(tags) {
1184
+ return tags.lane === "advisory" || tags.lane === "exclusive";
1185
+ }
1186
+
1187
+ // src/categories/bikelane-categories.ts
1188
+ var CATEGORY_DEFINITIONS = COMPILED_CATEGORY_DEFINITIONS;
1189
+ function categorizeBikelane(tags) {
1190
+ for (const category of CATEGORY_DEFINITIONS) {
1191
+ if (category.condition(decisionTagsView(tags))) {
1192
+ category.process?.(tags);
1193
+ return category;
1194
+ }
1195
+ }
1196
+ return null;
1197
+ }
1198
+
1199
+ // src/derive/derive-oneway.ts
1200
+ function deriveOneway(tags, category) {
1201
+ if (tags["oneway:bicycle"] === "yes") return "yes";
1202
+ if (tags["oneway:bicycle"] === "no") {
1203
+ return tags.oneway === "yes" ? "car_not_bike" : "no";
1204
+ }
1205
+ if (tags.oneway === "yes" || tags.oneway === "no") return tags.oneway;
1206
+ if (tags.highway === "service" || tags.highway === "track") return "assumed_no";
1207
+ if (category.implicitOneWay) return "implicit_yes";
1208
+ return "assumed_no";
1209
+ }
1210
+
1211
+ // src/sanitize/sanitize-surface.ts
1212
+ var SURFACE_ALLOWED = [
1213
+ "asphalt",
1214
+ "paved",
1215
+ "unpaved",
1216
+ "concrete",
1217
+ "concrete:plates",
1218
+ "concrete:lanes",
1219
+ "paving_stones",
1220
+ "paving_stones:lanes",
1221
+ "sett",
1222
+ "bricks",
1223
+ "stone",
1224
+ "ground",
1225
+ "grass",
1226
+ "sand",
1227
+ "compacted",
1228
+ "fine_gravel",
1229
+ "gravel",
1230
+ "pebblestone",
1231
+ "wood",
1232
+ "woodchips",
1233
+ "metal",
1234
+ "metal_grid",
1235
+ "plastic",
1236
+ "rubber",
1237
+ "grass_paver"
1238
+ ];
1239
+ var SURFACE_IGNORED = ["ice", "snow", "salt"];
1240
+ function sanitizeSurface(tags) {
1241
+ if (tags.surface == null) return void 0;
1242
+ const transformations = {
1243
+ earth: "ground",
1244
+ mud: "ground",
1245
+ clay: "ground",
1246
+ dirt: "ground",
1247
+ "dirt/sand": "ground",
1248
+ cobblestone: "large_sett",
1249
+ unhewn_cobblestone: "large_sett",
1250
+ "cobblestone:flattened": "large_sett",
1251
+ rock: "stone",
1252
+ "stone:plates": "stone",
1253
+ "paving_stones:20": "paving_stones",
1254
+ "paving_stones:30": "paving_stones",
1255
+ tartan: "rubber"
1256
+ };
1257
+ if (transformations[tags.surface]) return transformations[tags.surface];
1258
+ if (tags.surface === "sett") {
1259
+ const size = parseLength(tags["sett:length"]);
1260
+ if (size != null && size <= 0.08) return "mosaic_sett";
1261
+ if (size != null && size <= 0.13) return "small_sett";
1262
+ if (size != null && size > 0.13) return "large_sett";
1263
+ }
1264
+ return sanitizeForLogging(tags.surface, SURFACE_ALLOWED, SURFACE_IGNORED);
1265
+ }
1266
+
1267
+ // src/derive/derive-surface.ts
1268
+ function deriveSurface(tags) {
1269
+ if (tags.surface == null) return {};
1270
+ const surface = sanitizeSurface(tags);
1271
+ if (surface === DISALLOWED) return {};
1272
+ return { surface, surface_source: "tag", surface_confidence: "high" };
1273
+ }
1274
+ function deriveBikelaneSurface(tags, category) {
1275
+ const own = deriveSurface(tags);
1276
+ if (own.surface != null) {
1277
+ return { surface: own.surface, surface_source: "tag", surface_confidence: "high" };
1278
+ }
1279
+ const parent = tags._parent;
1280
+ if (category.copySurfaceSmoothnessFromParent && parent != null) {
1281
+ const parentSurface = deriveSurface(parent);
1282
+ if (parentSurface.surface != null) {
1283
+ return { surface: parentSurface.surface, surface_source: "parent_highway_tag", surface_confidence: "high" };
1284
+ }
1285
+ }
1286
+ return {};
1287
+ }
1288
+
1289
+ // src/derive/derive-smoothness.ts
1290
+ var SMOOTHNESS_DIRECT = /* @__PURE__ */ new Set(["excellent", "good", "intermediate", "bad", "very_bad"]);
1291
+ var SMOOTHNESS_NORMALIZATION = {
1292
+ very_good: "excellent",
1293
+ impassable: "very_bad",
1294
+ horrible: "very_bad",
1295
+ very_horrible: "very_bad"
1296
+ };
1297
+ function normalizeSmoothness(smoothness) {
1298
+ if (smoothness != null) {
1299
+ if (SMOOTHNESS_DIRECT.has(smoothness)) return { smoothness, smoothness_source: "tag", smoothness_confidence: "high" };
1300
+ const normalized = SMOOTHNESS_NORMALIZATION[smoothness];
1301
+ if (normalized) return { smoothness: normalized, smoothness_source: "tag_normalized", smoothness_confidence: "high" };
1302
+ }
1303
+ return {};
1304
+ }
1305
+ var SURFACE_TO_SMOOTHNESS = {
1306
+ "cobblestone:flattened": "bad",
1307
+ "concrete:lanes": "intermediate",
1308
+ "concrete:plates": "intermediate",
1309
+ "stone:plates": "intermediate",
1310
+ asphalt: "good",
1311
+ brick: "bad",
1312
+ cobblestone: "very_bad",
1313
+ compacted: "intermediate",
1314
+ concrete: "intermediate",
1315
+ dirt: "bad",
1316
+ earth: "bad",
1317
+ fine_gravel: "intermediate",
1318
+ granite: "intermediate",
1319
+ grass_paver: "bad",
1320
+ grass: "bad",
1321
+ gravel: "bad",
1322
+ "gravel:lanes": "bad",
1323
+ ground: "bad",
1324
+ metal_grid: "bad",
1325
+ metal: "good",
1326
+ mud: "very_bad",
1327
+ paved: "intermediate",
1328
+ paving_stones: "intermediate",
1329
+ pebblestone: "very_bad",
1330
+ rock: "very_bad",
1331
+ rubber: "good",
1332
+ sand: "very_bad",
1333
+ sett: "bad",
1334
+ stepping_stones: "bad",
1335
+ stone: "bad",
1336
+ tartan: "good",
1337
+ unhewn_cobblestone: "very_bad",
1338
+ unpaved: "bad",
1339
+ wood: "intermediate",
1340
+ woodchips: "very_bad"
1341
+ };
1342
+ var SURFACE_TO_SMOOTHNESS_NON_STANDARD = {
1343
+ ":plates": "intermediate",
1344
+ "asphalt;compacted": "intermediate",
1345
+ "asphalt;paving_stones": "intermediate",
1346
+ sandstone: "intermediate",
1347
+ "asphalt:lanes": "intermediate",
1348
+ "asphalt|sett": "very_bad",
1349
+ "cobblestone;ground": "bad",
1350
+ "cobblestone;asphalt": "bad",
1351
+ "compacted;paving_s": "bad",
1352
+ "compacted;paving_stones": "intermediate",
1353
+ "dirt;grass": "bad",
1354
+ "dirt/sand": "very_bad",
1355
+ "dirt;sand": "very_bad",
1356
+ "3": "bad",
1357
+ "grass;gravel": "bad",
1358
+ "ground;grass": "bad",
1359
+ "grass;ground": "bad",
1360
+ "gravel:tracks": "bad",
1361
+ "gravel;grass": "bad",
1362
+ "fine_gravel;grass": "bad",
1363
+ "fine_gravel;ground": "bad",
1364
+ "gravel;ground": "bad",
1365
+ "gravel; grass": "bad",
1366
+ clay: "bad",
1367
+ "paving_s;sett": "bad",
1368
+ "paving_stones;asphalt": "intermediate",
1369
+ "paving_stones;sett": "bad",
1370
+ "paving_stones:30": "intermediate",
1371
+ "sett;paving_s": "bad",
1372
+ "sett;paving_stones;cobblestone:flattened": "bad",
1373
+ "sett;paving_stones": "bad",
1374
+ grass_unpaved: "bad",
1375
+ grund: "bad",
1376
+ macadam: "intermediate",
1377
+ paving_stonees: "intermediate",
1378
+ tiles: "bad"
1379
+ };
1380
+ function deriveSmoothnessFromSurface(surface) {
1381
+ if (!surface) return {};
1382
+ const smoothness = SURFACE_TO_SMOOTHNESS[surface] ?? SURFACE_TO_SMOOTHNESS_NON_STANDARD[surface];
1383
+ if (smoothness) return { smoothness, smoothness_source: "surface_to_smoothness", smoothness_confidence: "medium" };
1384
+ return {};
1385
+ }
1386
+ var TRACKTYPE_TO_SMOOTHNESS = {
1387
+ grade1: "good",
1388
+ grade2: "intermediate",
1389
+ grade3: "bad",
1390
+ grade4: "bad",
1391
+ grade5: "very_bad"
1392
+ };
1393
+ function deriveSmoothnessFromTrackType(type) {
1394
+ if (!type) return {};
1395
+ const smoothness = TRACKTYPE_TO_SMOOTHNESS[type];
1396
+ if (smoothness) return { smoothness, smoothness_source: "tracktype_to_smoothness", smoothness_confidence: "medium" };
1397
+ return {};
1398
+ }
1399
+ function deriveSmoothnessFromMtbScale(scale) {
1400
+ if (!scale) return {};
1401
+ if (scale === "0" || scale === "0+" || scale === "0-") {
1402
+ return { smoothness: "bad", smoothness_source: "mtb:scale_to_smoothness", smoothness_confidence: "medium" };
1403
+ }
1404
+ return { smoothness: "very_bad", smoothness_source: "mtb:scale_to_smoothness", smoothness_confidence: "medium" };
1405
+ }
1406
+ function deriveSmoothness(tags) {
1407
+ let result = normalizeSmoothness(tags.smoothness);
1408
+ if (result.smoothness == null) result = deriveSmoothnessFromSurface(tags.surface);
1409
+ if (result.smoothness == null) result = deriveSmoothnessFromTrackType(tags.tracktype);
1410
+ if (result.smoothness == null) result = deriveSmoothnessFromMtbScale(tags["mtb:scale"]);
1411
+ return result;
1412
+ }
1413
+ function deriveBikelaneSmoothness(tags, category) {
1414
+ const own = deriveSmoothness(tags);
1415
+ let { smoothness, smoothness_source, smoothness_confidence } = own;
1416
+ let applyParent = false;
1417
+ const parent = tags._parent;
1418
+ if (category.copySurfaceSmoothnessFromParent && parent != null) {
1419
+ const parentResult = deriveSmoothness(parent);
1420
+ if (smoothness == null && parentResult.smoothness != null) {
1421
+ if (tags.surface == null || tags.surface === parent.surface) applyParent = true;
1422
+ }
1423
+ const okSources = smoothness_source === "tag" || smoothness_source === "tag_normalized";
1424
+ const surfaceMatchesParent = tags.surface != null && tags.surface === parent.surface;
1425
+ if (!okSources && surfaceMatchesParent && parentResult.smoothness != null) applyParent = true;
1426
+ if (applyParent) {
1427
+ smoothness = parentResult.smoothness;
1428
+ smoothness_source = parentResult.smoothness_source != null ? `parent_highway_${parentResult.smoothness_source}` : void 0;
1429
+ smoothness_confidence = parentResult.smoothness_confidence;
1430
+ }
1431
+ }
1432
+ if (smoothness != null && smoothness_source != null && smoothness_confidence != null) {
1433
+ return { smoothness, smoothness_source, smoothness_confidence };
1434
+ }
1435
+ return {};
1436
+ }
1437
+
1438
+ // src/derive/derive-traffic-mode.ts
1439
+ var DIRECTIONAL_PARKING_INFERENCE_CATEGORIES = /* @__PURE__ */ new Set([
1440
+ "cyclewayOnHighway_advisory",
1441
+ "cyclewayOnHighway_advisoryOrExclusive",
1442
+ "cyclewayOnHighway_exclusive",
1443
+ "cyclewayOnHighwayBetweenLanes",
1444
+ "cyclewayOnHighwayProtected"
1445
+ ]);
1446
+ var PARKING_ALLOWED = ["no", "yes", "lane", "street_side", "on_kerb", "half_on_kerb", "shoulder", "separate"];
1447
+ function sanitizeParking(value) {
1448
+ if (value == null) return void 0;
1449
+ return sanitizeForLogging(value, PARKING_ALLOWED);
1450
+ }
1451
+ function inferTrafficModeFromParking(centerlineTags, side) {
1452
+ const raw = centerlineTags[`parking:${side}`] ?? centerlineTags["parking:both"];
1453
+ const value = sanitizeParking(raw);
1454
+ if (removeDisallowedValue(value) == null) return void 0;
1455
+ if (value === "no") return void 0;
1456
+ return "parking";
1457
+ }
1458
+ function deriveTrafficMode(bikelaneTags, centerlineTags, categoryId, side) {
1459
+ const left = removeDisallowedValue(trafficMode(bikelaneTags, "left"));
1460
+ const right = removeDisallowedValue(trafficMode(bikelaneTags, "right"));
1461
+ if (left != null || right != null) {
1462
+ return { traffic_mode_left: left, traffic_mode_right: right };
1463
+ }
1464
+ const inferredLeft = inferTrafficModeFromParking(centerlineTags, "left");
1465
+ const inferredRight = inferTrafficModeFromParking(centerlineTags, "right");
1466
+ if (categoryId === "bicycleRoad" || categoryId === "bicycleRoad_vehicleDestination") {
1467
+ return { traffic_mode_left: inferredLeft, traffic_mode_right: inferredRight };
1468
+ }
1469
+ if (DIRECTIONAL_PARKING_INFERENCE_CATEGORIES.has(categoryId)) {
1470
+ return { traffic_mode_left: void 0, traffic_mode_right: inferTrafficModeFromParking(centerlineTags, side) };
1471
+ }
1472
+ return { traffic_mode_left: left, traffic_mode_right: right };
1473
+ }
1474
+
1475
+ // src/categories/analyze-category-gaps.ts
1476
+ function baseIdFromIncomplete(categoryId) {
1477
+ return categoryId.replace(/_adjoiningOrIsolated$/, "").replace(/_advisoryOrExclusive$/, "");
1478
+ }
1479
+ function discriminatorSatisfied(disc, tags) {
1480
+ return disc.values.some((v) => {
1481
+ if (disc.key === "traffic_sign") return tags.traffic_sign?.includes(v) === true;
1482
+ return tags[disc.key] === v;
1483
+ });
1484
+ }
1485
+ function gapDiscriminatorsResolved(spec, tags) {
1486
+ const keys = new Set(spec.gapDiscriminators?.map((d) => d.key) ?? []);
1487
+ if (keys.has("is_sidepath") && (sidepathDiscriminatorKnown(tags) || categoryIsSidepath(tags))) {
1488
+ return true;
1489
+ }
1490
+ if (keys.has("lane") && laneDiscriminatorKnown(tags)) {
1491
+ return true;
1492
+ }
1493
+ return false;
1494
+ }
1495
+ function resolveUnlockCategory(baseId, unlocksCategory) {
1496
+ if (unlocksCategory == null) return void 0;
1497
+ if (unlocksCategory.startsWith("_")) return `${baseId}${unlocksCategory}`;
1498
+ return unlocksCategory;
1499
+ }
1500
+ function gapsFromSpec(spec, categoryId, tags) {
1501
+ if (!spec.gapDiscriminators?.length) return [];
1502
+ if (gapDiscriminatorsResolved(spec, tags)) return [];
1503
+ const baseId = baseIdFromIncomplete(categoryId);
1504
+ return spec.gapDiscriminators.filter((d) => !discriminatorSatisfied(d, tags)).map((d) => ({
1505
+ key: d.key,
1506
+ values: [...d.values],
1507
+ reason: d.reason,
1508
+ unlocksCategory: resolveUnlockCategory(baseId, d.unlocksCategory)
1509
+ }));
1510
+ }
1511
+ function gapsForIncomplete(categoryId, tags) {
1512
+ const spec = specByCategoryId(categoryId);
1513
+ if (!spec) return [];
1514
+ return gapsFromSpec(spec, categoryId, tags);
1515
+ }
1516
+ function findTransformedTags(wayTags, result) {
1517
+ const tags = { ...wayTags };
1518
+ prepareTags(tags);
1519
+ const transformed = getTransformedObjects(tags, BIKELANE_TRANSFORMATIONS);
1520
+ return transformed.find(
1521
+ (t) => (t._side ?? "self") === result._side && (t._prefix ?? null) === result._prefix
1522
+ );
1523
+ }
1524
+ function analyzeCategoryGaps(wayTags, results) {
1525
+ return results.map((result) => {
1526
+ const incomplete = isIncompleteCategoryId(result.category);
1527
+ const transformed = findTransformedTags(wayTags, result) ?? wayTags;
1528
+ const missing = incomplete ? gapsForIncomplete(result.category, transformed) : [];
1529
+ return {
1530
+ category: result.category,
1531
+ _side: result._side,
1532
+ incomplete,
1533
+ missing
1534
+ };
1535
+ });
1536
+ }
1537
+
1538
+ // src/categories/plan-tags-for-category.ts
1539
+ function isPreciseTargetCategoryId(id) {
1540
+ const def = CATEGORY_DEFINITIONS.find((c) => c.id === id);
1541
+ return def != null && def.infrastructureExists && !isIncompleteCategoryId(id);
1542
+ }
1543
+ function resolveUnlockCategory2(baseId, unlocksCategory) {
1544
+ if (unlocksCategory == null) return void 0;
1545
+ if (unlocksCategory.startsWith("_")) return `${baseId}${unlocksCategory}`;
1546
+ return unlocksCategory;
1547
+ }
1548
+ function baseIdFromIncomplete2(categoryId) {
1549
+ return categoryId.replace(/_adjoiningOrIsolated$/, "").replace(/_advisoryOrExclusive$/, "");
1550
+ }
1551
+ function resolveRefinedIdFromSpec(spec, idSuffix) {
1552
+ if (idSuffix === "_advisoryOrExclusive" && spec.id.endsWith("_advisoryOrExclusive")) {
1553
+ return spec.id;
1554
+ }
1555
+ const base = spec.id.replace(/_advisoryOrExclusive$/, "");
1556
+ return `${base}${idSuffix}`;
1557
+ }
1558
+ function findTransformedTags2(wayTags, side) {
1559
+ const tags = { ...wayTags };
1560
+ prepareTags(tags);
1561
+ const transformed = getTransformedObjects(tags, BIKELANE_TRANSFORMATIONS);
1562
+ return transformed.find((t) => (t._side ?? "self") === side);
1563
+ }
1564
+ function categorizeSide(wayTags, side) {
1565
+ const transformed = findTransformedTags2(wayTags, side);
1566
+ if (!transformed) return null;
1567
+ const category = categorizeBikelane(transformed);
1568
+ return category?.id ?? null;
1569
+ }
1570
+ function writeKeyForSide(transformedKey, side, prefix) {
1571
+ if (side === "self" || prefix == null) return transformedKey;
1572
+ if (prefix === "cycleway" || prefix === "sidewalk") {
1573
+ return `${prefix}:${side}:${transformedKey}`;
1574
+ }
1575
+ return transformedKey;
1576
+ }
1577
+ function tagValue2(tags, key) {
1578
+ return tags[key];
1579
+ }
1580
+ function positiveMatchScore(tags, predicate) {
1581
+ switch (predicate.op) {
1582
+ case "eq":
1583
+ return tagValue2(tags, predicate.key) === predicate.value ? 1 : 0;
1584
+ case "in": {
1585
+ const v = tagValue2(tags, predicate.key);
1586
+ return v != null && predicate.values.includes(v) ? 1 : 0;
1587
+ }
1588
+ case "and":
1589
+ return predicate.predicates.reduce((sum, p) => sum + positiveMatchScore(tags, p), 0);
1590
+ case "or":
1591
+ return Math.max(0, ...predicate.predicates.map((p) => positiveMatchScore(tags, p)));
1592
+ default:
1593
+ return 0;
1594
+ }
1595
+ }
1596
+ function countEqInLeaves(predicate) {
1597
+ switch (predicate.op) {
1598
+ case "eq":
1599
+ case "in":
1600
+ return 1;
1601
+ case "and":
1602
+ return predicate.predicates.reduce((sum, p) => sum + countEqInLeaves(p), 0);
1603
+ case "or":
1604
+ return Math.max(0, ...predicate.predicates.map((p) => countEqInLeaves(p)));
1605
+ default:
1606
+ return 0;
1607
+ }
1608
+ }
1609
+ function pickOrBranch(tags, predicates) {
1610
+ let best;
1611
+ let bestScore = -1;
1612
+ let bestLeaves = -1;
1613
+ for (const child of predicates) {
1614
+ const score = positiveMatchScore(tags, child);
1615
+ const leaves = countEqInLeaves(child);
1616
+ if (score > bestScore || score === bestScore && leaves > bestLeaves) {
1617
+ bestScore = score;
1618
+ bestLeaves = leaves;
1619
+ best = child;
1620
+ }
1621
+ }
1622
+ return best;
1623
+ }
1624
+ function collectFromPredicate(predicate, tags, reason, out) {
1625
+ switch (predicate.op) {
1626
+ case "eq":
1627
+ out.push({ key: predicate.key, values: [predicate.value], reason });
1628
+ return;
1629
+ case "in":
1630
+ out.push({ key: predicate.key, values: [...predicate.values], reason });
1631
+ return;
1632
+ case "and":
1633
+ for (const child of predicate.predicates) {
1634
+ collectFromPredicate(child, tags, reason, out);
1635
+ }
1636
+ return;
1637
+ case "or": {
1638
+ const best = pickOrBranch(tags, predicate.predicates);
1639
+ if (best) collectFromPredicate(best, tags, reason, out);
1640
+ return;
1641
+ }
1642
+ case "macro":
1643
+ case "literal":
1644
+ case "exists":
1645
+ case "notExists":
1646
+ case "neq":
1647
+ case "notIn":
1648
+ case "includes":
1649
+ case "hasPrefix":
1650
+ case "hasSuffix":
1651
+ case "hasTagWithPrefix":
1652
+ case "not":
1653
+ return;
1654
+ default:
1655
+ return;
1656
+ }
1657
+ }
1658
+ function discriminatorBaseId(targetCategoryId) {
1659
+ return targetCategoryId.replace(/_adjoining$/, "").replace(/_isolated$/, "").replace(/_advisory$/, "").replace(/_exclusive$/, "");
1660
+ }
1661
+ function findParentSpecAndRefining(targetCategoryId) {
1662
+ for (const parent of CATEGORY_SPECS) {
1663
+ if (parent.id === targetCategoryId) return { parent };
1664
+ const refining = parent.refining?.find(
1665
+ (child) => resolveRefinedIdFromSpec(parent, child.idSuffix) === targetCategoryId
1666
+ );
1667
+ if (refining) return { parent, refining };
1668
+ }
1669
+ return void 0;
1670
+ }
1671
+ function discriminatorsForTarget(parent, targetCategoryId) {
1672
+ if (!parent.gapDiscriminators?.length) return [];
1673
+ const baseId = discriminatorBaseId(targetCategoryId);
1674
+ return parent.gapDiscriminators.filter((d) => {
1675
+ const unlocked = resolveUnlockCategory2(baseId, d.unlocksCategory);
1676
+ return unlocked === targetCategoryId;
1677
+ });
1678
+ }
1679
+ function requirementsFromSpec(targetCategoryId, tags) {
1680
+ const resolved = findParentSpecAndRefining(targetCategoryId);
1681
+ if (!resolved) return [];
1682
+ const { parent, refining } = resolved;
1683
+ const requirements = [];
1684
+ if (parent.match) {
1685
+ collectFromPredicate(parent.match, tags, `Required for ${targetCategoryId}`, requirements);
1686
+ }
1687
+ if (refining) {
1688
+ collectFromPredicate(refining.match, tags, `Discriminator for ${targetCategoryId}`, requirements);
1689
+ }
1690
+ for (const disc of discriminatorsForTarget(parent, targetCategoryId)) {
1691
+ for (const value of disc.values) {
1692
+ requirements.push({
1693
+ key: disc.key,
1694
+ values: [value],
1695
+ reason: disc.reason
1696
+ });
1697
+ }
1698
+ }
1699
+ const needsClarificationSpec = CATEGORY_SPECS.find((s) => s.id === "needsClarification");
1700
+ const baseForTarget = discriminatorBaseId(targetCategoryId);
1701
+ if (needsClarificationSpec?.gapDiscriminators) {
1702
+ for (const disc of needsClarificationSpec.gapDiscriminators) {
1703
+ const unlocked = resolveUnlockCategory2("", disc.unlocksCategory);
1704
+ if (unlocked !== baseForTarget && unlocked !== targetCategoryId) continue;
1705
+ for (const value of disc.values) {
1706
+ requirements.push({
1707
+ key: disc.key,
1708
+ values: [value],
1709
+ reason: disc.reason
1710
+ });
1711
+ }
1712
+ }
1713
+ }
1714
+ return requirements;
1715
+ }
1716
+ function dedupeRequirements(requirements) {
1717
+ const byKey = /* @__PURE__ */ new Map();
1718
+ for (const req of requirements) {
1719
+ const existing = byKey.get(req.key);
1720
+ if (!existing) {
1721
+ byKey.set(req.key, { ...req, values: [...req.values] });
1722
+ continue;
1723
+ }
1724
+ const values = /* @__PURE__ */ new Set([...existing.values, ...req.values]);
1725
+ byKey.set(req.key, { ...existing, values: [...values], reason: existing.reason || req.reason });
1726
+ }
1727
+ return [...byKey.values()];
1728
+ }
1729
+ function applyPlanToWayTags(wayTags, add, change) {
1730
+ const next = { ...wayTags };
1731
+ for (const entry of change) {
1732
+ next[entry.key] = entry.to;
1733
+ }
1734
+ for (const entry of add) {
1735
+ if (next[entry.key] == null) next[entry.key] = entry.value;
1736
+ }
1737
+ return next;
1738
+ }
1739
+ function trafficSignSatisfied(tags, value) {
1740
+ return tags.traffic_sign?.includes(value) === true;
1741
+ }
1742
+ function pickPreferredValue(req, tags) {
1743
+ if (req.key === "traffic_sign") {
1744
+ return req.values[0];
1745
+ }
1746
+ const current = tagValue2(tags, req.key);
1747
+ if (current != null && req.values.includes(current)) return current;
1748
+ return req.values[0];
1749
+ }
1750
+ function listTargetCategories(options) {
1751
+ const all = CATEGORY_DEFINITIONS.map((c) => c.id).filter(isPreciseTargetCategoryId);
1752
+ const fromCategory = options?.fromCategory;
1753
+ if (!fromCategory) return all;
1754
+ const spec = specByCategoryId(fromCategory);
1755
+ const incomplete = options.fromIncomplete ?? isIncompleteCategoryId(fromCategory);
1756
+ if (!spec || !incomplete || !spec.gapDiscriminators?.length) return all;
1757
+ const baseId = baseIdFromIncomplete2(fromCategory);
1758
+ const prioritized = [];
1759
+ const seen = /* @__PURE__ */ new Set();
1760
+ for (const disc of spec.gapDiscriminators) {
1761
+ const unlocked = resolveUnlockCategory2(baseId, disc.unlocksCategory);
1762
+ if (unlocked == null || seen.has(unlocked)) continue;
1763
+ if (!isPreciseTargetCategoryId(unlocked)) continue;
1764
+ seen.add(unlocked);
1765
+ prioritized.push(unlocked);
1766
+ }
1767
+ for (const id of all) {
1768
+ if (!seen.has(id)) prioritized.push(id);
1769
+ }
1770
+ return prioritized;
1771
+ }
1772
+ var UnknownTargetCategoryError = class extends Error {
1773
+ constructor(targetCategoryId) {
1774
+ super(`Unknown target category: ${targetCategoryId}`);
1775
+ this.targetCategoryId = targetCategoryId;
1776
+ this.name = "UnknownTargetCategoryError";
1777
+ }
1778
+ targetCategoryId;
1779
+ };
1780
+ function planTagsForCategory(wayTags, targetCategoryId, options) {
1781
+ const spec = specByCategoryId(targetCategoryId);
1782
+ if (!spec) {
1783
+ throw new UnknownTargetCategoryError(targetCategoryId);
1784
+ }
1785
+ const side = options?.side ?? "self";
1786
+ const transformed = findTransformedTags2(wayTags, side);
1787
+ const prefix = transformed?._prefix ?? null;
1788
+ const currentCategoryId = categorizeSide(wayTags, side);
1789
+ const tags = transformed ?? wayTags;
1790
+ if (currentCategoryId === targetCategoryId) {
1791
+ return {
1792
+ targetCategoryId,
1793
+ currentCategoryId,
1794
+ aligned: true,
1795
+ add: [],
1796
+ change: [],
1797
+ conflicts: []
1798
+ };
1799
+ }
1800
+ const requirements = dedupeRequirements(requirementsFromSpec(targetCategoryId, tags));
1801
+ const add = [];
1802
+ const change = [];
1803
+ const conflicts = [];
1804
+ for (const req of requirements) {
1805
+ const writeKey = writeKeyForSide(req.key, side, prefix);
1806
+ const wayValue = wayTags[writeKey] ?? tags[req.key];
1807
+ const transformedValue = tags[req.key];
1808
+ if (req.key === "traffic_sign") {
1809
+ const satisfied = req.values.some((v) => trafficSignSatisfied(tags, v));
1810
+ if (satisfied) continue;
1811
+ const preferred = pickPreferredValue(req, tags);
1812
+ if (wayValue == null && transformedValue == null) {
1813
+ add.push({ key: writeKey, value: preferred, reason: req.reason });
1814
+ } else if (transformedValue != null && !req.values.some((v) => transformedValue.includes(v))) {
1815
+ change.push({
1816
+ key: writeKey,
1817
+ from: wayValue ?? transformedValue,
1818
+ to: preferred,
1819
+ reason: req.reason
1820
+ });
1821
+ }
1822
+ continue;
1823
+ }
1824
+ if (transformedValue != null && !req.values.includes(transformedValue)) {
1825
+ change.push({
1826
+ key: writeKey,
1827
+ from: wayValue ?? transformedValue,
1828
+ to: pickPreferredValue(req, tags),
1829
+ reason: req.reason
1830
+ });
1831
+ continue;
1832
+ }
1833
+ if (transformedValue == null && wayValue == null) {
1834
+ add.push({
1835
+ key: writeKey,
1836
+ value: pickPreferredValue(req, tags),
1837
+ reason: req.reason
1838
+ });
1839
+ }
1840
+ }
1841
+ const dryRunTags = applyPlanToWayTags(wayTags, add, change);
1842
+ const resultCategory = categorizeSide(dryRunTags, side);
1843
+ const aligned = resultCategory === targetCategoryId;
1844
+ if (!aligned) {
1845
+ conflicts.push({
1846
+ key: "_category",
1847
+ value: resultCategory ?? "null",
1848
+ reason: "After suggested tag adds/changes, classification still does not match the target; additional tags (e.g. from macro predicates) may be required."
1849
+ });
1850
+ }
1851
+ return {
1852
+ targetCategoryId,
1853
+ currentCategoryId,
1854
+ aligned,
1855
+ add,
1856
+ change,
1857
+ conflicts
1858
+ };
1859
+ }
1860
+
1861
+ // src/index.ts
1862
+ function clean(value) {
1863
+ return value == null || value === DISALLOWED ? null : value;
1864
+ }
1865
+ function processBikelanes(objectTags) {
1866
+ const results = [];
1867
+ const tags = { ...objectTags };
1868
+ prepareTags(tags);
1869
+ const transformed = getTransformedObjects(tags, BIKELANE_TRANSFORMATIONS);
1870
+ for (const t of transformed) {
1871
+ t._length = tags._length;
1872
+ const category = categorizeBikelane(t);
1873
+ if (category == null) continue;
1874
+ const result = {
1875
+ _side: t._side ?? "self",
1876
+ _prefix: t._prefix ?? null,
1877
+ _infrastructureExists: category.infrastructureExists,
1878
+ category: category.id
1879
+ };
1880
+ if (category.infrastructureExists) {
1881
+ result.oneway = deriveOneway(t, category);
1882
+ result.width = parseLength(t.width) ?? null;
1883
+ result.surface_color = clean(surfaceColor(t));
1884
+ result.separation_left = clean(separation(t, "left"));
1885
+ result.separation_right = clean(separation(t, "right"));
1886
+ result.buffer_left = clean(buffer(t, "left"));
1887
+ result.buffer_right = clean(buffer(t, "right"));
1888
+ result.marking_left = clean(marking(t, "left"));
1889
+ result.marking_right = clean(marking(t, "right"));
1890
+ const tm = deriveTrafficMode(t, t._parent ?? tags, category.id, t._side ?? "self");
1891
+ result.traffic_mode_left = tm.traffic_mode_left ?? null;
1892
+ result.traffic_mode_right = tm.traffic_mode_right ?? null;
1893
+ const ts = deriveTrafficSigns(t);
1894
+ result.traffic_sign = ts.traffic_sign ?? null;
1895
+ const surf = deriveBikelaneSurface(t, category);
1896
+ result.surface = surf.surface ?? null;
1897
+ result.surface_source = surf.surface_source ?? null;
1898
+ result.surface_confidence = surf.surface_confidence ?? null;
1899
+ const smooth = deriveBikelaneSmoothness(t, category);
1900
+ result.smoothness = smooth.smoothness ?? null;
1901
+ result.smoothness_source = smooth.smoothness_source ?? null;
1902
+ result.smoothness_confidence = smooth.smoothness_confidence ?? null;
1903
+ }
1904
+ results.push(result);
1905
+ }
1906
+ return results;
1907
+ }
1908
+
1909
+ export { ALLOWED_HIGHWAYS, BIKELANE_TRANSFORMATIONS, CATEGORY_DEFINITIONS, CATEGORY_SPECS, MAJOR_ROAD_CLASSES, MINOR_ROAD_CLASSES, PATH_CLASSES, SIDEPATH_HIGHWAY_CLASSES, TRUNK_MOTORWAY_CLASSES, UnknownTargetCategoryError, analyzeCategoryGaps, categorizeBikelane, getTransformedObjects, isIncompleteCategoryId, listTargetCategories, planTagsForCategory, prepareTags, processBikelanes, specsWithGapDiscriminators, writeKeyForSide };