@focus-daima/gis-workbench 0.0.0-stage → 0.9.9

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.
@@ -0,0 +1,30 @@
1
+ import json
2
+ import os
3
+ import shutil
4
+ import sys
5
+ import zipfile
6
+
7
+ archive = sys.argv[1]
8
+ out_dir = sys.argv[2]
9
+ root = os.path.realpath(out_dir)
10
+ os.makedirs(root, exist_ok=True)
11
+ total = 0
12
+ files = []
13
+ with zipfile.ZipFile(archive) as zf:
14
+ for info in zf.infolist():
15
+ if info.is_dir():
16
+ continue
17
+ name = info.filename.replace('\\', '/')
18
+ if name.startswith('__MACOSX/') or '/__MACOSX/' in name:
19
+ continue
20
+ target = os.path.realpath(os.path.join(root, name))
21
+ if target != root and not target.startswith(root + os.sep):
22
+ raise RuntimeError('Unsafe path in zip: ' + info.filename)
23
+ total += info.file_size
24
+ if total > 100 * 1024 * 1024 * 1024:
25
+ raise RuntimeError('Zip archive expands beyond 100 GB')
26
+ os.makedirs(os.path.dirname(target), exist_ok=True)
27
+ with zf.open(info) as src, open(target, 'wb') as dst:
28
+ shutil.copyfileobj(src, dst)
29
+ files.append(os.path.relpath(target, root))
30
+ print(json.dumps(files))
@@ -0,0 +1,133 @@
1
+ import json
2
+ import os
3
+ import sqlite3
4
+ import sys
5
+ from osgeo import ogr, osr
6
+
7
+ command = sys.argv[1]
8
+ cfg = json.loads(os.environ.get('GIS_VECTOR_EDIT', '{}'))
9
+ gpkg = cfg['gpkg']
10
+ table = cfg['table']
11
+
12
+
13
+ def open_gpkg(update):
14
+ driver = ogr.GetDriverByName('GPKG')
15
+ ds = ogr.Open(gpkg, 1 if update else 0)
16
+ if ds is None and update:
17
+ ds = driver.CreateDataSource(gpkg)
18
+ if ds is None:
19
+ raise RuntimeError('Cannot open GeoPackage: ' + gpkg)
20
+ return ds
21
+
22
+
23
+ def update_contents(extent):
24
+ if extent is None:
25
+ return
26
+ db = sqlite3.connect(gpkg)
27
+ db.execute(
28
+ 'UPDATE gpkg_contents SET min_x=?, min_y=?, max_x=?, max_y=? WHERE table_name=?',
29
+ (extent[0], extent[2], extent[1], extent[3], table),
30
+ )
31
+ db.commit()
32
+ db.close()
33
+
34
+
35
+ if command == 'create':
36
+ ds = open_gpkg(True)
37
+ existing = ds.GetLayerByName(table)
38
+ if existing is not None:
39
+ raise RuntimeError('Layer already exists: ' + table)
40
+ srs = osr.SpatialReference()
41
+ srs.ImportFromEPSG(4326)
42
+ layer = ds.CreateLayer(table, srs, ogr.wkbMultiPolygon)
43
+ if layer is None:
44
+ raise RuntimeError('Cannot create layer: ' + table)
45
+ layer.CreateField(ogr.FieldDefn('name', ogr.OFTString))
46
+ layer.CreateField(ogr.FieldDefn('created_at', ogr.OFTString))
47
+ ds = None
48
+ print(json.dumps({'table': table, 'geometryType': 'MultiPolygon', 'fields': ['name', 'created_at']}))
49
+ sys.exit(0)
50
+
51
+ if command == 'add':
52
+ geometry_json = cfg['geometry']
53
+ geometry = ogr.CreateGeometryFromJson(json.dumps(geometry_json))
54
+ if geometry is None:
55
+ raise RuntimeError('Invalid GeoJSON geometry')
56
+ if geometry.GetGeometryType() == ogr.wkbPolygon:
57
+ geometry = ogr.ForceToMultiPolygon(geometry)
58
+ if geometry.GetGeometryType() != ogr.wkbMultiPolygon:
59
+ raise RuntimeError('Only Polygon/MultiPolygon geometry is supported')
60
+ ds = open_gpkg(True)
61
+ layer = ds.GetLayerByName(table)
62
+ if layer is None:
63
+ raise RuntimeError('Layer not found: ' + table)
64
+ feature = ogr.Feature(layer.GetLayerDefn())
65
+ feature.SetField('name', cfg.get('name') or '未命名多边形')
66
+ feature.SetField('created_at', cfg.get('createdAt') or '')
67
+ feature.SetGeometry(geometry)
68
+ layer.CreateFeature(feature)
69
+ extent = layer.GetExtent(1)
70
+ feature_count = layer.GetFeatureCount()
71
+ layer = None
72
+ ds = None
73
+ update_contents(extent)
74
+ print(json.dumps({'featureCount': feature_count, 'extent': list(extent)}))
75
+ sys.exit(0)
76
+
77
+ if command == 'update':
78
+ target_name = cfg.get('name')
79
+ target_created = cfg.get('createdAt')
80
+ geometry = ogr.CreateGeometryFromJson(json.dumps(cfg['geometry']))
81
+ if geometry is None:
82
+ raise RuntimeError('Invalid GeoJSON geometry')
83
+ if geometry.GetGeometryType() == ogr.wkbPolygon:
84
+ geometry = ogr.ForceToMultiPolygon(geometry)
85
+ if geometry.GetGeometryType() != ogr.wkbMultiPolygon:
86
+ raise RuntimeError('Only Polygon/MultiPolygon geometry is supported')
87
+ ds = open_gpkg(True)
88
+ layer = ds.GetLayerByName(table)
89
+ if layer is None:
90
+ raise RuntimeError('Layer not found: ' + table)
91
+ found = 0
92
+ for feature in layer:
93
+ if target_name is not None and feature.GetField('name') != target_name:
94
+ continue
95
+ if target_created is not None and feature.GetField('created_at') != target_created:
96
+ continue
97
+ feature.SetGeometry(geometry)
98
+ layer.SetFeature(feature)
99
+ found += 1
100
+ break
101
+ feature_count = layer.GetFeatureCount()
102
+ extent = layer.GetExtent(1)
103
+ layer = None
104
+ ds = None
105
+ update_contents(extent)
106
+ print(json.dumps({'updated': found, 'featureCount': feature_count, 'extent': list(extent)}))
107
+ sys.exit(0)
108
+
109
+ if command == 'delete':
110
+ target_name = cfg.get('name')
111
+ target_created = cfg.get('createdAt')
112
+ ds = open_gpkg(True)
113
+ layer = ds.GetLayerByName(table)
114
+ if layer is None:
115
+ raise RuntimeError('Layer not found: ' + table)
116
+ deleted = 0
117
+ for feature in layer:
118
+ if target_name is not None and feature.GetField('name') != target_name:
119
+ continue
120
+ if target_created is not None and feature.GetField('created_at') != target_created:
121
+ continue
122
+ layer.DeleteFeature(feature.GetFID())
123
+ deleted += 1
124
+ break
125
+ feature_count = layer.GetFeatureCount()
126
+ extent = layer.GetExtent(1) if feature_count > 0 else None
127
+ layer = None
128
+ ds = None
129
+ update_contents(extent)
130
+ print(json.dumps({'deleted': deleted, 'featureCount': feature_count, 'extent': list(extent) if extent else None}))
131
+ sys.exit(0)
132
+
133
+ raise SystemExit('Unknown command: ' + command)
@@ -0,0 +1,48 @@
1
+ import json
2
+ import sys
3
+ from osgeo import ogr
4
+
5
+ path = sys.argv[1]
6
+ layer_name = sys.argv[2] if len(sys.argv) > 2 else None
7
+ ds = ogr.Open(path, 0)
8
+ if ds is None:
9
+ raise SystemExit('Cannot open vector dataset: ' + path)
10
+
11
+
12
+ def layer_info(layer):
13
+ extent = layer.GetExtent()
14
+ fields = []
15
+ definition = layer.GetLayerDefn()
16
+ for index in range(definition.GetFieldCount()):
17
+ field = definition.GetFieldDefn(index)
18
+ fields.append({'name': field.GetName(), 'type': field.GetTypeName()})
19
+ srs = layer.GetSpatialRef()
20
+ epsg = None
21
+ if srs is not None:
22
+ try:
23
+ srs.AutoIdentifyEPSG()
24
+ code = srs.GetAuthorityCode(None)
25
+ if code:
26
+ epsg = int(code)
27
+ except Exception:
28
+ pass
29
+ return {
30
+ 'name': layer.GetName(),
31
+ 'featureCount': layer.GetFeatureCount(),
32
+ 'extent': list(extent) if extent else None,
33
+ 'bbox': [extent[0], extent[2], extent[1], extent[3]] if extent else None,
34
+ 'fields': fields,
35
+ 'geometryType': ogr.GeometryTypeToName(layer.GetGeomType()),
36
+ 'crs': epsg,
37
+ }
38
+
39
+ if layer_name:
40
+ layer = ds.GetLayerByName(layer_name)
41
+ if layer is None:
42
+ raise SystemExit('Layer not found: ' + layer_name)
43
+ print(json.dumps({'layer': layer_info(layer)}))
44
+ else:
45
+ layers = []
46
+ for index in range(ds.GetLayerCount()):
47
+ layers.append(layer_info(ds.GetLayerByIndex(index)))
48
+ print(json.dumps({'layers': layers}))
package/shared.js ADDED
@@ -0,0 +1,37 @@
1
+ /** Shared constants between the Host tool and the Client map. */
2
+ export const TOOL_NAME = 'gis_add_layer';
3
+ export const VIEW_TOOL_NAME = 'gis_set_view';
4
+ export const DEFAULT_LAYER_NAME = '天地图影像';
5
+ export const DEFAULT_TILE_URL = '//your-tile-host/api/gis-map-service/world-map-tiles/images/tiandi-image-3857/{z}/{x}/{y}';
6
+ export const DEFAULT_TILE_SIZE = 256;
7
+ export const DEFAULT_ATTRIBUTION = '天地图';
8
+ export const DEFAULT_VIEW_ZOOM = 11;
9
+
10
+ /**
11
+ * Small built-in gazetteer the Host resolves when a view request names a place
12
+ * instead of raw coordinates. Keys are lower-case latin aliases; every entry
13
+ * carries the Chinese label shown in the UI.
14
+ */
15
+ export const PLACE_PRESETS = {
16
+ hangzhou: { label: '中国 · 杭州', center: [120.1551, 30.2741], zoom: 11 },
17
+ '杭州': { label: '中国 · 杭州', center: [120.1551, 30.2741], zoom: 11 },
18
+ beijing: { label: '中国 · 北京', center: [116.4074, 39.9042], zoom: 11 },
19
+ '北京': { label: '中国 · 北京', center: [116.4074, 39.9042], zoom: 11 },
20
+ shanghai: { label: '中国 · 上海', center: [121.4737, 31.2304], zoom: 11 },
21
+ '上海': { label: '中国 · 上海', center: [121.4737, 31.2304], zoom: 11 },
22
+ shenzhen: { label: '中国 · 深圳', center: [114.0579, 22.5431], zoom: 11 },
23
+ '深圳': { label: '中国 · 深圳', center: [114.0579, 22.5431], zoom: 11 },
24
+ guangzhou: { label: '中国 · 广州', center: [113.2644, 23.1291], zoom: 11 },
25
+ '广州': { label: '中国 · 广州', center: [113.2644, 23.1291], zoom: 11 },
26
+ chengdu: { label: '中国 · 成都', center: [104.0665, 30.5723], zoom: 11 },
27
+ '成都': { label: '中国 · 成都', center: [104.0665, 30.5723], zoom: 11 },
28
+ xian: { label: '中国 · 西安', center: [108.9398, 34.3416], zoom: 11 },
29
+ '西安': { label: '中国 · 西安', center: [108.9398, 34.3416], zoom: 11 },
30
+ china: { label: '中国', center: [104.2, 35.5], zoom: 3.4 },
31
+ '中国': { label: '中国', center: [104.2, 35.5], zoom: 3.4 },
32
+ };
33
+ export const LIST_LAYERS_TOOL_NAME = 'gis_list_layers';
34
+ export const DESCRIBE_LAYER_TOOL_NAME = 'gis_describe_layer';
35
+ export const SAMPLE_FIELD_TOOL_NAME = 'gis_sample_field';
36
+ export const MAP_CAPABILITIES_TOOL_NAME = 'gis_map_capabilities';
37
+ export const UPDATE_STYLE_TOOL_NAME = 'gis_update_layer_style';
package/src/api.js ADDED
@@ -0,0 +1,269 @@
1
+ const BASE = '/api/gis-workbench';
2
+
3
+ async function request(path, options = {}) {
4
+ const init = {
5
+ method: options.method || 'GET',
6
+ credentials: 'same-origin',
7
+ headers: { ...(options.headers || {}) },
8
+ };
9
+ if (options.body !== undefined) {
10
+ if (options.body instanceof FormData) {
11
+ init.body = options.body;
12
+ } else {
13
+ init.headers['content-type'] = 'application/json';
14
+ init.body = JSON.stringify(options.body);
15
+ }
16
+ }
17
+ const response = await fetch(BASE + path, init);
18
+ const type = response.headers.get('content-type') || '';
19
+ let payload = null;
20
+ if (type.includes('application/json')) {
21
+ payload = await response.json().catch(() => null);
22
+ } else {
23
+ const text = await response.text().catch(() => '');
24
+ payload = text ? { error: text } : null;
25
+ }
26
+ if (!response.ok) {
27
+ const error = new Error((payload && payload.error) || `Request failed (${response.status})`);
28
+ error.status = response.status;
29
+ throw error;
30
+ }
31
+ return payload;
32
+ }
33
+
34
+ function query(path, params) {
35
+ const url = new URL(path, 'http://local');
36
+ for (const [key, value] of Object.entries(params || {})) {
37
+ if (value !== undefined && value !== null && value !== '') url.searchParams.set(key, value);
38
+ }
39
+ return url.pathname + (url.search || '');
40
+ }
41
+
42
+ export function getBootstrap() {
43
+ return request('');
44
+ }
45
+
46
+ export function listProjects() {
47
+ return request('/projects').then((value) => value.projects || []);
48
+ }
49
+
50
+ export function createProject(input) {
51
+ return request('/projects', { method: 'POST', body: input }).then((value) => value.project);
52
+ }
53
+
54
+ export function updateProject(id, input) {
55
+ return request('/projects/' + encodeURIComponent(id), { method: 'PATCH', body: input }).then((value) => value.project);
56
+ }
57
+
58
+ export function saveProjectState(projectId, state) {
59
+ return request('/projects/' + encodeURIComponent(projectId) + '/state', {
60
+ method: 'PUT',
61
+ body: state,
62
+ });
63
+ }
64
+
65
+ export function listDatasets(projectId) {
66
+ return request('/projects/' + encodeURIComponent(projectId) + '/datasets').then((value) => value.datasets || []);
67
+ }
68
+
69
+ export function createDataset(projectId, input) {
70
+ return request('/projects/' + encodeURIComponent(projectId) + '/datasets', {
71
+ method: 'POST',
72
+ body: input,
73
+ });
74
+ }
75
+
76
+ export function createTileDataset(projectId, input) {
77
+ return request('/projects/' + encodeURIComponent(projectId) + '/datasets/tile', {
78
+ method: 'POST',
79
+ body: input,
80
+ });
81
+ }
82
+
83
+ export function uploadDataset(projectId, file, options = {}) {
84
+ const form = new FormData();
85
+ form.set('file', file, file.name);
86
+ if (options.crs !== undefined && options.crs !== null && options.crs !== '') form.set('crs', String(options.crs));
87
+ if (options.bbox !== undefined && options.bbox !== null && options.bbox !== '') {
88
+ form.set('bbox', typeof options.bbox === 'string' ? options.bbox : JSON.stringify(options.bbox));
89
+ }
90
+ if (options.addLayer) form.set('addLayer', 'true');
91
+ return request('/projects/' + encodeURIComponent(projectId) + '/datasets/upload', {
92
+ method: 'POST',
93
+ body: form,
94
+ });
95
+ }
96
+
97
+ export function convertDataset(id, options = {}) {
98
+ return request('/datasets/' + encodeURIComponent(id) + '/convert', {
99
+ method: 'POST',
100
+ body: { force: options.force === true },
101
+ }).then((value) => value.dataset);
102
+ }
103
+
104
+ export function deleteDataset(id) {
105
+ return request('/datasets/' + encodeURIComponent(id), { method: 'DELETE' });
106
+ }
107
+
108
+ export function listLayers(projectId) {
109
+ return request('/projects/' + encodeURIComponent(projectId) + '/layers').then((value) => value.layers || []);
110
+ }
111
+
112
+ export function createLayer(projectId, input) {
113
+ return request('/projects/' + encodeURIComponent(projectId) + '/layers', {
114
+ method: 'POST',
115
+ body: input,
116
+ }).then((value) => value.layer);
117
+ }
118
+
119
+ export function updateLayer(id, input) {
120
+ return request('/layers/' + encodeURIComponent(id), {
121
+ method: 'PATCH',
122
+ body: input,
123
+ }).then((value) => value.layer);
124
+ }
125
+
126
+ export function deleteLayer(id) {
127
+ return request('/layers/' + encodeURIComponent(id), { method: 'DELETE' });
128
+ }
129
+
130
+ export function browse(pathname) {
131
+ return request(query('/browse', { path: pathname }));
132
+ }
133
+
134
+ export function contentUrl(datasetId) {
135
+ return BASE + '/datasets/' + encodeURIComponent(datasetId) + '/content';
136
+ }
137
+
138
+ export function initUpload(projectId, input) {
139
+ return request('/projects/' + encodeURIComponent(projectId) + '/uploads/init', {
140
+ method: 'POST',
141
+ body: input,
142
+ }).then((value) => value.upload);
143
+ }
144
+
145
+ export function getUpload(uploadId) {
146
+ return request('/uploads/' + encodeURIComponent(uploadId)).then((value) => value.upload);
147
+ }
148
+
149
+ export function deleteUpload(uploadId) {
150
+ return request('/uploads/' + encodeURIComponent(uploadId), { method: 'DELETE' });
151
+ }
152
+
153
+ export function completeUpload(uploadId, input = {}) {
154
+ return request('/uploads/' + encodeURIComponent(uploadId) + '/complete', {
155
+ method: 'POST',
156
+ body: input,
157
+ });
158
+ }
159
+
160
+ export function uploadChunk(uploadId, index, blob, onProgress, signal) {
161
+ return new Promise((resolve, reject) => {
162
+ const xhr = new XMLHttpRequest();
163
+ let settled = false;
164
+ const cleanup = () => {
165
+ signal?.removeEventListener('abort', onAbort);
166
+ };
167
+ const fail = (error) => {
168
+ if (settled) return;
169
+ settled = true;
170
+ cleanup();
171
+ reject(error);
172
+ };
173
+ const done = (value) => {
174
+ if (settled) return;
175
+ settled = true;
176
+ cleanup();
177
+ resolve(value);
178
+ };
179
+ const onAbort = () => {
180
+ try {
181
+ xhr.abort();
182
+ } catch (error) {
183
+ // The request may already be settled.
184
+ }
185
+ const error = new Error('Upload aborted');
186
+ error.name = 'AbortError';
187
+ fail(error);
188
+ };
189
+ xhr.open('PUT', BASE + '/uploads/' + encodeURIComponent(uploadId) + '/chunks/' + index);
190
+ xhr.setRequestHeader('content-type', 'application/octet-stream');
191
+ xhr.upload.onprogress = (event) => {
192
+ if (onProgress && event.lengthComputable) onProgress(event.loaded);
193
+ };
194
+ xhr.onload = () => {
195
+ let payload = null;
196
+ try {
197
+ payload = xhr.responseText ? JSON.parse(xhr.responseText) : null;
198
+ } catch (error) {
199
+ payload = null;
200
+ }
201
+ if (xhr.status >= 200 && xhr.status < 300) done(payload && payload.upload ? payload.upload : payload);
202
+ else fail(new Error((payload && payload.error) || `Chunk upload failed (${xhr.status})`));
203
+ };
204
+ xhr.onerror = () => fail(new Error('Network error while uploading chunk'));
205
+ xhr.ontimeout = () => fail(new Error('Chunk upload timed out'));
206
+ if (signal) {
207
+ if (signal.aborted) {
208
+ onAbort();
209
+ return;
210
+ }
211
+ signal.addEventListener('abort', onAbort, { once: true });
212
+ }
213
+ xhr.send(blob);
214
+ });
215
+ }
216
+
217
+ export function listDatabases(projectId) {
218
+ return request('/projects/' + encodeURIComponent(projectId) + '/databases').then((value) => value.databases || []);
219
+ }
220
+
221
+ export function createDatabase(projectId, input) {
222
+ return request('/projects/' + encodeURIComponent(projectId) + '/databases', {
223
+ method: 'POST',
224
+ body: input,
225
+ }).then((value) => value.database);
226
+ }
227
+
228
+ export function deleteDatabase(databaseId) {
229
+ return request('/databases/' + encodeURIComponent(databaseId), { method: 'DELETE' });
230
+ }
231
+
232
+ export function listDatabaseTables(databaseId) {
233
+ return request('/databases/' + encodeURIComponent(databaseId) + '/tables').then((value) => value.tables || []);
234
+ }
235
+
236
+ export function importDatabaseTable(databaseId, input) {
237
+ return request('/databases/' + encodeURIComponent(databaseId) + '/tables/import', {
238
+ method: 'POST',
239
+ body: input,
240
+ });
241
+ }
242
+
243
+ export function createVectorLayer(projectId, input) {
244
+ return request('/projects/' + encodeURIComponent(projectId) + '/vector-layers', {
245
+ method: 'POST',
246
+ body: input,
247
+ });
248
+ }
249
+
250
+ export function addVectorFeature(datasetId, input) {
251
+ return request('/datasets/' + encodeURIComponent(datasetId) + '/features', {
252
+ method: 'POST',
253
+ body: input,
254
+ }).then((value) => value.dataset);
255
+ }
256
+
257
+ export function deleteVectorFeature(datasetId, input) {
258
+ return request('/datasets/' + encodeURIComponent(datasetId) + '/features/delete', {
259
+ method: 'POST',
260
+ body: input,
261
+ }).then((value) => value.dataset);
262
+ }
263
+
264
+ export function updateVectorFeature(datasetId, input) {
265
+ return request('/datasets/' + encodeURIComponent(datasetId) + '/features/update', {
266
+ method: 'POST',
267
+ body: input,
268
+ }).then((value) => value.dataset);
269
+ }
@@ -0,0 +1,9 @@
1
+ import { createPlugin } from './plugin.js';
2
+
3
+ window.__ModuleLoader__.load({
4
+ id: '@focus-daima/gis-workbench',
5
+ factory(require) {
6
+ const React = require('react');
7
+ return createPlugin(React);
8
+ },
9
+ });