@florasync/leaflet-geokit 0.8.3 → 0.9.1

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.
Files changed (78) hide show
  1. package/ARCHITECTURE.md +195 -0
  2. package/CHANGELOG.md +8 -0
  3. package/README.md +146 -11
  4. package/custom-toolbar.html +165 -0
  5. package/dist/django/index.js +8993 -5090
  6. package/dist/django/index.js.map +1 -1
  7. package/dist/leaflet-geokit.es.js +21536 -5994
  8. package/dist/leaflet-geokit.es.js.map +1 -1
  9. package/dist/leaflet-geokit.external.es.js +18006 -2461
  10. package/dist/leaflet-geokit.external.es.js.map +1 -1
  11. package/dist/leaflet-geokit.umd.js +263 -60
  12. package/dist/leaflet-geokit.umd.js.map +1 -1
  13. package/dist/preact/index-DCKj0r6a.js +8545 -0
  14. package/dist/preact/index-DCKj0r6a.js.map +1 -0
  15. package/dist/preact/index.js +1 -1
  16. package/dist/preact-bundled/index.js +9002 -5089
  17. package/dist/preact-bundled/index.js.map +1 -1
  18. package/dist/react/index-DCKj0r6a.js +8545 -0
  19. package/dist/react/index-DCKj0r6a.js.map +1 -0
  20. package/dist/react/index.js +1 -1
  21. package/dist/react-bundled/index.js +9040 -5127
  22. package/dist/react-bundled/index.js.map +1 -1
  23. package/dist/types/components/LeafletDrawMapElement.d.ts +42 -3
  24. package/dist/types/django/index.d.ts +2 -2
  25. package/dist/types/external.d.ts +9 -3
  26. package/dist/types/index.d.ts +9 -3
  27. package/dist/types/lib/FeatureStore.d.ts +2 -2
  28. package/dist/types/lib/LayerRegistry.d.ts +19 -0
  29. package/dist/types/lib/MapController.d.ts +95 -5
  30. package/dist/types/lib/draw/L.Draw.Move.d.ts +1 -0
  31. package/dist/types/lib/draw/move-pointer.d.ts +12 -0
  32. package/dist/types/lib/layer-cake/LayerCakeManager.d.ts +10 -2
  33. package/dist/types/lib/layer-style-panel.d.ts +3 -0
  34. package/dist/types/lib/marker-icons.d.ts +1 -1
  35. package/dist/types/lib/providers.d.ts +64 -0
  36. package/dist/types/lib/snapping.d.ts +30 -0
  37. package/dist/types/lib/tool-buttons.d.ts +3 -1
  38. package/dist/types/lib/tool-capabilities.d.ts +27 -0
  39. package/dist/types/lib/toolbar-accessibility.d.ts +3 -0
  40. package/dist/types/lib/toolbar-layout.d.ts +14 -0
  41. package/dist/types/lib/toolbar-styles.d.ts +2 -0
  42. package/dist/types/preact/core.d.ts +2 -2
  43. package/dist/types/preact/index.d.ts +2 -2
  44. package/dist/types/preact-bundled/index.d.ts +3 -3
  45. package/dist/types/react/core.d.ts +2 -2
  46. package/dist/types/react/index.d.ts +2 -2
  47. package/dist/types/react-bundled/index.d.ts +3 -3
  48. package/dist/types/types/events.d.ts +15 -1
  49. package/dist/types/types/layers.d.ts +65 -0
  50. package/dist/types/types/public.d.ts +160 -5
  51. package/dist/types/utils/geojson-pipeline.d.ts +51 -0
  52. package/dist/types/utils/geojson.d.ts +15 -2
  53. package/dist/types/utils/grower-geometry.d.ts +107 -0
  54. package/docs/accessibility.md +142 -0
  55. package/docs/api-reference.md +249 -0
  56. package/docs/custom-toolbar.md +168 -0
  57. package/docs/diagnostics.md +216 -0
  58. package/docs/geojson-pipelines.md +145 -0
  59. package/docs/google-maps-adapter-spike.md +77 -0
  60. package/docs/grower-geometry.md +237 -0
  61. package/docs/grower-measurement.md +23 -0
  62. package/docs/integration-recipes.md +301 -0
  63. package/docs/layers.md +136 -0
  64. package/docs/providers.md +191 -0
  65. package/docs/release-verification.md +75 -0
  66. package/docs/shims/django.md +102 -0
  67. package/docs/shims/preact.md +98 -0
  68. package/docs/shims/react.md +98 -0
  69. package/docs/snapping-and-measurements.md +42 -0
  70. package/docs/tool-capabilities.md +131 -0
  71. package/docs/tool-lifecycle.md +124 -0
  72. package/docs/toolbar-layout.md +158 -0
  73. package/docs/toolbar-styling.md +118 -0
  74. package/package.json +35 -3
  75. package/dist/preact/index-BMfJn-mD.js +0 -4632
  76. package/dist/preact/index-BMfJn-mD.js.map +0 -1
  77. package/dist/react/index-BMfJn-mD.js +0 -4632
  78. package/dist/react/index-BMfJn-mD.js.map +0 -1
@@ -0,0 +1,216 @@
1
+ # Diagnostics and troubleshooting
2
+
3
+ Use the public element API, not `_controller` or Leaflet handler internals.
4
+ [API reference](api-reference.md), [event types](../src/types/events.ts), and
5
+ [element implementation](../src/components/LeafletDrawMapElement.ts) define the
6
+ surfaces below. Diagnostics describe failures; they do not guarantee recovery,
7
+ transaction rollback, provider health, or successful persistence.
8
+
9
+ ## Choose the right signal
10
+
11
+ | Surface | Purpose / delivery |
12
+ | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
13
+ | `map.status` and `leaflet-geokit:status` | Durable detached state snapshot. Subscribe directly on the element and read an initial snapshot. |
14
+ | `leaflet-geokit:diagnostic` | Structured component/controller/provider warning or error. Direct element listener; not bubbling/composed. |
15
+ | `leaflet-draw:error` | Legacy error notification. Component/controller errors also produce a diagnostic and update status. Not bubbling/composed. |
16
+ | `tile-provider-error` | Built-in raster provider failure; bubbles, not composed. Also emits a warning diagnostic; does **not** use the legacy error event. |
17
+ | `leaflet-geokit:tool-failed` | Correlated tool command failure with a human-readable `reason`. Bubbling/composed; not a component error-code catalog. |
18
+ | `getToolCapabilities()` and `leaflet-geokit:tool-capabilities-changed` | Why each tool is enabled, disabled, or unavailable, plus requested/active provider. |
19
+ | `getProviderDiagnostics()` | Detached basemap **configuration** report; null without initialized diagnostics. Not a tile-load or key-validity check. |
20
+ | GeoJSON helper results / `GeoJSONValidationError.summary` | Data validation diagnostics with paths; separate from DOM diagnostic events. |
21
+ | Promise rejection or synchronous exception | Caller must catch it. Not every public-method exception is forwarded to the diagnostic event. |
22
+
23
+ Avoid double-reporting a legacy error and its corresponding diagnostic. Log
24
+ levels affect console output, not whether public diagnostic events are emitted.
25
+
26
+ ## Status and diagnostic payloads
27
+
28
+ `StatusEventDetail` contains `state`, `ready`, `busy`, `featureCount`, optional
29
+ `lastEvent`, optional `lastError`, and `timestamp`. `lastError` contains only
30
+ `code`, `message`, `recoverable`, `timestamp`; it omits the raw cause but its
31
+ message can still contain sensitive input. A successful operation may clear it;
32
+ status is not an audit history. Timestamps are milliseconds since the Unix epoch.
33
+
34
+ | State | Interpretation |
35
+ | --------------- | ----------------------------------------------------------------------------------- |
36
+ | `uninitialized` | Before connection or after disconnect; not ready, not busy. |
37
+ | `initializing` | Connection/map initialization in progress. |
38
+ | `ready` | Map ready; recoverable warnings can coexist with this state. |
39
+ | `loading` | GeoJSON import in progress; `ready` can remain true for an already initialized map. |
40
+ | `error` | Nonrecoverable controller initialization failure; inspect diagnostic. |
41
+
42
+ `DiagnosticEventDetail` adds `severity: "info" | "warn" | "error"`, `state`, and
43
+ optional `cause` to the summary. The type permits `info`; current component
44
+ error forwarding uses `warn` when recoverable and `error` otherwise. Recoverable
45
+ means the map may remain usable, not that the requested operation succeeded.
46
+ The diagnostic event precedes its associated status update: use `detail.state`
47
+ in that callback or observe the following status event.
48
+
49
+ ```js
50
+ import "@florasync/leaflet-geokit";
51
+
52
+ const map = document.createElement("leaflet-geokit");
53
+ map.style.cssText = "width:100%;height:400px";
54
+ map.logLevel = "warn";
55
+ map.addEventListener("leaflet-geokit:diagnostic", ({ detail }) => {
56
+ // Deliberately omit message/cause/URLs/keys from shared telemetry.
57
+ console.warn({
58
+ code: detail.code,
59
+ severity: detail.severity,
60
+ recoverable: detail.recoverable,
61
+ state: detail.state,
62
+ timestamp: detail.timestamp,
63
+ });
64
+ });
65
+ map.addEventListener("leaflet-geokit:status", ({ detail }) => {
66
+ console.log({ state: detail.state, busy: detail.busy });
67
+ });
68
+ map.addEventListener("leaflet-geokit:tool-failed", ({ detail }) => {
69
+ console.warn({ tool: detail.tool, commandId: detail.commandId });
70
+ });
71
+ document.body.append(map);
72
+ console.log(map.status);
73
+ ```
74
+
75
+ For async calls, still use `try`/`catch`; for example, catch a rejection from
76
+ `loadGeoJSONFromUrl()` even if the diagnostic listener already updates the UI.
77
+
78
+ ## Component and controller error catalog
79
+
80
+ These codes come from the element and [MapController](../src/lib/MapController.ts).
81
+ The public `code` type is a string, not a closed enum; tolerate unknown future
82
+ codes and use the code rather than matching message text.
83
+
84
+ | Code | Recoverable / severity | Trigger and recovery |
85
+ | ---------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
86
+ | `map_init_failed` | No / error | Leaflet map initialization failed. Check host size, browser globals, runtime/plugin identity, and styling/runtime configuration. Fix prerequisites before reconnecting; preserve host data outside the element. |
87
+ | `controller_error` | Yes / warn by default | Generic controller operation failure. Inspect the local message/cause and reproduce the specific operation; do not assume rollback. |
88
+ | `invalid_marker_icon_config` | Yes / warn | Invalid marker URL or tuple/configuration. Correct URL/size/anchor fields; invalid optional values fall back individually, invalid primary URL uses default markers. |
89
+ | `invalid_tool_button_config` | Yes / warn | `tool-button-config` JSON parse or object-shape failure. Supply an object keyed by valid tool names; use the property for functions. |
90
+ | `invalid_toolbar_groups` | Yes / warn | `toolbar-groups` JSON parse or array-shape failure. Supply an array with group IDs/tool lists. |
91
+ | `data_fetch_failed` | Yes / warn | URL import network rejection or non-success HTTP response. Check URL trust, CORS, connectivity, authentication and response status; retry explicitly. Promise rejects. |
92
+ | `data_parse_failed` | Yes / warn | URL/text import is not parseable JSON. Check response body/content type or uploaded text; parsing JSON alone does not validate GeoJSON. Promise rejects. |
93
+ | `data_load_failed` | Yes / warn | Replacement import failed after parsing/ingest. Inspect validation/render cause; use preflight validation before replacing data. Promise rejects. |
94
+ | `data_add_failed` | Yes / warn | Additive import failed. With validated imports, inspect duplicate IDs as well as geometry. Promise rejects. |
95
+
96
+ Invalid toolbar JSON falls back to no custom configuration/groups; this is not a
97
+ schema validation service for every nested renderer setting. Other renderer or
98
+ host-hook problems may be logged or thrown rather than assigned one of these
99
+ codes. For safe data replacement, `importGeoJSON(fc, { validate: true })` validates
100
+ after the mutable ingest hook and before clearing data. This protects validation
101
+ failures, not arbitrary rendering failures. URL/text convenience methods currently
102
+ forward only behavior/fit options; validate through the pipeline helpers and then
103
+ call `importGeoJSON` explicitly.
104
+
105
+ ## Raster provider error catalog
106
+
107
+ `TileProviderErrorDetail` contains `code`, `message`, `provider`, `timestamp`.
108
+ These errors also emit a recoverable warning diagnostic and attempt OSM raster
109
+ fallback. The requested provider remains visible in tool capabilities, even
110
+ when the active basemap is OSM. Local geometry tools do not require HERE.
111
+ Fallback attempts are not proof that the public OSM service is reachable.
112
+
113
+ | Code | Meaning / next check |
114
+ | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
115
+ | `missing_api_key` | HERE requested without a nonempty key. Choose OSM/custom tiles or configure an approved provider integration. |
116
+ | `unknown_provider` | Unsupported named provider. Use `osm`/`here`; custom URLs belong in `tile-url` with `tileProvider` cleared. |
117
+ | `permission_denied` | HERE tile error text indicates permission/forbidden/403/unauthorized/access denial. Inspect permitted API/product, project permissions, origin/referrer restrictions and style access. |
118
+ | `invalid_api_key` | Remaining HERE tile errors are classified this way. This is a heuristic, **not proof the key is invalid**; inspect Network/CORS/connectivity and provider response too. |
119
+ | `tile_load_failed` | Generic custom/OSM tile failure, tile setup exception, or other configuration validation failure. Inspect the actual network request and tile template/placeholders. |
120
+
121
+ `tile-provider-changed` means a provider layer was installed, not that all tiles
122
+ loaded successfully. An injected basemap adapter has different failure semantics:
123
+ synchronous mount failures preserve the previous basemap; asynchronous renderer
124
+ errors belong to the bridge. See [provider contracts and limits](providers.md).
125
+
126
+ Provider configuration diagnostics contain only `kind`, `attribution`,
127
+ `attributionRequired`, `offline`, `apiKey`, `drawing`, and `scope`.
128
+ `scope: "configuration"` is deliberate; `apiKey` describes credential requirements,
129
+ not a key value or validation result. `offline: "host-managed"` is a declaration,
130
+ not proof of offline assets/cache. See the exhaustive
131
+ [provider capability table](providers.md#capability-diagnostics).
132
+
133
+ ## Tool requirement diagnostics
134
+
135
+ Tool reasons are separate from component error codes. Use
136
+ `getToolCapabilities().tools[tool].reason`, not the text of `tool-failed.reason`,
137
+ for stable prerequisite codes. The complete codes are `not_ready`, `read_only`,
138
+ `missing_attribute`, `unavailable_plugin`, `empty_selection`, `no_editable_layers`,
139
+ `missing_provider`, `missing_api_key`, `runtime_error`, `configured_disabled`.
140
+ Their exhaustive recovery/precedence table is in
141
+ [tool capabilities](tool-capabilities.md#requirements-and-recovery).
142
+
143
+ Important distinctions:
144
+
145
+ - Removing read-only means removing the attribute or setting `readOnly = false`,
146
+ not writing `read-only="false"` (including when a reason says `read-only=false`).
147
+ - Delete needs both `delete-features` and `edit-features`. Move/edit/delete need
148
+ actual editable layers, not just a stored feature count.
149
+ - Host `disabled` controls buttons, not imperative activation. `commandEnabled`
150
+ also allows explicit runtime-failure retries; do not equate it with `state`.
151
+ - Selection prerequisites are opt-in. Supply IDs with `setToolSelection()`;
152
+ GeoKit does not invent a global selection UI.
153
+ - An activation result of `true` is not completion. Observe correlated
154
+ `tool-completed`/`tool-cancelled`/`tool-failed` events as described in
155
+ [tool lifecycle](tool-lifecycle.md).
156
+
157
+ ## GeoJSON and geometry diagnostics
158
+
159
+ The [pipeline contract](geojson-pipelines.md#diagnostics-and-limits) describes
160
+ validation limits and source metadata behavior. Helper diagnostics use
161
+ `severity: "error" | "warning" | "info"` (note **warning**, not DOM diagnostic
162
+ **warn**), `code`, `path`, and `message`. They are returned in results or carried
163
+ by `GeoJSONValidationError.summary`, not automatically dispatched as DOM events.
164
+
165
+ `invalid-json` identifies text parsing failure; `crs-mismatch` warns about CRS or
166
+ coordinate ranges without reprojecting; `multi-expansion` is information about
167
+ editing expansion; `metadata-conflict` requires reconciling sibling properties
168
+ before safe source export. Geometry structure, positions, IDs, rings and reserved
169
+ provenance have additional validation diagnostics defined in
170
+ [geojson-pipeline.ts](../src/utils/geojson-pipeline.ts). Do not treat structural
171
+ validation as comprehensive topology validation or silent geometry repair.
172
+
173
+ Grower operations have their own typed result/error contract; consult
174
+ [grower geometry](grower-geometry.md) and [measurements](grower-measurement.md).
175
+ Do not confuse a helper failure result with map readiness or basemap availability.
176
+
177
+ ## Troubleshooting by symptom
178
+
179
+ | Symptom | Checks / remedy |
180
+ | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
181
+ | Blank or zero-height map | Give the host explicit dimensions; inspect its computed size. Wait for readiness and check initialization diagnostics. A defined custom element is not a ready map. |
182
+ | Controls/map look unstyled | Check `skip-leaflet-styles`, CSS injection, CSP and shadow-root styling. In external mode use one compatible Leaflet namespace with Draw attached; set `leafletInstance` before connection. |
183
+ | Tool button missing or disabled | Read capability snapshot first; check enable attribute, read-only, plugin, and editable layers. Custom groups hide native toolbars by default. |
184
+ | Custom JSON toolbar ignored | Check diagnostic codes and JSON top-level shape. A property override wins over its attribute; set it to `undefined` to resume attribute configuration, `null` to clear. |
185
+ | Tiles changed unexpectedly | Inspect `tile-provider-error` and requested/active capabilities for OSM fallback. Named provider wins over `tile-url`. Attribute changes can replace an injected adapter. |
186
+ | HERE reports invalid key but key is correct | Classification is heuristic. Inspect network/CORS, restrictions, permissions and style; try permitted `lite.day` if satellite access fails. Never paste keys into issue reports. |
187
+ | Parent listener never receives an event | Subscribe on the actual element. Legacy draw/status/diagnostic events do not bubble; provider events are not composed. |
188
+ | Import did nothing | Wait for readiness; pre-controller methods are not queued. Catch promise failures; validate FC structure and coordinate order. Empty collection is valid, empty geometry is not. |
189
+ | Read-only still active | Remove `read-only`; a literal `"false"` attribute is still present. Read-only is interactive tool policy, not protection against host data API calls. |
190
+ | `prefer-canvas="false"` still uses Canvas | Boolean attribute presence is true. Set concrete-element `preferCanvas = false` before connection. |
191
+ | CSS cannot target a button inside `::part(toolbar-group)` | `::part` does not expose descendant selectors. Use button/icon parts, public tokens or trusted `themeCss`/`theme-url` rules. |
192
+ | Duplicate/missing toolbar controls | Any custom group with default/true `hideDefaultToolbar` hides native draw/ruler controls. Set false on every group to keep native controls; keep group IDs unique. |
193
+ | No developer overlay | `dev-overlay` is reserved; no overlay UI ships. Use public status/diagnostics and browser DevTools. |
194
+ | Reconnection loses a basemap or session | Disconnect destroys the controller. Preserve host data, wait for readiness, reload data, then reapply the adapter. |
195
+
196
+ ## Logging and safe bug reports
197
+
198
+ Console levels are `trace`, `debug`, `info`, `warn`, `error`, `silent`; default is
199
+ `debug`. Configure an appropriate production level. Verbose logs can include
200
+ attribute values, tile URLs, GeoJSON and causes. General diagnostics are **not**
201
+ a credential-redaction boundary; only the dedicated provider/capability snapshots
202
+ intentionally omit keys/URLs/raw provider payloads. Even a message or status
203
+ `lastError.message` can contain a URL. Sanitize before sharing.
204
+
205
+ A useful report includes:
206
+
207
+ 1. Package version/entrypoint, browser, bundled versus external runtime setup.
208
+ 2. Minimal HTML/configuration with keys, private URLs, grower geometry and identifiers removed.
209
+ 3. Diagnostic code/severity/state/recoverable, status transition, and tool command ID
210
+ when relevant; only sanitized message/cause excerpts.
211
+ 4. Initial capability/configuration snapshots, reproduction steps, expected/actual behavior.
212
+ 5. Whether it reproduces with OSM or deterministic local tiles and minimal valid GeoJSON.
213
+
214
+ Never include service credentials, unrestricted paid keys, complete request URLs
215
+ with tokens, raw exports, or unredacted screenshots/network archives. Follow
216
+ [provider security guidance](providers.md#security-and-vendor-independence).
@@ -0,0 +1,145 @@
1
+ # GeoJSON pipelines
2
+
3
+ GeoKit exports `validateGeoJSON`, `normalizeGeoJSON`, `diffGeoJSON`,
4
+ `applyGeoJSONPatch`, `importGeoJSONData`, `importGeoJSONText`,
5
+ `importGeoJSONURL`, and `exportGeoJSONData` from the main and external entrypoints.
6
+ The helpers are framework-agnostic TypeScript and do not mutate a map or their
7
+ inputs. Package entrypoints register the web component and therefore require a
8
+ browser; these are not advertised as SSR entrypoints.
9
+
10
+ ## Reject uploads before changing the map
11
+
12
+ ```ts
13
+ import {
14
+ importGeoJSONText,
15
+ exportGeoJSONData,
16
+ diffGeoJSON,
17
+ applyGeoJSONPatch,
18
+ } from "@florasync/leaflet-geokit";
19
+
20
+ const upload = importGeoJSONText(fileText);
21
+ if (!upload.valid || !upload.data) {
22
+ showUploadErrors(upload.diagnostics);
23
+ return;
24
+ }
25
+ // CRS warnings are non-fatal. Your host may reject them too.
26
+ if (upload.diagnostics.some((d) => d.code === "crs-mismatch")) return;
27
+ await map.importGeoJSON(upload.data, { validate: true, fitToData: true });
28
+ const saved = structuredClone(await map.getGeoJSON());
29
+ // Later, after drawing/editing:
30
+ const current = await map.getGeoJSON();
31
+ const diff = diffGeoJSON(saved, current);
32
+ showSavePrompt(diff.createdIds, diff.updatedIds, diff.deletedIds);
33
+ const nextSaved = applyGeoJSONPatch(saved, diff);
34
+ const source = exportGeoJSONData(nextSaved, { adapter: "source" });
35
+ if (source.valid) persist(source.data);
36
+ else showUploadErrors(source.diagnostics);
37
+ ```
38
+
39
+ The illustrative host functions above are app-owned, not GeoKit APIs.
40
+
41
+ - `validateGeoJSON(unknown)` returns `{ valid, featureCount, diagnostics }`.
42
+ Each diagnostic has `severity`, `code`, `path`, and `message`.
43
+ - `importGeoJSONData(unknown)` accepts a Feature, FeatureCollection, or bare
44
+ geometry and returns the summary plus `data: FeatureCollection | null`.
45
+ - `importGeoJSONText(text)` parses JSON and returns `invalid-json` on parse errors.
46
+ - `importGeoJSONURL(url, { signal, fetcher })` fetches explicitly. Abort/network
47
+ failures and non-2xx HTTP responses reject; invalid JSON/data returns the
48
+ validation summary. The host owns URL trust, CORS, request timeouts and upload
49
+ size limits. Strings are never implicitly fetched.
50
+ - `normalizeGeoJSON(input, { expandMulti: false })` wraps the common shapes,
51
+ deep-clones JSON properties/coordinates, preserves supplied root IDs, and
52
+ assigns UUIDs to missing IDs (falling back to `properties.id`). Normalize once
53
+ and retain that snapshot: re-normalizing ID-less data generates new IDs.
54
+ Invalid input throws `GeoJSONValidationError` with a `.summary`.
55
+ - `{ expandMulti: true }` additionally creates single-geometry editing features,
56
+ including recursively nested GeometryCollections. Expansion collisions are
57
+ rejected. Each expanded child gets an isolated copy of app metadata.
58
+ - `map.importGeoJSON(fc, { validate: true })` validates and expands before any
59
+ replace/clear operation. Add mode also rejects IDs already present in the map.
60
+ The preflight runs after the ingest hook, so hook-modified data is checked.
61
+ This is opt-in for backwards compatibility; old import calls retain their
62
+ permissive behavior. These guarantees cover data-validation failures, not
63
+ arbitrary Leaflet/rendering failures.
64
+
65
+ ## Diagnostics and limits
66
+
67
+ Ingest and export summaries report invalid rings (minimum four positions and
68
+ exact closure), invalid positions/lines, unsupported geometry, empty/null
69
+ geometry, malformed JSON/properties/IDs, duplicate IDs, and malformed reserved
70
+ provenance. Multi geometries and GeometryCollections emit `multi-expansion`
71
+ information. Legacy `crs` declarations and out-of-range WGS84 coordinates emit
72
+ `crs-mismatch` warnings: GeoKit does not reproject or guess coordinate order.
73
+ An empty FeatureCollection is valid; an empty geometry is not editable and is
74
+ rejected. Cycles, non-finite values, sparse arrays, non-JSON metadata and excessive
75
+ nesting are rejected.
76
+
77
+ Validation is structural, not a GIS topology engine: it does not detect every
78
+ self-intersection, validate hole containment, repair rings, change winding,
79
+ reproject, or simplify geometry. Hosts needing those policies must apply a
80
+ separate topology validator. Normalization never silently repairs invalid data.
81
+
82
+ ## Metadata and source round trips
83
+
84
+ App-owned JSON belongs in `properties`; nested records and arrays are preserved.
85
+ All `geokit:*` property names are reserved for library use. Currently
86
+ `properties["geokit:source"]` is an internal provenance stack created by validated
87
+ Multi/collection expansion. Preserve it while editing; do not author or modify
88
+ it. It records source IDs, source geometry types, and the original `properties.id`
89
+ state. It contains no cached coordinates: source export reconstructs from the
90
+ current visible editing geometry, preserving singleton Multi types and nested
91
+ collection structure. Removed children stay removed; removing every child
92
+ removes the source feature.
93
+
94
+ Editing IDs are `sourceId::childIndex` (nested paths append another `::index`).
95
+ The existing map store uses string IDs, including for numeric root IDs.
96
+ Provenance-backed source export restores the original numeric Multi source ID
97
+ and original app-owned `properties.id`. For simple non-expanded features the
98
+ store's established string-ID behavior is unchanged. Diff ID lists are always
99
+ strings; `1` and `"1"` identify the same feature and cannot coexist.
100
+
101
+ `exportGeoJSONData(fc, { adapter: "source" })` returns the same summary/data shape
102
+ as the import helpers. It collapses only explicit provenance, not arbitrary app
103
+ IDs ending in `::0`. If sibling properties have diverged, it returns
104
+ `metadata-conflict` rather than silently discarding one child's edits. Reconcile
105
+ those properties or export the editing collection (the default adapter). It also
106
+ validates the reconstructed output. Legacy `map.exportGeoJSON({adapter:"source"})`
107
+ retains historical suffix inference and first-child metadata behavior; use the
108
+ new diagnostic helper for safe persistence. GeoJSON foreign members and cached
109
+ `bbox` values are not promised across Multi expansion; keep application data
110
+ under `properties` rather than foreign top-level fields.
111
+
112
+ Existing irrigation drawing, tool events, and layer-cake generation remain in
113
+ place; this pipeline wraps the existing expansion/export implementation rather
114
+ than introducing another map or drawing engine.
115
+
116
+ ## Diff and patch contract
117
+
118
+ `diffGeoJSON(before, after)` requires valid FeatureCollections with stable unique
119
+ IDs. It returns `created`, `updated` (complete feature payloads), and `deleted`
120
+ (string IDs), plus `createdIds`, `updatedIds`, and `deletedIds` for save prompts.
121
+ Geometry and metadata changes count; object-key and feature-array order do not.
122
+ Feature reordering and collection-level foreign-member changes are not tracked.
123
+
124
+ `applyGeoJSONPatch(base, patch)` is pure and atomic: it returns a deep-cloned
125
+ collection and never mutates `base`. Creates must be absent, updates/deletes must
126
+ exist, and operations may not overlap. It validates all feature payloads and
127
+ rejects conflicts. Existing feature order is retained; new features are appended.
128
+ This is an ID-based local patch format, not RFC 6902, a server transaction, or an
129
+ optimistic concurrency protocol. The host owns revision checks when saving.
130
+
131
+ ## Verification
132
+
133
+ ```sh
134
+ npm run test:unit:focused -- tests/geojson-pipeline.spec.ts tests/geojson.spec.ts tests/geojson-more.spec.ts tests/geojson-merge.spec.ts tests/map-controller.spec.ts
135
+ npm run typecheck
136
+ npm run test:e2e -- e2e/geojson-pipeline.spec.ts --workers=1
137
+ ```
138
+
139
+ The Playwright test uses the existing irrigation harness with real Leaflet
140
+ markers. It proves invalid replacement and duplicate-ID add rejection, edits a
141
+ visible marker through Leaflet's draw-edited event, compares visible coordinates
142
+ with export, checks nested app metadata/numeric source ID restoration, and
143
+ applies the save-prompt diff back to the baseline. In shared workspaces, pass
144
+ `--output="$PAPERCLIP_RUN_SCRATCH_DIR/geojson-playwright"` to avoid another run's
145
+ Playwright output directory.
@@ -0,0 +1,77 @@
1
+ # Google Maps optional adapter spike
2
+
3
+ Status: design spike only. No Google SDK, browser key, billing account, paid tile
4
+ endpoint or runtime network request has been added to GeoKit. Core stays Leaflet
5
+
6
+ - OSM. See [provider boundary and security guidance](providers.md).
7
+
8
+ ## Package boundary
9
+
10
+ A future, separately installed package (proposed name, **not published**:
11
+ `@florasync/geokit-google-adapter`) owns SDK loading, credentials policy, vendor
12
+ terms, attribution, quota/billing controls and Google-specific cleanup. It must
13
+ not be imported by core or automatically selected as fallback. Review vendor
14
+ terms for the chosen product and map-compositing approach before implementation.
15
+ Do not fabricate a Google raster URL or treat Google imagery as a generic XYZ
16
+ endpoint.
17
+
18
+ Two possible strategies, deliberately not conflated:
19
+
20
+ 1. A vendor-permitted Leaflet-compatible basemap bridge returns a fresh Leaflet
21
+ layer through `VectorBasemapProvider.createLayer` (or raster resolution only
22
+ when the licensed product genuinely supplies that contract). It uses existing
23
+ `setBasemapAdapter` and Leaflet.draw/irrigation features without touching the
24
+ public component API. The bridge must prove visual synchronization, attribution,
25
+ map-pane ordering, pointer routing and cleanup. Google SDK capability alone is
26
+ not evidence that such a bridge is permitted or drawing-compatible.
27
+ 2. A native Google map needs an implementation of the separate
28
+ `DrawEngineAdapter<Context, Document, Command>` design port plus translation to
29
+ GeoKit GeoJSON, stable IDs, public lifecycle events, edit/delete/move and
30
+ irrigation semantics. That is a larger optional package, not part of this
31
+ basemap shim. Do not advertise native Google drawing until parity is proven.
32
+
33
+ ## Authentication and spend decision
34
+
35
+ Browser Maps SDK credentials are observable. Moving them from an HTML attribute
36
+ into a JavaScript property, an environment variable bundled at build time, or a
37
+ proxy-delivered bootstrap response does not make them secret.
38
+
39
+ - Prefer approved server-side APIs behind a narrow authenticated gateway where
40
+ supported. Keep private credentials server-side, constrain requests, enforce
41
+ quotas and redact logs. A gateway cannot hide a browser SDK key while that SDK
42
+ still requires it in the browser, nor can it bypass usage/display terms.
43
+ - A browser SDK deployment is an explicitly approved exception: separate
44
+ application/environment keys, website-origin and API restrictions, usage
45
+ monitoring, quota controls, billing alerts, documented ownership and revocation.
46
+ Budget alerts alone are not a hard spending cap. Never use server/signing keys
47
+ in the client and never provision a paid account as part of a default install.
48
+ - State key requirements as `required`, offline support conservatively as
49
+ `unsupported` unless the exact licensed product allows and implements it.
50
+ Attribution cannot be hidden by GeoKit theme configuration.
51
+ - Keep user geometry independent of vendor objects and IDs. Round-trip fixtures
52
+ through the existing GeoJSON import/export pipeline. Switching back to OSM or
53
+ custom tiles must not lose user features or depend on a paid account.
54
+
55
+ ## Executable promotion checklist
56
+
57
+ The implementation owner can start in the optional package without changing the
58
+ new core basemap method:
59
+
60
+ 1. Select exact Google product and supported SDK/version; review licensing,
61
+ attribution/display and storage restrictions. Decide bridge versus native
62
+ renderer; record why existing drawing is supported or not.
63
+ 2. Obtain explicit provisioning and billing approval before live calls. Until then,
64
+ use contract fixtures with no credentials and no vendor requests.
65
+ 3. Implement fresh layer creation and cleanup for the bridge path. Mark native
66
+ rendering/drawing unavailable unless the separate draw port passes parity.
67
+ 4. Run GeoKit's provider unit/Chromium tests plus adapter-owned browser tests for
68
+ repeated mount/remove, auth denial, quota exhaustion, network loss, restoration
69
+ to OSM, attribution, resize/pan/zoom and read-only operation.
70
+ 5. Verify exports preserve user GeoJSON/IDs; exported files and diagnostics contain
71
+ no keys, session tokens, SDK objects or paid-vendor-only identifiers.
72
+ 6. Approve cost and security controls independently of technical feasibility. Ship
73
+ optional documentation and separate dependency entrypoint; no core dependency,
74
+ default switch or auto paid fallback.
75
+
76
+ Source: [Google Maps Platform security guidance](https://developers.google.com/maps/api-security-best-practices).
77
+ This spike is not a vendor-term approval or a claim of live Google validation.