@tileflow/dev 0.1.0-alpha.13 → 0.1.0-alpha.16
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/README.md +105 -0
- package/dist/index.d.ts +236 -2
- package/dist/index.js +2053 -219
- package/package.json +14 -6
package/dist/index.js
CHANGED
|
@@ -1,203 +1,1838 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
2
|
import { createJiti } from "jiti";
|
|
3
|
-
import { existsSync as
|
|
3
|
+
import { existsSync, readFileSync, realpathSync as realpathSync2 } from "fs";
|
|
4
4
|
import { mkdir, writeFile } from "fs/promises";
|
|
5
|
-
import {
|
|
5
|
+
import { createRequire } from "module";
|
|
6
|
+
import { dirname as dirname2, isAbsolute as isAbsolute3, join, relative as relative3, resolve as resolve3, sep as sep3 } from "path";
|
|
6
7
|
import {
|
|
8
|
+
compareCodeUnits as compareCodeUnits3,
|
|
7
9
|
createManifest,
|
|
8
|
-
createStyleFromProject,
|
|
10
|
+
createStyleFromProject as createStyleFromProject2,
|
|
9
11
|
validateConfig
|
|
10
12
|
} from "@tileflow/core";
|
|
11
13
|
|
|
12
14
|
// src/icons.ts
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
15
|
+
import { readdir, readFile, realpath, stat } from "fs/promises";
|
|
16
|
+
import { basename, extname, isAbsolute, relative, resolve, sep } from "path";
|
|
17
|
+
import { SaxesParser } from "saxes";
|
|
18
|
+
import {
|
|
19
|
+
compareCodeUnits,
|
|
20
|
+
hashTileflowIconPackageManifest,
|
|
21
|
+
hashTileflowRenderedIconPixels,
|
|
22
|
+
serializeCanonicalJson,
|
|
23
|
+
sha256Hex,
|
|
24
|
+
tileflowHostedIconIdPattern,
|
|
25
|
+
tileflowIconPackageLabelSchema,
|
|
26
|
+
tileflowIconPackageLimits,
|
|
27
|
+
tileflowIconPackageManifestSchema
|
|
28
|
+
} from "@tileflow/core";
|
|
29
|
+
var TileflowIconCompilationError = class extends Error {
|
|
30
|
+
code = "ICON_INVALID";
|
|
31
|
+
issues;
|
|
32
|
+
phase = "icon-compilation";
|
|
33
|
+
constructor(issues) {
|
|
34
|
+
super(
|
|
35
|
+
[
|
|
36
|
+
"Invalid Tileflow icon package",
|
|
37
|
+
...issues.map((issue) => `- ${issue.path}: ${issue.message}`)
|
|
38
|
+
].join("\n")
|
|
39
|
+
);
|
|
40
|
+
this.name = "TileflowIconCompilationError";
|
|
41
|
+
this.issues = issues;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
16
44
|
var iconFileExtensions = /* @__PURE__ */ new Set([".svg", ".png", ".jpg", ".jpeg", ".webp"]);
|
|
17
45
|
var iconSpriteSize = 24;
|
|
46
|
+
async function compileTileflowIconPackages(project, options) {
|
|
47
|
+
const result = await compileIconSources(project, options);
|
|
48
|
+
const packagesByHash = /* @__PURE__ */ new Map();
|
|
49
|
+
for (const compiled of result.compiledBySource.values()) {
|
|
50
|
+
packagesByHash.set(compiled.package.contentHash, compiled.package);
|
|
51
|
+
}
|
|
52
|
+
const bindings = result.resolvedRequests.map((request) => {
|
|
53
|
+
const compiled = result.compiledBySource.get(request.realSourceDir);
|
|
54
|
+
if (!compiled) {
|
|
55
|
+
throw new Error(`Missing compiled icon package for map ${request.mapName}`);
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
label: request.label,
|
|
59
|
+
mapName: request.mapName,
|
|
60
|
+
...request.mapping ? { mapping: request.mapping } : {},
|
|
61
|
+
packageHash: compiled.package.contentHash
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
return {
|
|
65
|
+
bindings,
|
|
66
|
+
packages: [...packagesByHash.values()].sort(
|
|
67
|
+
(left, right) => compareCodeUnits(left.contentHash, right.contentHash)
|
|
68
|
+
),
|
|
69
|
+
watchPaths: [...result.compiledBySource.keys()].sort(compareCodeUnits)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
async function inspectTileflowIconCatalogs(project, options) {
|
|
73
|
+
const result = await compileIconSources(project, {
|
|
74
|
+
cwd: options.cwd,
|
|
75
|
+
mapNames: options.mapNames,
|
|
76
|
+
target: "local"
|
|
77
|
+
});
|
|
78
|
+
const resolvedByMap = new Map(
|
|
79
|
+
result.resolvedRequests.map((request) => [request.mapName, request])
|
|
80
|
+
);
|
|
81
|
+
const mappedFromBySource = /* @__PURE__ */ new Map();
|
|
82
|
+
const maps = result.mapRequests.map((request) => {
|
|
83
|
+
if (request.kind !== "local") {
|
|
84
|
+
return {
|
|
85
|
+
name: request.mapName,
|
|
86
|
+
icons: {
|
|
87
|
+
inspectable: false,
|
|
88
|
+
kind: request.kind,
|
|
89
|
+
mappings: createCatalogMappings(request.mapping, "unknown")
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const resolved = resolvedByMap.get(request.mapName);
|
|
94
|
+
if (!resolved || !result.realCwd) {
|
|
95
|
+
throw new Error(`Missing resolved icon source for map ${request.mapName}`);
|
|
96
|
+
}
|
|
97
|
+
const compiled = result.compiledBySource.get(resolved.realSourceDir);
|
|
98
|
+
if (!compiled) {
|
|
99
|
+
throw new Error(`Missing compiled icon catalog for map ${request.mapName}`);
|
|
100
|
+
}
|
|
101
|
+
const iconNames = new Set(compiled.package.manifest.iconNames);
|
|
102
|
+
const mappings = createCatalogMappings(
|
|
103
|
+
request.mapping,
|
|
104
|
+
(iconId) => iconNames.has(iconId) ? "present" : "missing"
|
|
105
|
+
);
|
|
106
|
+
const mappedFromByIcon = mappedFromBySource.get(resolved.realSourceDir) ?? /* @__PURE__ */ new Map();
|
|
107
|
+
for (const mapping of mappings) {
|
|
108
|
+
if (mapping.targetStatus !== "present") {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const mappedFrom = mappedFromByIcon.get(mapping.iconId) ?? [];
|
|
112
|
+
mappedFrom.push({ map: request.mapName, semantic: mapping.semantic });
|
|
113
|
+
mappedFromByIcon.set(mapping.iconId, mappedFrom);
|
|
114
|
+
}
|
|
115
|
+
mappedFromBySource.set(resolved.realSourceDir, mappedFromByIcon);
|
|
116
|
+
return {
|
|
117
|
+
name: request.mapName,
|
|
118
|
+
icons: {
|
|
119
|
+
catalogSourcePath: relativePortablePath(result.realCwd, resolved.realSourceDir),
|
|
120
|
+
kind: "local",
|
|
121
|
+
label: request.label,
|
|
122
|
+
mappings,
|
|
123
|
+
packageHash: compiled.package.contentHash
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
if (!result.realCwd) {
|
|
128
|
+
return { catalogs: [], maps };
|
|
129
|
+
}
|
|
130
|
+
const realCwd = result.realCwd;
|
|
131
|
+
const catalogs = [...result.compiledBySource.entries()].map(([realSourceDir, compiled]) => {
|
|
132
|
+
const sourcePath2 = relativePortablePath(realCwd, realSourceDir);
|
|
133
|
+
const mappedFromByIcon = mappedFromBySource.get(realSourceDir) ?? /* @__PURE__ */ new Map();
|
|
134
|
+
return {
|
|
135
|
+
compiledPackage: compiled.package,
|
|
136
|
+
icons: compiled.icons.map((icon, index) => {
|
|
137
|
+
const manifestIcon = compiled.package.manifest.renderedIcons[index];
|
|
138
|
+
const oneXAtlas = compiled.layoutOneX.index[icon.input.name];
|
|
139
|
+
const twoXAtlas = compiled.layoutTwoX.index[icon.input.name];
|
|
140
|
+
if (!manifestIcon || manifestIcon.name !== icon.input.name || !oneXAtlas || !twoXAtlas) {
|
|
141
|
+
throw new Error(`Missing compiled catalog metadata for icon ${icon.input.name}`);
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
id: icon.input.name,
|
|
145
|
+
mappedFrom: [...mappedFromByIcon.get(icon.input.name) ?? []].sort(compareMappedFrom),
|
|
146
|
+
rendered: {
|
|
147
|
+
oneX: {
|
|
148
|
+
atlas: atlasRectangle(oneXAtlas),
|
|
149
|
+
height: icon.oneX.height,
|
|
150
|
+
pixelRatio: 1,
|
|
151
|
+
pixelSha256: manifestIcon.pixelSha256.oneX,
|
|
152
|
+
width: icon.oneX.width
|
|
153
|
+
},
|
|
154
|
+
twoX: {
|
|
155
|
+
atlas: atlasRectangle(twoXAtlas),
|
|
156
|
+
height: icon.twoX.height,
|
|
157
|
+
pixelRatio: 2,
|
|
158
|
+
pixelSha256: manifestIcon.pixelSha256.twoX,
|
|
159
|
+
width: icon.twoX.width
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
source: {
|
|
163
|
+
byteLength: icon.input.source.byteLength,
|
|
164
|
+
dimensions: { ...icon.dimensions },
|
|
165
|
+
format: icon.input.format,
|
|
166
|
+
path: relativePortablePath(realCwd, icon.input.path)
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
}),
|
|
170
|
+
insideWorkingTree: isPathInside(realCwd, realSourceDir),
|
|
171
|
+
sourcePath: sourcePath2
|
|
172
|
+
};
|
|
173
|
+
}).sort((left, right) => compareCodeUnits(left.sourcePath, right.sourcePath));
|
|
174
|
+
return { catalogs, maps };
|
|
175
|
+
}
|
|
176
|
+
async function compileIconSources(project, options) {
|
|
177
|
+
const mapRequests = getMapIconRequests(project, options.cwd, options.mapNames);
|
|
178
|
+
const requests = mapRequests.filter(
|
|
179
|
+
(request) => request.kind === "local"
|
|
180
|
+
);
|
|
181
|
+
if (requests.length === 0) {
|
|
182
|
+
return {
|
|
183
|
+
compiledBySource: /* @__PURE__ */ new Map(),
|
|
184
|
+
mapRequests,
|
|
185
|
+
realCwd: null,
|
|
186
|
+
resolvedRequests: []
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
const issues = [];
|
|
190
|
+
const realCwd = await resolveWorkingDirectory(options.cwd, issues);
|
|
191
|
+
const resolvedRequests = [];
|
|
192
|
+
for (const request of requests) {
|
|
193
|
+
try {
|
|
194
|
+
const realSourceDir = await realpath(request.sourceDir);
|
|
195
|
+
if (options.target === "hosted" && realCwd && !isPathInside(realCwd, realSourceDir)) {
|
|
196
|
+
issues.push({
|
|
197
|
+
message: "Hosted icon sources must remain inside the selected working tree",
|
|
198
|
+
path: sourcePath(request.mapName)
|
|
199
|
+
});
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
const sourceStat = await stat(realSourceDir);
|
|
203
|
+
if (!sourceStat.isDirectory()) {
|
|
204
|
+
issues.push({
|
|
205
|
+
message: "Icon source must be a directory",
|
|
206
|
+
path: sourcePath(request.mapName)
|
|
207
|
+
});
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
resolvedRequests.push({ ...request, realSourceDir });
|
|
211
|
+
} catch (error) {
|
|
212
|
+
issues.push({
|
|
213
|
+
message: describeFileSystemError(error, "Icon source was not found"),
|
|
214
|
+
path: sourcePath(request.mapName)
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const inspectedBySource = /* @__PURE__ */ new Map();
|
|
219
|
+
const requestsBySource = groupRequestsBySource(resolvedRequests);
|
|
220
|
+
for (const [realSourceDir, sourceRequests] of requestsBySource) {
|
|
221
|
+
const representative = sourceRequests[0];
|
|
222
|
+
if (!representative) {
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const inspected = await inspectIconSource(
|
|
226
|
+
representative,
|
|
227
|
+
realSourceDir,
|
|
228
|
+
realCwd,
|
|
229
|
+
options.target,
|
|
230
|
+
issues
|
|
231
|
+
);
|
|
232
|
+
if (inspected) {
|
|
233
|
+
inspectedBySource.set(realSourceDir, inspected);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (issues.length > 0) {
|
|
237
|
+
throw new TileflowIconCompilationError(issues);
|
|
238
|
+
}
|
|
239
|
+
const compiledBySource = /* @__PURE__ */ new Map();
|
|
240
|
+
for (const [realSourceDir, inspected] of inspectedBySource) {
|
|
241
|
+
const representative = requestsBySource.get(realSourceDir)?.[0];
|
|
242
|
+
if (!representative) {
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
compiledBySource.set(realSourceDir, await compileInspectedIconSource(inspected));
|
|
247
|
+
} catch (error) {
|
|
248
|
+
issues.push({
|
|
249
|
+
message: error instanceof Error ? error.message : "Icon compilation failed",
|
|
250
|
+
path: sourcePath(representative.mapName)
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (issues.length > 0) {
|
|
255
|
+
throw new TileflowIconCompilationError(issues);
|
|
256
|
+
}
|
|
257
|
+
return { compiledBySource, mapRequests, realCwd, resolvedRequests };
|
|
258
|
+
}
|
|
18
259
|
async function prepareTileflowProjectIcons(project, options) {
|
|
19
260
|
const nextProject = cloneProject(project);
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
261
|
+
const compiled = await compileTileflowIconPackages(project, {
|
|
262
|
+
cwd: options.cwd,
|
|
263
|
+
target: "local"
|
|
264
|
+
});
|
|
265
|
+
const packagesByHash = new Map(
|
|
266
|
+
compiled.packages.map((iconPackage) => [iconPackage.contentHash, iconPackage])
|
|
267
|
+
);
|
|
268
|
+
const assets = [];
|
|
269
|
+
for (const binding of compiled.bindings) {
|
|
270
|
+
const mapConfig = nextProject.maps[binding.mapName];
|
|
271
|
+
const iconPackage = packagesByHash.get(binding.packageHash);
|
|
272
|
+
if (!mapConfig || !iconPackage) {
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
const spriteUrl = joinUrl(options.assetBaseUrl, `icons/${binding.mapName}/sprite`);
|
|
276
|
+
mapConfig.icons = {
|
|
277
|
+
...binding.mapping ? { mapping: binding.mapping } : {},
|
|
278
|
+
sprite: spriteUrl
|
|
279
|
+
};
|
|
280
|
+
for (const file of iconPackage.files) {
|
|
281
|
+
assets.push({
|
|
282
|
+
contentType: file.contentType === "application/json" ? "application/json; charset=utf-8" : file.contentType,
|
|
283
|
+
fileName: `icons/${binding.mapName}/${file.fileName}`,
|
|
284
|
+
source: file.contentType === "application/json" ? new TextDecoder().decode(file.source) : file.source
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return {
|
|
289
|
+
assets,
|
|
290
|
+
project: nextProject,
|
|
291
|
+
watchPaths: compiled.watchPaths
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
function getTileflowIconWatchPaths(project, cwd) {
|
|
295
|
+
return uniqueStrings(getLocalIconRequests(project, cwd).map((request) => request.sourceDir)).sort(
|
|
296
|
+
compareCodeUnits
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
function getLocalIconRequests(project, cwd) {
|
|
300
|
+
return getMapIconRequests(project, cwd).filter(
|
|
301
|
+
(request) => request.kind === "local"
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
function getMapIconRequests(project, cwd, mapNames) {
|
|
305
|
+
const selectedNames = (mapNames === void 0 ? Object.keys(project.maps) : [...new Set(mapNames)]).sort(compareCodeUnits);
|
|
306
|
+
return selectedNames.map((mapName) => {
|
|
307
|
+
const mapConfig = project.maps[mapName];
|
|
23
308
|
if (!mapConfig) {
|
|
309
|
+
throw new Error(`Unknown Tileflow map: ${mapName}`);
|
|
310
|
+
}
|
|
311
|
+
const iconSet = resolveIconSet(mapConfig.icons, project.icons);
|
|
312
|
+
const mapping = sortMapping(iconSet?.mapping);
|
|
313
|
+
if (iconSet?.source) {
|
|
314
|
+
return {
|
|
315
|
+
kind: "local",
|
|
316
|
+
label: resolvePackageLabel(mapConfig.icons, iconSet.source, project.icons, mapName),
|
|
317
|
+
mapName,
|
|
318
|
+
...mapping ? { mapping } : {},
|
|
319
|
+
source: iconSet.source,
|
|
320
|
+
sourceDir: resolve(cwd, iconSet.source)
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
return {
|
|
324
|
+
kind: iconSet?.sprite ? "external" : "none",
|
|
325
|
+
mapName,
|
|
326
|
+
...mapping ? { mapping } : {}
|
|
327
|
+
};
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function resolveIconSet(icons, iconSets, path = []) {
|
|
331
|
+
if (!icons) {
|
|
332
|
+
return void 0;
|
|
333
|
+
}
|
|
334
|
+
if (typeof icons === "string") {
|
|
335
|
+
const referenced = iconSets?.[icons];
|
|
336
|
+
if (referenced) {
|
|
337
|
+
if (path.includes(icons)) {
|
|
338
|
+
throw new Error(`Circular Tileflow icon set extends: ${[...path, icons].join(" -> ")}`);
|
|
339
|
+
}
|
|
340
|
+
return resolveIconSet(referenced, iconSets, [...path, icons]);
|
|
341
|
+
}
|
|
342
|
+
return isRemoteSpriteReference(icons) ? { sprite: icons } : { source: icons };
|
|
343
|
+
}
|
|
344
|
+
const extended = icons.extends ? resolveIconSet(icons.extends, iconSets, path) : void 0;
|
|
345
|
+
return {
|
|
346
|
+
...extended,
|
|
347
|
+
...icons,
|
|
348
|
+
mapping: {
|
|
349
|
+
...extended?.mapping,
|
|
350
|
+
...icons.mapping
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
async function resolveWorkingDirectory(cwd, issues) {
|
|
355
|
+
try {
|
|
356
|
+
const resolved = await realpath(cwd);
|
|
357
|
+
if (!(await stat(resolved)).isDirectory()) {
|
|
358
|
+
throw new Error("Working tree is not a directory");
|
|
359
|
+
}
|
|
360
|
+
return resolved;
|
|
361
|
+
} catch (error) {
|
|
362
|
+
issues.push({
|
|
363
|
+
message: describeFileSystemError(error, "Selected working tree was not found"),
|
|
364
|
+
path: "cwd"
|
|
365
|
+
});
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
function groupRequestsBySource(requests) {
|
|
370
|
+
const result = /* @__PURE__ */ new Map();
|
|
371
|
+
for (const request of requests) {
|
|
372
|
+
const existing = result.get(request.realSourceDir) ?? [];
|
|
373
|
+
existing.push(request);
|
|
374
|
+
result.set(request.realSourceDir, existing);
|
|
375
|
+
}
|
|
376
|
+
return result;
|
|
377
|
+
}
|
|
378
|
+
async function inspectIconSource(request, realSourceDir, realCwd, target, issues) {
|
|
379
|
+
let entries;
|
|
380
|
+
try {
|
|
381
|
+
entries = await readdir(realSourceDir, { withFileTypes: true });
|
|
382
|
+
} catch (error) {
|
|
383
|
+
issues.push({
|
|
384
|
+
message: describeFileSystemError(error, "Icon source could not be read"),
|
|
385
|
+
path: sourcePath(request.mapName)
|
|
386
|
+
});
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
entries.sort((left, right) => compareCodeUnits(left.name, right.name));
|
|
390
|
+
const candidates = [];
|
|
391
|
+
const names = /* @__PURE__ */ new Set();
|
|
392
|
+
let aggregateBytes = 0;
|
|
393
|
+
for (const entry of entries) {
|
|
394
|
+
const entryPath = resolve(realSourceDir, entry.name);
|
|
395
|
+
const path = iconPath(request.mapName, entry.name);
|
|
396
|
+
if (entry.isDirectory()) {
|
|
397
|
+
if (target === "hosted") {
|
|
398
|
+
issues.push({ message: "Nested directories are not supported", path });
|
|
399
|
+
}
|
|
24
400
|
continue;
|
|
25
401
|
}
|
|
26
|
-
|
|
27
|
-
|
|
402
|
+
let entryStat;
|
|
403
|
+
let realEntryPath = entryPath;
|
|
404
|
+
try {
|
|
405
|
+
if (entry.isSymbolicLink()) {
|
|
406
|
+
if (target === "local") {
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
realEntryPath = await realpath(entryPath);
|
|
410
|
+
if (!realCwd || !isPathInside(realCwd, realEntryPath)) {
|
|
411
|
+
issues.push({ message: "Icon symlink escapes the selected working tree", path });
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
entryStat = await stat(realEntryPath);
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (target === "hosted") {
|
|
418
|
+
issues.push({
|
|
419
|
+
message: describeFileSystemError(error, "Icon entry could not be read"),
|
|
420
|
+
path
|
|
421
|
+
});
|
|
422
|
+
}
|
|
28
423
|
continue;
|
|
29
424
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
425
|
+
if (!entryStat.isFile()) {
|
|
426
|
+
if (target === "hosted") {
|
|
427
|
+
issues.push({ message: "Icon entries must be regular files", path });
|
|
428
|
+
}
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
const extension = extname(entry.name).toLowerCase();
|
|
432
|
+
if (!iconFileExtensions.has(extension)) {
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
const name = entry.name.slice(0, -extname(entry.name).length);
|
|
436
|
+
if (names.has(name)) {
|
|
437
|
+
issues.push({
|
|
438
|
+
message: `Duplicate icon basename "${name}"`,
|
|
439
|
+
path
|
|
440
|
+
});
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
names.add(name);
|
|
444
|
+
if (target === "hosted" && !tileflowHostedIconIdPattern.test(name)) {
|
|
445
|
+
issues.push({
|
|
446
|
+
message: "Hosted icon IDs must match ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$",
|
|
447
|
+
path
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
if (entryStat.size > tileflowIconPackageLimits.maxSourceFileBytes) {
|
|
451
|
+
issues.push({
|
|
452
|
+
message: `Icon source exceeds ${tileflowIconPackageLimits.maxSourceFileBytes} bytes`,
|
|
453
|
+
path
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
aggregateBytes += entryStat.size;
|
|
457
|
+
candidates.push({
|
|
458
|
+
fileName: entry.name,
|
|
459
|
+
format: iconSourceFormat(extension),
|
|
460
|
+
name,
|
|
461
|
+
path: realEntryPath,
|
|
462
|
+
size: entryStat.size
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
candidates.sort((left, right) => compareCodeUnits(left.name, right.name));
|
|
466
|
+
if (candidates.length === 0) {
|
|
467
|
+
issues.push({
|
|
468
|
+
message: "No supported .svg, .png, .jpg, .jpeg, or .webp icon files were found",
|
|
469
|
+
path: sourcePath(request.mapName)
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
if (candidates.length > tileflowIconPackageLimits.maxIconCount) {
|
|
473
|
+
issues.push({
|
|
474
|
+
message: `Icon source contains more than ${tileflowIconPackageLimits.maxIconCount} icons`,
|
|
475
|
+
path: sourcePath(request.mapName)
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
if (aggregateBytes > tileflowIconPackageLimits.maxSourceBytes) {
|
|
479
|
+
issues.push({
|
|
480
|
+
message: `Icon source exceeds ${tileflowIconPackageLimits.maxSourceBytes} aggregate bytes`,
|
|
481
|
+
path: sourcePath(request.mapName)
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
if (issues.length > 0) {
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
const icons = [];
|
|
488
|
+
for (const candidate of candidates) {
|
|
489
|
+
const displayPath = iconPath(request.mapName, candidate.fileName);
|
|
490
|
+
try {
|
|
491
|
+
const source = await readFile(candidate.path);
|
|
492
|
+
if (source.byteLength !== candidate.size || source.byteLength > tileflowIconPackageLimits.maxSourceFileBytes) {
|
|
493
|
+
throw new Error("Icon changed while it was being validated");
|
|
494
|
+
}
|
|
495
|
+
if (target === "hosted" && extname(candidate.fileName).toLowerCase() === ".svg") {
|
|
496
|
+
validateHostedSvg(source, displayPath);
|
|
497
|
+
}
|
|
498
|
+
icons.push({
|
|
499
|
+
fileName: candidate.fileName,
|
|
500
|
+
format: candidate.format,
|
|
501
|
+
name: candidate.name,
|
|
502
|
+
path: candidate.path,
|
|
503
|
+
source
|
|
504
|
+
});
|
|
505
|
+
} catch (error) {
|
|
506
|
+
issues.push({
|
|
507
|
+
message: error instanceof Error ? error.message : "Icon could not be read",
|
|
508
|
+
path: displayPath
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (issues.length > 0) {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
return { icons, realSourceDir };
|
|
516
|
+
}
|
|
517
|
+
async function compileInspectedIconSource(inspected) {
|
|
518
|
+
const layoutOneX = createSpriteLayout(inspected.icons, 1);
|
|
519
|
+
const layoutTwoX = createSpriteLayout(inspected.icons, 2);
|
|
520
|
+
const rendered = await mapWithConcurrency(
|
|
521
|
+
inspected.icons,
|
|
522
|
+
tileflowIconPackageLimits.decodeConcurrency,
|
|
523
|
+
async (icon) => {
|
|
524
|
+
const dimensions = await validateDecodedDimensions(icon);
|
|
525
|
+
const oneX = await renderIcon(icon, 1);
|
|
526
|
+
const twoX = await renderIcon(icon, 2);
|
|
527
|
+
return {
|
|
528
|
+
dimensions,
|
|
529
|
+
input: icon,
|
|
530
|
+
oneX,
|
|
531
|
+
pixelSha256: {
|
|
532
|
+
oneX: await hashTileflowRenderedIconPixels({
|
|
533
|
+
height: oneX.height,
|
|
534
|
+
pixelRatio: 1,
|
|
535
|
+
rgba: oneX.rgba,
|
|
536
|
+
width: oneX.width
|
|
537
|
+
}),
|
|
538
|
+
twoX: await hashTileflowRenderedIconPixels({
|
|
539
|
+
height: twoX.height,
|
|
540
|
+
pixelRatio: 2,
|
|
541
|
+
rgba: twoX.rgba,
|
|
542
|
+
width: twoX.width
|
|
543
|
+
})
|
|
544
|
+
},
|
|
545
|
+
twoX
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
);
|
|
549
|
+
const [oneXImage, twoXImage] = await Promise.all([
|
|
550
|
+
createSpriteImage(
|
|
551
|
+
rendered.map((item) => item.oneX),
|
|
552
|
+
layoutOneX
|
|
553
|
+
),
|
|
554
|
+
createSpriteImage(
|
|
555
|
+
rendered.map((item) => item.twoX),
|
|
556
|
+
layoutTwoX
|
|
557
|
+
)
|
|
558
|
+
]);
|
|
559
|
+
const oneXJson = new TextEncoder().encode(`${serializeCanonicalJson(layoutOneX.index)}
|
|
560
|
+
`);
|
|
561
|
+
const twoXJson = new TextEncoder().encode(`${serializeCanonicalJson(layoutTwoX.index)}
|
|
562
|
+
`);
|
|
563
|
+
const files = [
|
|
564
|
+
{ contentType: "application/json", fileName: "sprite.json", source: oneXJson },
|
|
565
|
+
{ contentType: "image/png", fileName: "sprite.png", source: oneXImage },
|
|
566
|
+
{ contentType: "application/json", fileName: "sprite@2x.json", source: twoXJson },
|
|
567
|
+
{ contentType: "image/png", fileName: "sprite@2x.png", source: twoXImage }
|
|
568
|
+
];
|
|
569
|
+
assertGeneratedFileLimits(files);
|
|
570
|
+
const fileDigests = await Promise.all(files.map((file) => sha256Hex(file.source)));
|
|
571
|
+
const manifest = tileflowIconPackageManifestSchema.parse({
|
|
572
|
+
files: files.map((file, index) => ({
|
|
573
|
+
byteLength: file.source.byteLength,
|
|
574
|
+
contentType: file.contentType,
|
|
575
|
+
name: file.fileName,
|
|
576
|
+
sha256: fileDigests[index]
|
|
577
|
+
})),
|
|
578
|
+
format: "tileflow-icon-package-v1",
|
|
579
|
+
iconNames: inspected.icons.map((icon) => icon.name),
|
|
580
|
+
renderedIcons: inspected.icons.map((icon, index) => {
|
|
581
|
+
const pixels = rendered[index];
|
|
582
|
+
if (!pixels) {
|
|
583
|
+
throw new Error(`Missing rendered pixels for ${icon.name}`);
|
|
584
|
+
}
|
|
585
|
+
return { name: icon.name, pixelSha256: pixels.pixelSha256 };
|
|
586
|
+
}),
|
|
587
|
+
sprites: {
|
|
588
|
+
oneX: { height: layoutOneX.height, pixelRatio: 1, width: layoutOneX.width },
|
|
589
|
+
twoX: { height: layoutTwoX.height, pixelRatio: 2, width: layoutTwoX.width }
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
return {
|
|
593
|
+
icons: rendered,
|
|
594
|
+
layoutOneX,
|
|
595
|
+
layoutTwoX,
|
|
596
|
+
package: {
|
|
597
|
+
contentHash: await hashTileflowIconPackageManifest(manifest),
|
|
598
|
+
files,
|
|
599
|
+
manifest
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
function createSpriteLayout(icons, pixelRatio) {
|
|
604
|
+
const cellSize = iconSpriteSize * pixelRatio;
|
|
605
|
+
const columns = Math.ceil(Math.sqrt(icons.length));
|
|
606
|
+
const rows = Math.ceil(icons.length / columns);
|
|
607
|
+
const width = columns * cellSize;
|
|
608
|
+
const height = rows * cellSize;
|
|
609
|
+
if (width > tileflowIconPackageLimits.maxAtlasDimension || height > tileflowIconPackageLimits.maxAtlasDimension) {
|
|
610
|
+
throw new Error(
|
|
611
|
+
`Generated sprite exceeds ${tileflowIconPackageLimits.maxAtlasDimension} pixels per dimension`
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
const index = Object.fromEntries(
|
|
615
|
+
icons.map((icon, indexNumber) => {
|
|
616
|
+
const column = indexNumber % columns;
|
|
617
|
+
const row = Math.floor(indexNumber / columns);
|
|
618
|
+
return [
|
|
619
|
+
icon.name,
|
|
620
|
+
{
|
|
621
|
+
height: cellSize,
|
|
622
|
+
pixelRatio,
|
|
623
|
+
width: cellSize,
|
|
624
|
+
x: column * cellSize,
|
|
625
|
+
y: row * cellSize
|
|
626
|
+
}
|
|
627
|
+
];
|
|
628
|
+
})
|
|
629
|
+
);
|
|
630
|
+
return { cellSize, columns, height, index, width };
|
|
631
|
+
}
|
|
632
|
+
async function validateDecodedDimensions(icon) {
|
|
633
|
+
const sharp = await loadSharp();
|
|
634
|
+
const metadata = await sharp(icon.source, {
|
|
635
|
+
density: 72,
|
|
636
|
+
failOn: "error",
|
|
637
|
+
limitInputPixels: tileflowIconPackageLimits.maxDecodedPixelsPerIcon
|
|
638
|
+
}).metadata();
|
|
639
|
+
const width = metadata.width ?? 0;
|
|
640
|
+
const height = metadata.height ?? 0;
|
|
641
|
+
if (width <= 0 || height <= 0) {
|
|
642
|
+
throw new Error(`Unable to determine decoded dimensions for ${icon.fileName}`);
|
|
643
|
+
}
|
|
644
|
+
if (width * height > tileflowIconPackageLimits.maxDecodedPixelsPerIcon) {
|
|
645
|
+
throw new Error(
|
|
646
|
+
`${icon.fileName} exceeds ${tileflowIconPackageLimits.maxDecodedPixelsPerIcon} decoded pixels`
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
return { height, width };
|
|
650
|
+
}
|
|
651
|
+
async function renderIcon(icon, pixelRatio) {
|
|
652
|
+
const sharp = await loadSharp();
|
|
653
|
+
const cellSize = iconSpriteSize * pixelRatio;
|
|
654
|
+
const { data, info } = await sharp(icon.source, {
|
|
655
|
+
density: 72 * pixelRatio,
|
|
656
|
+
failOn: "error",
|
|
657
|
+
limitInputPixels: tileflowIconPackageLimits.maxDecodedPixelsPerIcon
|
|
658
|
+
}).resize(cellSize, cellSize, {
|
|
659
|
+
background: { alpha: 0, b: 0, g: 0, r: 0 },
|
|
660
|
+
fit: "contain"
|
|
661
|
+
}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
662
|
+
if (info.channels !== 4 || info.width !== cellSize || info.height !== cellSize) {
|
|
663
|
+
throw new Error(`Rendered icon ${icon.fileName} did not produce canonical RGBA pixels`);
|
|
664
|
+
}
|
|
665
|
+
const rgba = new Uint8Array(data);
|
|
666
|
+
const png = await sharp(data, {
|
|
667
|
+
raw: { channels: 4, height: info.height, width: info.width }
|
|
668
|
+
}).png({ adaptiveFiltering: false, compressionLevel: 9, palette: false }).toBuffer();
|
|
669
|
+
return { height: info.height, png, rgba, width: info.width };
|
|
670
|
+
}
|
|
671
|
+
async function createSpriteImage(icons, layout) {
|
|
672
|
+
const sharp = await loadSharp();
|
|
673
|
+
const atlas = new Uint8Array(layout.width * layout.height * 4);
|
|
674
|
+
for (const [indexNumber, icon] of icons.entries()) {
|
|
675
|
+
if (icon.width !== layout.cellSize || icon.height !== layout.cellSize) {
|
|
676
|
+
throw new Error("Rendered icon dimensions do not match the sprite layout");
|
|
677
|
+
}
|
|
678
|
+
const left = indexNumber % layout.columns * layout.cellSize;
|
|
679
|
+
const top = Math.floor(indexNumber / layout.columns) * layout.cellSize;
|
|
680
|
+
const rowBytes = icon.width * 4;
|
|
681
|
+
for (let row = 0; row < icon.height; row += 1) {
|
|
682
|
+
const sourceStart = row * rowBytes;
|
|
683
|
+
const targetStart = ((top + row) * layout.width + left) * 4;
|
|
684
|
+
atlas.set(icon.rgba.subarray(sourceStart, sourceStart + rowBytes), targetStart);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
return sharp(atlas, {
|
|
688
|
+
raw: {
|
|
689
|
+
channels: 4,
|
|
690
|
+
height: layout.height,
|
|
691
|
+
width: layout.width
|
|
692
|
+
}
|
|
693
|
+
}).png({ adaptiveFiltering: false, compressionLevel: 9, palette: false }).toBuffer();
|
|
694
|
+
}
|
|
695
|
+
function assertGeneratedFileLimits(files) {
|
|
696
|
+
let totalBytes = 0;
|
|
697
|
+
for (const file of files) {
|
|
698
|
+
if (file.source.byteLength > tileflowIconPackageLimits.maxGeneratedFileBytes) {
|
|
699
|
+
throw new Error(
|
|
700
|
+
`${file.fileName} exceeds ${tileflowIconPackageLimits.maxGeneratedFileBytes} generated bytes`
|
|
701
|
+
);
|
|
702
|
+
}
|
|
703
|
+
totalBytes += file.source.byteLength;
|
|
704
|
+
}
|
|
705
|
+
if (totalBytes > tileflowIconPackageLimits.maxGeneratedPackageBytes) {
|
|
706
|
+
throw new Error(
|
|
707
|
+
`Generated package exceeds ${tileflowIconPackageLimits.maxGeneratedPackageBytes} bytes`
|
|
708
|
+
);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
function validateHostedSvg(source, displayPath) {
|
|
712
|
+
const parser = new SaxesParser({ fileName: displayPath, xmlns: true });
|
|
713
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
714
|
+
let styleDepth = 0;
|
|
715
|
+
let styleText = "";
|
|
716
|
+
parser.on("doctype", () => {
|
|
717
|
+
throw new Error("Hosted SVGs cannot contain a document type or entity declarations");
|
|
718
|
+
});
|
|
719
|
+
parser.on("processinginstruction", (instruction) => {
|
|
720
|
+
if (instruction.target.toLowerCase() === "xml-stylesheet") {
|
|
721
|
+
throw new Error("Hosted SVGs cannot load external stylesheets");
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
parser.on("opentag", (tag) => {
|
|
725
|
+
const localName = tag.local.toLowerCase();
|
|
726
|
+
if (localName === "script") {
|
|
727
|
+
throw new Error("Hosted SVGs cannot contain scripts");
|
|
728
|
+
}
|
|
729
|
+
if (localName === "style") {
|
|
730
|
+
styleDepth += 1;
|
|
731
|
+
}
|
|
732
|
+
for (const attribute of Object.values(tag.attributes)) {
|
|
733
|
+
const attributeName = attribute.local.toLowerCase();
|
|
734
|
+
const value = attribute.value.trim();
|
|
735
|
+
if (attributeName.startsWith("on")) {
|
|
736
|
+
throw new Error("Hosted SVGs cannot contain script event handlers");
|
|
737
|
+
}
|
|
738
|
+
if (attributeName === "href" && value.length > 0 && !value.startsWith("#")) {
|
|
739
|
+
throw new Error("Hosted SVG resource references must use local fragments");
|
|
740
|
+
}
|
|
741
|
+
if (containsExternalCssUrl(value)) {
|
|
742
|
+
throw new Error("Hosted SVG resource references must use local fragments");
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
});
|
|
746
|
+
parser.on("text", (text) => {
|
|
747
|
+
if (styleDepth > 0) {
|
|
748
|
+
styleText += text;
|
|
749
|
+
}
|
|
750
|
+
});
|
|
751
|
+
parser.on("cdata", (text) => {
|
|
752
|
+
if (styleDepth > 0) {
|
|
753
|
+
styleText += text;
|
|
754
|
+
}
|
|
755
|
+
});
|
|
756
|
+
parser.on("closetag", (tag) => {
|
|
757
|
+
if (tag.local.toLowerCase() !== "style") {
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
styleDepth -= 1;
|
|
761
|
+
if (styleDepth === 0) {
|
|
762
|
+
if (styleText.toLowerCase().includes("@import") || containsExternalCssUrl(styleText)) {
|
|
763
|
+
throw new Error("Hosted SVGs cannot load external stylesheets or resources");
|
|
764
|
+
}
|
|
765
|
+
styleText = "";
|
|
766
|
+
}
|
|
767
|
+
});
|
|
768
|
+
parser.on("error", (error) => {
|
|
769
|
+
throw error;
|
|
770
|
+
});
|
|
771
|
+
const chunkBytes = 64 * 1024;
|
|
772
|
+
for (let offset = 0; offset < source.byteLength; offset += chunkBytes) {
|
|
773
|
+
parser.write(decoder.decode(source.subarray(offset, offset + chunkBytes), { stream: true }));
|
|
774
|
+
}
|
|
775
|
+
parser.write(decoder.decode());
|
|
776
|
+
parser.close();
|
|
777
|
+
}
|
|
778
|
+
function containsExternalCssUrl(value) {
|
|
779
|
+
const lowerValue = value.toLowerCase();
|
|
780
|
+
let cursor = 0;
|
|
781
|
+
while (cursor < value.length) {
|
|
782
|
+
const start = lowerValue.indexOf("url(", cursor);
|
|
783
|
+
if (start === -1) {
|
|
784
|
+
return false;
|
|
785
|
+
}
|
|
786
|
+
const end = value.indexOf(")", start + 4);
|
|
787
|
+
if (end === -1) {
|
|
788
|
+
return true;
|
|
789
|
+
}
|
|
790
|
+
const rawTarget = value.slice(start + 4, end).trim();
|
|
791
|
+
const target = stripMatchingQuotes(rawTarget);
|
|
792
|
+
if (!target.startsWith("#")) {
|
|
793
|
+
return true;
|
|
794
|
+
}
|
|
795
|
+
cursor = end + 1;
|
|
796
|
+
}
|
|
797
|
+
return false;
|
|
798
|
+
}
|
|
799
|
+
function stripMatchingQuotes(value) {
|
|
800
|
+
if (value.length < 2) {
|
|
801
|
+
return value;
|
|
802
|
+
}
|
|
803
|
+
const first = value[0];
|
|
804
|
+
const last = value[value.length - 1];
|
|
805
|
+
return first === '"' && last === '"' || first === "'" && last === "'" ? value.slice(1, -1).trim() : value;
|
|
806
|
+
}
|
|
807
|
+
async function mapWithConcurrency(values, concurrency, map) {
|
|
808
|
+
const results = new Array(values.length);
|
|
809
|
+
let nextIndex = 0;
|
|
810
|
+
async function worker() {
|
|
811
|
+
while (nextIndex < values.length) {
|
|
812
|
+
const index = nextIndex;
|
|
813
|
+
nextIndex += 1;
|
|
814
|
+
const value = values[index];
|
|
815
|
+
if (value !== void 0) {
|
|
816
|
+
results[index] = await map(value, index);
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
await Promise.all(
|
|
821
|
+
Array.from({ length: Math.min(concurrency, values.length) }, async () => worker())
|
|
822
|
+
);
|
|
823
|
+
return results;
|
|
824
|
+
}
|
|
825
|
+
async function loadSharp() {
|
|
826
|
+
try {
|
|
827
|
+
return (await import("sharp")).default;
|
|
828
|
+
} catch (error) {
|
|
829
|
+
throw new Error(
|
|
830
|
+
'Local icon sprites require the optional "sharp" package. Install sharp or disable local icons.',
|
|
831
|
+
{ cause: error }
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
function resolvePackageLabel(icons, source, iconSets, mapName) {
|
|
836
|
+
let candidate;
|
|
837
|
+
if (typeof icons === "string" && iconSets?.[icons]) {
|
|
838
|
+
candidate = icons;
|
|
839
|
+
} else if (icons && typeof icons === "object" && icons.extends && iconSets?.[icons.extends]) {
|
|
840
|
+
candidate = icons.extends;
|
|
841
|
+
}
|
|
842
|
+
candidate ??= basename(source.replace(/[\\/]+$/u, "")) || mapName || "Icons";
|
|
843
|
+
const printable = Array.from(candidate.normalize("NFC")).map((character) => {
|
|
844
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
845
|
+
return codePoint < 32 || codePoint >= 127 && codePoint <= 159 ? "" : character;
|
|
846
|
+
}).join("").trim();
|
|
847
|
+
const bounded = Array.from(printable || "Icons").slice(0, 64).join("");
|
|
848
|
+
return tileflowIconPackageLabelSchema.parse(bounded);
|
|
849
|
+
}
|
|
850
|
+
function sortMapping(mapping) {
|
|
851
|
+
if (!mapping) {
|
|
852
|
+
return void 0;
|
|
853
|
+
}
|
|
854
|
+
return Object.fromEntries(
|
|
855
|
+
Object.entries(mapping).sort(([left], [right]) => compareCodeUnits(left, right))
|
|
856
|
+
);
|
|
857
|
+
}
|
|
858
|
+
function createCatalogMappings(mapping, targetStatus) {
|
|
859
|
+
return Object.entries(mapping ?? {}).sort(([left], [right]) => compareCodeUnits(left, right)).map(([semantic, iconId]) => ({
|
|
860
|
+
iconId,
|
|
861
|
+
semantic,
|
|
862
|
+
targetStatus: typeof targetStatus === "function" ? targetStatus(iconId) : targetStatus
|
|
863
|
+
}));
|
|
864
|
+
}
|
|
865
|
+
function compareMappedFrom(left, right) {
|
|
866
|
+
return compareCodeUnits(left.map, right.map) || compareCodeUnits(left.semantic, right.semantic);
|
|
867
|
+
}
|
|
868
|
+
function atlasRectangle(entry) {
|
|
869
|
+
return { height: entry.height, width: entry.width, x: entry.x, y: entry.y };
|
|
870
|
+
}
|
|
871
|
+
function relativePortablePath(root, candidate) {
|
|
872
|
+
const pathFromRoot = relative(root, candidate);
|
|
873
|
+
if (pathFromRoot === "") {
|
|
874
|
+
return ".";
|
|
875
|
+
}
|
|
876
|
+
if (isAbsolute(pathFromRoot)) {
|
|
877
|
+
throw new Error("Icon catalog path cannot be represented relative to the working tree");
|
|
878
|
+
}
|
|
879
|
+
return pathFromRoot.split(sep).join("/");
|
|
880
|
+
}
|
|
881
|
+
function iconSourceFormat(extension) {
|
|
882
|
+
switch (extension) {
|
|
883
|
+
case ".svg":
|
|
884
|
+
return "svg";
|
|
885
|
+
case ".png":
|
|
886
|
+
return "png";
|
|
887
|
+
case ".jpg":
|
|
888
|
+
case ".jpeg":
|
|
889
|
+
return "jpeg";
|
|
890
|
+
case ".webp":
|
|
891
|
+
return "webp";
|
|
892
|
+
default:
|
|
893
|
+
throw new Error(`Unsupported icon source format: ${extension}`);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
function sourcePath(mapName) {
|
|
897
|
+
return `maps.${mapName}.icons.source`;
|
|
898
|
+
}
|
|
899
|
+
function iconPath(mapName, fileName) {
|
|
900
|
+
return `${sourcePath(mapName)}/${fileName}`;
|
|
901
|
+
}
|
|
902
|
+
function isPathInside(root, candidate) {
|
|
903
|
+
const pathFromRoot = relative(root, candidate);
|
|
904
|
+
return pathFromRoot === "" || !isAbsolute(pathFromRoot) && pathFromRoot !== ".." && !pathFromRoot.startsWith(`..${sep}`);
|
|
905
|
+
}
|
|
906
|
+
function describeFileSystemError(error, fallback) {
|
|
907
|
+
if (error && typeof error === "object" && "code" in error) {
|
|
908
|
+
const code = String(error.code ?? "");
|
|
909
|
+
if (code === "ENOENT") {
|
|
910
|
+
return fallback;
|
|
911
|
+
}
|
|
912
|
+
if (code === "EACCES" || code === "EPERM") {
|
|
913
|
+
return "Icon source is not readable";
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
return error instanceof Error && error.message ? error.message : fallback;
|
|
917
|
+
}
|
|
918
|
+
function cloneProject(project) {
|
|
919
|
+
return JSON.parse(JSON.stringify(project));
|
|
920
|
+
}
|
|
921
|
+
function isRemoteSpriteReference(value) {
|
|
922
|
+
return value.startsWith("http://") || value.startsWith("https://") || value.startsWith("/") || value.startsWith("data:");
|
|
923
|
+
}
|
|
924
|
+
function joinUrl(base, path) {
|
|
925
|
+
const trimmedBase = base.replace(/\/+$/g, "");
|
|
926
|
+
const trimmedPath = path.replace(/^\/+/g, "");
|
|
927
|
+
return trimmedBase ? `${trimmedBase}/${trimmedPath}` : trimmedPath;
|
|
928
|
+
}
|
|
929
|
+
function uniqueStrings(values) {
|
|
930
|
+
return [...new Set(values)];
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// src/session.ts
|
|
934
|
+
import { watch } from "chokidar";
|
|
935
|
+
import { realpathSync } from "fs";
|
|
936
|
+
import { dirname, extname as extname2, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2, sep as sep2, win32 } from "path";
|
|
937
|
+
|
|
938
|
+
// src/diagnostic-sanitization.ts
|
|
939
|
+
function sanitizeDiagnosticSecrets(value) {
|
|
940
|
+
return value.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[redacted]@").replace(/\bBearer\s+[^\s,;]+/gi, "Bearer [redacted]").replace(/\btf_(?:live|cli|test)_[A-Za-z0-9_-]{8,}\b/gi, "tf_[redacted]").replace(/\b(?:sk_(?:live|test)|rk_(?:live|test)|whsec)_[A-Za-z0-9_-]+\b/g, "[redacted]").replace(
|
|
941
|
+
/([?&](?:access_token|api_key|key|password|secret|signature|token)=)[^&#\s]+/gi,
|
|
942
|
+
"$1[redacted]"
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// src/session.ts
|
|
947
|
+
var tileflowArtifactSessionSchemaVersion = 1;
|
|
948
|
+
var configExtensions = /* @__PURE__ */ new Set([".cjs", ".cts", ".js", ".json", ".mjs", ".mts", ".ts", ".tsx"]);
|
|
949
|
+
var iconExtensions = /* @__PURE__ */ new Set([".jpeg", ".jpg", ".png", ".svg", ".webp"]);
|
|
950
|
+
var excludedDirectories = /* @__PURE__ */ new Set([
|
|
951
|
+
".cache",
|
|
952
|
+
".git",
|
|
953
|
+
".hg",
|
|
954
|
+
".next",
|
|
955
|
+
".nuxt",
|
|
956
|
+
".svn",
|
|
957
|
+
".svelte-kit",
|
|
958
|
+
".tileflow",
|
|
959
|
+
".turbo",
|
|
960
|
+
"build",
|
|
961
|
+
"coverage",
|
|
962
|
+
"dist",
|
|
963
|
+
"node_modules"
|
|
964
|
+
]);
|
|
965
|
+
async function createTileflowArtifactSessionWithBuilder(options, buildArtifacts) {
|
|
966
|
+
const session = new TileflowArtifactSessionImpl(options, buildArtifacts);
|
|
967
|
+
await session.start();
|
|
968
|
+
return session;
|
|
969
|
+
}
|
|
970
|
+
var TileflowArtifactSessionImpl = class {
|
|
971
|
+
#buildArtifacts;
|
|
972
|
+
#buildOptions;
|
|
973
|
+
#configPath;
|
|
974
|
+
#cwd;
|
|
975
|
+
#debounceMs;
|
|
976
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
977
|
+
#ignoredPaths;
|
|
978
|
+
#watchEnabled;
|
|
979
|
+
#closed = false;
|
|
980
|
+
#debounceTimer;
|
|
981
|
+
#generation = 0;
|
|
982
|
+
#lastGoodArtifacts;
|
|
983
|
+
#lastGoodGeneration;
|
|
984
|
+
#refreshToken = 0;
|
|
985
|
+
#state = { generation: 0, status: "building" };
|
|
986
|
+
#watcher;
|
|
987
|
+
#watchedArtifactPaths = /* @__PURE__ */ new Set();
|
|
988
|
+
constructor(options, buildArtifacts) {
|
|
989
|
+
this.#cwd = resolve2(options.cwd ?? process.cwd());
|
|
990
|
+
this.#configPath = resolve2(this.#cwd, options.config ?? "tileflow.config.ts");
|
|
991
|
+
this.#debounceMs = Math.max(0, Math.min(options.debounceMs ?? 75, 1e3));
|
|
992
|
+
this.#watchEnabled = options.watch ?? false;
|
|
993
|
+
this.#ignoredPaths = (options.ignoredPaths ?? []).map((path) => resolve2(this.#cwd, path));
|
|
994
|
+
this.#buildArtifacts = buildArtifacts;
|
|
995
|
+
this.#buildOptions = {
|
|
996
|
+
assetBaseUrl: options.assetBaseUrl,
|
|
997
|
+
config: options.config,
|
|
998
|
+
cwd: this.#cwd,
|
|
999
|
+
styleBaseUrl: options.styleBaseUrl,
|
|
1000
|
+
tileBaseUrl: options.tileBaseUrl
|
|
34
1001
|
};
|
|
35
1002
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
1003
|
+
async start() {
|
|
1004
|
+
if (this.#watchEnabled) {
|
|
1005
|
+
this.#watcher = watch(dirname(this.#configPath), {
|
|
1006
|
+
awaitWriteFinish: { pollInterval: 20, stabilityThreshold: 50 },
|
|
1007
|
+
followSymlinks: false,
|
|
1008
|
+
ignoreInitial: true,
|
|
1009
|
+
ignored: (path, stats) => this.#ignoreWatchPath(path, stats?.isDirectory())
|
|
1010
|
+
});
|
|
1011
|
+
const watcherReady = new Promise((resolveReady, rejectReady) => {
|
|
1012
|
+
const watcher = this.#watcher;
|
|
1013
|
+
const cleanup = () => {
|
|
1014
|
+
watcher.off("ready", onReady);
|
|
1015
|
+
watcher.off("error", onError);
|
|
1016
|
+
};
|
|
1017
|
+
const onReady = () => {
|
|
1018
|
+
cleanup();
|
|
1019
|
+
resolveReady();
|
|
1020
|
+
};
|
|
1021
|
+
const onError = (error) => {
|
|
1022
|
+
cleanup();
|
|
1023
|
+
rejectReady(error);
|
|
1024
|
+
};
|
|
1025
|
+
watcher.once("ready", onReady);
|
|
1026
|
+
watcher.once("error", onError);
|
|
1027
|
+
});
|
|
1028
|
+
this.#watcher.on("all", (event, path) => {
|
|
1029
|
+
if (event === "addDir" || event === "unlinkDir") return;
|
|
1030
|
+
if (!this.#shouldRefreshForWatchEvent(path)) return;
|
|
1031
|
+
this.#scheduleRefresh(path);
|
|
1032
|
+
});
|
|
1033
|
+
this.#watcher.on("error", (error) => {
|
|
1034
|
+
if (this.#closed) return;
|
|
1035
|
+
this.#refreshToken += 1;
|
|
1036
|
+
this.#publishInvalid(this.#generation + 1, error);
|
|
1037
|
+
});
|
|
1038
|
+
await watcherReady;
|
|
1039
|
+
}
|
|
1040
|
+
await this.refresh("initial");
|
|
1041
|
+
}
|
|
1042
|
+
getState() {
|
|
1043
|
+
return this.#state;
|
|
1044
|
+
}
|
|
1045
|
+
getLastGoodArtifacts() {
|
|
1046
|
+
return this.#lastGoodArtifacts;
|
|
1047
|
+
}
|
|
1048
|
+
subscribe(listener) {
|
|
1049
|
+
if (this.#closed) return () => void 0;
|
|
1050
|
+
this.#listeners.add(listener);
|
|
1051
|
+
return () => this.#listeners.delete(listener);
|
|
1052
|
+
}
|
|
1053
|
+
async refresh(_reason = "manual") {
|
|
1054
|
+
if (this.#closed) return;
|
|
1055
|
+
const generation = ++this.#generation;
|
|
1056
|
+
const token = ++this.#refreshToken;
|
|
1057
|
+
this.#publish({
|
|
1058
|
+
generation,
|
|
1059
|
+
status: "building",
|
|
1060
|
+
...this.#lastGoodGeneration === void 0 ? {} : { lastGoodGeneration: this.#lastGoodGeneration }
|
|
1061
|
+
});
|
|
1062
|
+
try {
|
|
1063
|
+
const artifacts = await this.#buildArtifacts(this.#buildOptions);
|
|
1064
|
+
if (this.#closed || token !== this.#refreshToken) return;
|
|
1065
|
+
this.#lastGoodArtifacts = artifacts;
|
|
1066
|
+
this.#lastGoodGeneration = generation;
|
|
1067
|
+
this.#updateArtifactWatchPaths(artifacts.watchPaths);
|
|
1068
|
+
this.#publish({
|
|
1069
|
+
artifacts,
|
|
1070
|
+
generation,
|
|
1071
|
+
lastGoodGeneration: generation,
|
|
1072
|
+
status: "ready"
|
|
1073
|
+
});
|
|
1074
|
+
} catch (error) {
|
|
1075
|
+
if (this.#closed || token !== this.#refreshToken) return;
|
|
1076
|
+
this.#publishInvalid(generation, error);
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
async close() {
|
|
1080
|
+
if (this.#closed) return;
|
|
1081
|
+
this.#closed = true;
|
|
1082
|
+
this.#refreshToken += 1;
|
|
1083
|
+
if (this.#debounceTimer) clearTimeout(this.#debounceTimer);
|
|
1084
|
+
this.#listeners.clear();
|
|
1085
|
+
await this.#watcher?.close();
|
|
1086
|
+
}
|
|
1087
|
+
#ignoreWatchPath(path, isDirectory) {
|
|
1088
|
+
const resolvedPath = resolve2(path);
|
|
1089
|
+
const relativePath = relative2(dirname(this.#configPath), resolvedPath);
|
|
1090
|
+
const segments = relativePath.split(sep2).filter(Boolean);
|
|
1091
|
+
if (this.#ignoredPaths.some((path2) => isSameOrInside(path2, resolvedPath))) return true;
|
|
1092
|
+
if (segments.some((segment) => excludedDirectories.has(segment))) return true;
|
|
1093
|
+
if (isDirectory !== false) return false;
|
|
1094
|
+
if (resolvedPath === this.#configPath || this.#watchedArtifactPaths.has(resolvedPath))
|
|
1095
|
+
return false;
|
|
1096
|
+
const extension = extname2(resolvedPath).toLowerCase();
|
|
1097
|
+
if (configExtensions.has(extension)) return false;
|
|
1098
|
+
if (iconExtensions.has(extension)) return false;
|
|
1099
|
+
return true;
|
|
1100
|
+
}
|
|
1101
|
+
#shouldRefreshForWatchEvent(path) {
|
|
1102
|
+
const resolvedPath = resolve2(path);
|
|
1103
|
+
if (!iconExtensions.has(extname2(resolvedPath).toLowerCase())) return true;
|
|
1104
|
+
return [...this.#watchedArtifactPaths].some((path2) => isSameOrInside(path2, resolvedPath));
|
|
1105
|
+
}
|
|
1106
|
+
#publish(state) {
|
|
1107
|
+
this.#state = state;
|
|
1108
|
+
for (const listener of this.#listeners) listener(state);
|
|
1109
|
+
}
|
|
1110
|
+
#publishInvalid(generation, error) {
|
|
1111
|
+
this.#generation = Math.max(this.#generation, generation);
|
|
1112
|
+
this.#publish({
|
|
1113
|
+
diagnostics: createTileflowArtifactDiagnostics(error, this.#cwd),
|
|
1114
|
+
generation,
|
|
1115
|
+
status: "invalid",
|
|
1116
|
+
...this.#lastGoodGeneration === void 0 ? {} : { lastGoodGeneration: this.#lastGoodGeneration }
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
#scheduleRefresh(_path) {
|
|
1120
|
+
if (this.#closed) return;
|
|
1121
|
+
if (this.#debounceTimer) clearTimeout(this.#debounceTimer);
|
|
1122
|
+
this.#debounceTimer = setTimeout(() => {
|
|
1123
|
+
this.#debounceTimer = void 0;
|
|
1124
|
+
void this.refresh("filesystem");
|
|
1125
|
+
}, this.#debounceMs);
|
|
1126
|
+
}
|
|
1127
|
+
#updateArtifactWatchPaths(paths) {
|
|
1128
|
+
if (!this.#watcher) return;
|
|
1129
|
+
const next = new Set(paths.map((path) => resolve2(this.#cwd, path)));
|
|
1130
|
+
const previous = this.#watchedArtifactPaths;
|
|
1131
|
+
this.#watchedArtifactPaths = next;
|
|
1132
|
+
for (const path of previous) {
|
|
1133
|
+
if (!next.has(path) && !isSameOrInside(dirname(this.#configPath), path)) {
|
|
1134
|
+
void this.#watcher.unwatch(path);
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
for (const path of next) {
|
|
1138
|
+
if (!previous.has(path) && !isSameOrInside(dirname(this.#configPath), path)) {
|
|
1139
|
+
this.#watcher.add(path);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
function isSameOrInside(root, candidate) {
|
|
1145
|
+
const path = relative2(resolve2(root), resolve2(candidate));
|
|
1146
|
+
return path === "" || !isAbsolute2(path) && path !== ".." && !path.startsWith(`..${sep2}`);
|
|
1147
|
+
}
|
|
1148
|
+
function createTileflowArtifactDiagnostics(error, cwd) {
|
|
1149
|
+
const inheritedCode = optionalDiagnosticField(error, "code");
|
|
1150
|
+
const inheritedPhase = optionalDiagnosticField(error, "phase") ?? optionalNestedDiagnosticField(error, "phase");
|
|
1151
|
+
const issueList = getIssueList(error);
|
|
1152
|
+
if (issueList.length > 0) {
|
|
1153
|
+
return normalizeDiagnostics(
|
|
1154
|
+
issueList.map((issue) => ({
|
|
1155
|
+
...issue.code ?? inheritedCode ? { code: issue.code ?? inheritedCode } : {},
|
|
1156
|
+
message: sanitizeMessage(issue.message, cwd),
|
|
1157
|
+
path: sanitizePath(issue.path, cwd),
|
|
1158
|
+
...issue.phase ?? inheritedPhase ? { phase: issue.phase ?? inheritedPhase } : {}
|
|
1159
|
+
}))
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
return normalizeDiagnostics([
|
|
1163
|
+
{
|
|
1164
|
+
...inheritedCode ? { code: inheritedCode } : {},
|
|
1165
|
+
message: sanitizeMessage(error instanceof Error ? error.message : "Unknown build error", cwd),
|
|
1166
|
+
path: "",
|
|
1167
|
+
...inheritedPhase ? { phase: inheritedPhase } : {}
|
|
1168
|
+
}
|
|
1169
|
+
]);
|
|
1170
|
+
}
|
|
1171
|
+
function getIssueList(error) {
|
|
1172
|
+
if (!error || typeof error !== "object") return [];
|
|
1173
|
+
const containers = [];
|
|
1174
|
+
for (const key of ["messages", "issues"]) {
|
|
1175
|
+
const value = error[key];
|
|
1176
|
+
if (Array.isArray(value)) containers.push(value);
|
|
1177
|
+
}
|
|
1178
|
+
const details = error.details;
|
|
1179
|
+
if (details && typeof details === "object") {
|
|
1180
|
+
const diagnostics = details.diagnostics;
|
|
1181
|
+
if (Array.isArray(diagnostics)) containers.push(diagnostics);
|
|
1182
|
+
}
|
|
1183
|
+
return containers.flatMap(
|
|
1184
|
+
(value) => value.flatMap((entry) => {
|
|
1185
|
+
if (!entry || typeof entry !== "object") return [];
|
|
1186
|
+
const message = entry.message;
|
|
1187
|
+
const path = entry.path;
|
|
1188
|
+
const code = optionalDiagnosticField(entry, "code");
|
|
1189
|
+
const phase = optionalDiagnosticField(entry, "phase");
|
|
1190
|
+
return typeof message === "string" ? [
|
|
1191
|
+
{
|
|
1192
|
+
...code ? { code } : {},
|
|
1193
|
+
message,
|
|
1194
|
+
path: typeof path === "string" ? path : "",
|
|
1195
|
+
...phase ? { phase } : {}
|
|
1196
|
+
}
|
|
1197
|
+
] : [];
|
|
1198
|
+
})
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
function sanitizeMessage(value, cwd) {
|
|
1202
|
+
let sanitized = value;
|
|
1203
|
+
for (const root of localPathAliases(cwd)) sanitized = sanitized.replaceAll(root, ".");
|
|
1204
|
+
sanitized = sanitized.replace(/[\r\n]+/g, " ").trim();
|
|
1205
|
+
sanitized = sanitized.replace(/https?:\/\/[^\s'")<>]+/gi, (url) => {
|
|
1206
|
+
try {
|
|
1207
|
+
return new URL(url.replace(/[),.;]+$/, "")).origin;
|
|
1208
|
+
} catch {
|
|
1209
|
+
return "(resource URL)";
|
|
1210
|
+
}
|
|
1211
|
+
});
|
|
1212
|
+
sanitized = sanitized.replace(/(^|[\s'"(])[A-Za-z]:[\\/][^\s'")]+/g, "$1(external path)");
|
|
1213
|
+
sanitized = sanitized.replace(/(^|[\s'"(])(?:\\\\|\/\/)[^\s'")]+/g, "$1(external path)");
|
|
1214
|
+
sanitized = sanitized.replace(/(^|[\s'"(])\/[^\s'")]+/g, "$1(external path)");
|
|
1215
|
+
return sanitizeDiagnosticSecrets(sanitized);
|
|
1216
|
+
}
|
|
1217
|
+
function sanitizePath(value, cwd) {
|
|
1218
|
+
if (!value) return "";
|
|
1219
|
+
if (win32.isAbsolute(value) && !isAbsolute2(value)) return "(external)";
|
|
1220
|
+
if (!isAbsolute2(value)) return value.replaceAll("\\", "/");
|
|
1221
|
+
const local = relative2(canonicalPath(cwd), canonicalPath(value)).replaceAll(sep2, "/");
|
|
1222
|
+
return local.startsWith("../") || local === ".." ? "(external)" : local || ".";
|
|
1223
|
+
}
|
|
1224
|
+
function localPathAliases(path) {
|
|
1225
|
+
return [.../* @__PURE__ */ new Set([resolve2(path), canonicalPath(path)])].sort(
|
|
1226
|
+
(left, right) => right.length - left.length
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
function canonicalPath(path) {
|
|
1230
|
+
try {
|
|
1231
|
+
return realpathSync.native(resolve2(path));
|
|
1232
|
+
} catch {
|
|
1233
|
+
return resolve2(path);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
function normalizeDiagnostics(diagnostics) {
|
|
1237
|
+
const bounded = diagnostics.map((diagnostic) => ({
|
|
1238
|
+
...diagnostic.code ? { code: boundDiagnosticField(diagnostic.code) } : {},
|
|
1239
|
+
message: boundDiagnosticText(diagnostic.message, 300),
|
|
1240
|
+
path: boundDiagnosticText(diagnostic.path, 300),
|
|
1241
|
+
...diagnostic.phase ? { phase: boundDiagnosticField(diagnostic.phase) } : {}
|
|
1242
|
+
}));
|
|
1243
|
+
bounded.sort((left, right) => {
|
|
1244
|
+
const leftKey = `${left.path}\0${left.message}\0${left.code ?? ""}\0${left.phase ?? ""}`;
|
|
1245
|
+
const rightKey = `${right.path}\0${right.message}\0${right.code ?? ""}\0${right.phase ?? ""}`;
|
|
1246
|
+
return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
|
|
1247
|
+
});
|
|
1248
|
+
return bounded.filter(
|
|
1249
|
+
(diagnostic, index) => index === 0 || JSON.stringify(diagnostic) !== JSON.stringify(bounded[index - 1])
|
|
1250
|
+
).slice(0, 32);
|
|
1251
|
+
}
|
|
1252
|
+
function optionalDiagnosticField(value, key) {
|
|
1253
|
+
if (!value || typeof value !== "object") return void 0;
|
|
1254
|
+
const field = value[key];
|
|
1255
|
+
return typeof field === "string" && field.trim() ? boundDiagnosticField(field) : void 0;
|
|
1256
|
+
}
|
|
1257
|
+
function optionalNestedDiagnosticField(value, key) {
|
|
1258
|
+
if (!value || typeof value !== "object") return void 0;
|
|
1259
|
+
return optionalDiagnosticField(value.details, key);
|
|
1260
|
+
}
|
|
1261
|
+
function boundDiagnosticField(value) {
|
|
1262
|
+
return boundDiagnosticText(value.replace(/[^A-Za-z0-9_-]/g, ""), 64);
|
|
1263
|
+
}
|
|
1264
|
+
function boundDiagnosticText(value, limit) {
|
|
1265
|
+
return value.length <= limit ? value : `${value.slice(0, limit - 1)}\u2026`;
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// src/style-validation.ts
|
|
1269
|
+
import { validateStyleMin } from "@maplibre/maplibre-gl-style-spec";
|
|
1270
|
+
var TileflowStyleValidationError = class extends Error {
|
|
1271
|
+
code = "STYLE_INVALID";
|
|
1272
|
+
issues;
|
|
1273
|
+
phase = "style-validation";
|
|
1274
|
+
constructor(issues) {
|
|
1275
|
+
super("Compiled Tileflow styles are not valid MapLibre styles.");
|
|
1276
|
+
this.name = "TileflowStyleValidationError";
|
|
1277
|
+
this.issues = normalizeIssues(issues);
|
|
42
1278
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
1279
|
+
};
|
|
1280
|
+
var maxIssues = 32;
|
|
1281
|
+
var maxMessageLength = 300;
|
|
1282
|
+
var maxPathLength = 300;
|
|
1283
|
+
function assertValidTileflowStyle(style, map) {
|
|
1284
|
+
const issues = validateTileflowStyle(style, map);
|
|
1285
|
+
if (issues.length > 0) throw new TileflowStyleValidationError(issues);
|
|
1286
|
+
}
|
|
1287
|
+
function validateTileflowStyle(style, map) {
|
|
1288
|
+
const jsonIssues = [];
|
|
1289
|
+
collectJsonIssues(
|
|
1290
|
+
style,
|
|
1291
|
+
`maps.${sanitizePathSegment(map)}.style`,
|
|
1292
|
+
map,
|
|
1293
|
+
jsonIssues,
|
|
1294
|
+
/* @__PURE__ */ new Set()
|
|
1295
|
+
);
|
|
1296
|
+
if (jsonIssues.length > 0) return normalizeIssues(jsonIssues);
|
|
1297
|
+
const semanticIssues = validateStyleMin(style).map(
|
|
1298
|
+
(issue) => createSemanticIssue(style, map, issue.message)
|
|
1299
|
+
);
|
|
1300
|
+
return normalizeIssues(semanticIssues);
|
|
1301
|
+
}
|
|
1302
|
+
function normalizeTileflowStyleValidationIssues(issues) {
|
|
1303
|
+
return normalizeIssues(issues);
|
|
1304
|
+
}
|
|
1305
|
+
function createSemanticIssue(style, map, rawMessage) {
|
|
1306
|
+
const normalized = rawMessage.replace(/[\r\n]+/g, " ").trim();
|
|
1307
|
+
const separator = normalized.indexOf(":");
|
|
1308
|
+
const rawPath = separator >= 0 ? normalized.slice(0, separator).trim() : "";
|
|
1309
|
+
const detail = separator >= 0 ? normalized.slice(separator + 1).trim() : normalized;
|
|
46
1310
|
return {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
1311
|
+
map,
|
|
1312
|
+
message: boundText(sanitizeDiagnosticSecrets(sanitizeUrls(detail)), maxMessageLength),
|
|
1313
|
+
path: boundText(stableStylePath(style, map, rawPath), maxPathLength)
|
|
50
1314
|
};
|
|
51
1315
|
}
|
|
52
|
-
function
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
return sourceDir ? [{ mapName, sourceDir }] : [];
|
|
1316
|
+
function stableStylePath(style, map, rawPath) {
|
|
1317
|
+
const fallback = `maps.${sanitizePathSegment(map)}.style`;
|
|
1318
|
+
if (!rawPath) return fallback;
|
|
1319
|
+
const path = rawPath.replace(/layers\[(\d+)]/g, (_match, index) => {
|
|
1320
|
+
const layer = style.layers[Number(index)];
|
|
1321
|
+
const id = typeof layer?.id === "string" && layer.id ? layer.id : index;
|
|
1322
|
+
return `layers.${sanitizePathSegment(id)}`;
|
|
60
1323
|
});
|
|
1324
|
+
return `${fallback}.${path}`;
|
|
61
1325
|
}
|
|
62
|
-
function
|
|
63
|
-
|
|
64
|
-
|
|
1326
|
+
function sanitizePathSegment(value) {
|
|
1327
|
+
let sanitized = "";
|
|
1328
|
+
let replacing = false;
|
|
1329
|
+
for (const character of value) {
|
|
1330
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
1331
|
+
const isAsciiLetter = codePoint >= 65 && codePoint <= 90 || codePoint >= 97 && codePoint <= 122;
|
|
1332
|
+
const isDigit = codePoint >= 48 && codePoint <= 57;
|
|
1333
|
+
const shouldReplace = !isAsciiLetter && !isDigit && character !== "-" && character !== "_";
|
|
1334
|
+
if (shouldReplace) {
|
|
1335
|
+
if (!replacing) sanitized += "-";
|
|
1336
|
+
replacing = true;
|
|
1337
|
+
} else {
|
|
1338
|
+
sanitized += character;
|
|
1339
|
+
replacing = false;
|
|
1340
|
+
}
|
|
65
1341
|
}
|
|
66
|
-
return
|
|
1342
|
+
return sanitized.slice(0, 128) || "(unknown)";
|
|
67
1343
|
}
|
|
68
|
-
function
|
|
69
|
-
if (
|
|
70
|
-
|
|
1344
|
+
function collectJsonIssues(value, path, map, issues, ancestors) {
|
|
1345
|
+
if (issues.length >= maxIssues) return;
|
|
1346
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
1347
|
+
if (typeof value === "number") {
|
|
1348
|
+
if (!Number.isFinite(value)) addJsonIssue(map, path, "non-finite number", issues);
|
|
1349
|
+
return;
|
|
71
1350
|
}
|
|
72
|
-
if (typeof
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
1351
|
+
if (typeof value !== "object") {
|
|
1352
|
+
addJsonIssue(map, path, typeof value, issues);
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
if (ancestors.has(value)) {
|
|
1356
|
+
addJsonIssue(map, path, "cyclic object", issues);
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
ancestors.add(value);
|
|
1360
|
+
if (Array.isArray(value)) {
|
|
1361
|
+
value.forEach((item, index) => {
|
|
1362
|
+
const layerId = path.endsWith(".layers") && item && typeof item === "object" && !Array.isArray(item) ? item.id : void 0;
|
|
1363
|
+
const childPath = typeof layerId === "string" && layerId ? `${path}.${sanitizePathSegment(layerId)}` : `${path}[${index}]`;
|
|
1364
|
+
collectJsonIssues(item, childPath, map, issues, ancestors);
|
|
1365
|
+
});
|
|
1366
|
+
} else {
|
|
1367
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1368
|
+
collectJsonIssues(item, `${path}.${sanitizePathSegment(key)}`, map, issues, ancestors);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
ancestors.delete(value);
|
|
1372
|
+
}
|
|
1373
|
+
function addJsonIssue(map, path, type, issues) {
|
|
1374
|
+
issues.push({
|
|
1375
|
+
map,
|
|
1376
|
+
message: `Expected a recursive JSON value; found ${type}.`,
|
|
1377
|
+
path: boundText(path, maxPathLength)
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
function normalizeIssues(issues) {
|
|
1381
|
+
const normalized = issues.map((issue) => ({
|
|
1382
|
+
map: boundText(sanitizePathSegment(issue.map), 128),
|
|
1383
|
+
message: boundText(
|
|
1384
|
+
sanitizeDiagnosticSecrets(issue.message.replace(/[\r\n]+/g, " ").trim()),
|
|
1385
|
+
maxMessageLength
|
|
1386
|
+
),
|
|
1387
|
+
path: boundText(issue.path.replaceAll("\\", "/"), maxPathLength)
|
|
1388
|
+
}));
|
|
1389
|
+
normalized.sort(
|
|
1390
|
+
(left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : left.message < right.message ? -1 : left.message > right.message ? 1 : 0
|
|
1391
|
+
);
|
|
1392
|
+
return normalized.filter(
|
|
1393
|
+
(issue, index) => index === 0 || issue.path !== normalized[index - 1]?.path || issue.message !== normalized[index - 1]?.message
|
|
1394
|
+
).slice(0, maxIssues);
|
|
1395
|
+
}
|
|
1396
|
+
function sanitizeUrls(message) {
|
|
1397
|
+
return message.replace(/https?:\/\/[^\s'"<>]+/gi, (value) => {
|
|
1398
|
+
try {
|
|
1399
|
+
return new URL(value.replace(/[),.;]+$/, "")).origin;
|
|
1400
|
+
} catch {
|
|
1401
|
+
return "(resource URL)";
|
|
1402
|
+
}
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
function boundText(value, limit) {
|
|
1406
|
+
return value.length <= limit ? value : `${value.slice(0, limit - 1)}\u2026`;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
// src/feature-inspection.ts
|
|
1410
|
+
import { VectorTile } from "@mapbox/vector-tile";
|
|
1411
|
+
import Pbf from "pbf";
|
|
1412
|
+
import {
|
|
1413
|
+
compareCodeUnits as compareCodeUnits2,
|
|
1414
|
+
createStyleFromProject
|
|
1415
|
+
} from "@tileflow/core";
|
|
1416
|
+
var mercatorLatitudeLimit = 85.0511287798066;
|
|
1417
|
+
var maxTileJsonBytes = 1024 * 1024;
|
|
1418
|
+
var maxTileBytes = 6 * 1024 * 1024;
|
|
1419
|
+
var maxTotalTileBytes = 24 * 1024 * 1024;
|
|
1420
|
+
var maxTiles = 32;
|
|
1421
|
+
var maxScannedFeatures = 2e4;
|
|
1422
|
+
var maxStringLength = 256;
|
|
1423
|
+
async function inspectTileflowFeatures(project, mapName, input) {
|
|
1424
|
+
const options = validateInspectionOptions(input);
|
|
1425
|
+
if (!Object.hasOwn(project.maps, mapName)) {
|
|
1426
|
+
const available = Object.keys(project.maps).sort(compareCodeUnits2);
|
|
1427
|
+
throw new Error(
|
|
1428
|
+
`Unknown map "${mapName}". Available maps: ${available.join(", ") || "(none)"}`
|
|
1429
|
+
);
|
|
1430
|
+
}
|
|
1431
|
+
const style = createStyleFromProject(project, mapName, { tileBaseUrl: options.tileBaseUrl });
|
|
1432
|
+
assertValidTileflowStyle(style, mapName);
|
|
1433
|
+
const source = resolveVectorSource(style, options.sourceLayers);
|
|
1434
|
+
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
1435
|
+
const remoteOrigins = /* @__PURE__ */ new Set();
|
|
1436
|
+
const tileSource = await resolveTileSource(
|
|
1437
|
+
source.definition,
|
|
1438
|
+
fetchImplementation,
|
|
1439
|
+
options,
|
|
1440
|
+
remoteOrigins
|
|
1441
|
+
);
|
|
1442
|
+
const bounds = viewportBounds(options.center, options.zoom, options.width, options.height);
|
|
1443
|
+
const tileZoom = resolveTileZoom(options.zoom, tileSource.minzoom, tileSource.maxzoom);
|
|
1444
|
+
const tileCoordinates = tileCover(bounds, tileZoom);
|
|
1445
|
+
if (tileCoordinates.length > maxTiles) {
|
|
1446
|
+
throw new Error(
|
|
1447
|
+
`Feature inspection would read ${tileCoordinates.length} tiles; narrow the viewport or increase zoom (maximum ${maxTiles}).`
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
const features = [];
|
|
1451
|
+
let scannedFeatures = 0;
|
|
1452
|
+
let totalTileBytes = 0;
|
|
1453
|
+
let scanTruncated = false;
|
|
1454
|
+
for (const coordinate of tileCoordinates) {
|
|
1455
|
+
const tileUrl = resolveTileUrl(tileSource.template, coordinate, tileSource.scheme);
|
|
1456
|
+
const bytes = await fetchBytes(tileUrl, {
|
|
1457
|
+
fetchImplementation,
|
|
1458
|
+
label: "vector tile",
|
|
1459
|
+
limit: maxTileBytes,
|
|
1460
|
+
signal: options.signal,
|
|
1461
|
+
timeoutMs: options.timeoutMs
|
|
1462
|
+
});
|
|
1463
|
+
remoteOrigins.add(safeOrigin(bytes.finalUrl));
|
|
1464
|
+
totalTileBytes += bytes.body.byteLength;
|
|
1465
|
+
if (totalTileBytes > maxTotalTileBytes) {
|
|
1466
|
+
throw new Error(
|
|
1467
|
+
`Feature inspection exceeded the ${maxTotalTileBytes}-byte total vector-tile limit.`
|
|
1468
|
+
);
|
|
1469
|
+
}
|
|
1470
|
+
const tile = new VectorTile(new Pbf(bytes.body));
|
|
1471
|
+
for (const sourceLayer of options.sourceLayers) {
|
|
1472
|
+
const layer = tile.layers[sourceLayer];
|
|
1473
|
+
if (!layer) continue;
|
|
1474
|
+
for (let index = 0; index < layer.length; index += 1) {
|
|
1475
|
+
scannedFeatures += 1;
|
|
1476
|
+
if (scannedFeatures > maxScannedFeatures) {
|
|
1477
|
+
scanTruncated = true;
|
|
1478
|
+
break;
|
|
1479
|
+
}
|
|
1480
|
+
const vectorFeature = layer.feature(index);
|
|
1481
|
+
const geoJsonFeature = vectorFeature.toGeoJSON(coordinate.x, coordinate.y, coordinate.z);
|
|
1482
|
+
const geometry = summarizeGeometry(geoJsonFeature.geometry);
|
|
1483
|
+
if (!geometry || !boundsIntersect(bounds, geometry.bounds)) continue;
|
|
1484
|
+
features.push({
|
|
1485
|
+
sourceLayer,
|
|
1486
|
+
id: typeof vectorFeature.id === "number" && Number.isSafeInteger(vectorFeature.id) ? vectorFeature.id : null,
|
|
1487
|
+
geometry,
|
|
1488
|
+
properties: projectProperties(vectorFeature.properties, options.properties)
|
|
1489
|
+
});
|
|
77
1490
|
}
|
|
78
|
-
|
|
1491
|
+
if (scanTruncated) break;
|
|
79
1492
|
}
|
|
80
|
-
|
|
1493
|
+
if (scanTruncated) break;
|
|
81
1494
|
}
|
|
82
|
-
const
|
|
1495
|
+
const uniqueFeatures = deduplicateFeatures(features).sort(compareInspectedFeatures);
|
|
1496
|
+
const limitedFeatures = uniqueFeatures.slice(0, options.limit);
|
|
1497
|
+
const metadataVersion = style.metadata?.["tileflow:tilesetVersion"];
|
|
83
1498
|
return {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
...
|
|
88
|
-
|
|
89
|
-
|
|
1499
|
+
schemaVersion: 1,
|
|
1500
|
+
map: mapName,
|
|
1501
|
+
camera: {
|
|
1502
|
+
center: [...options.center],
|
|
1503
|
+
zoom: options.zoom,
|
|
1504
|
+
viewport: { width: options.width, height: options.height }
|
|
1505
|
+
},
|
|
1506
|
+
source: {
|
|
1507
|
+
id: source.id,
|
|
1508
|
+
origin: tileSource.origin,
|
|
1509
|
+
tileJsonPath: tileSource.tileJsonPath,
|
|
1510
|
+
tileOrigins: [...remoteOrigins].sort(compareCodeUnits2),
|
|
1511
|
+
version: typeof metadataVersion === "string" ? metadataVersion : null
|
|
1512
|
+
},
|
|
1513
|
+
sourceLayers: options.sourceLayers,
|
|
1514
|
+
properties: options.properties,
|
|
1515
|
+
tileZoom,
|
|
1516
|
+
tilesRead: tileCoordinates.length,
|
|
1517
|
+
scannedFeatures: Math.min(scannedFeatures, maxScannedFeatures),
|
|
1518
|
+
truncated: scanTruncated || uniqueFeatures.length > options.limit,
|
|
1519
|
+
features: limitedFeatures
|
|
90
1520
|
};
|
|
91
1521
|
}
|
|
92
|
-
|
|
93
|
-
const
|
|
94
|
-
if (
|
|
95
|
-
throw new Error(
|
|
1522
|
+
function validateInspectionOptions(input) {
|
|
1523
|
+
const center = input.center;
|
|
1524
|
+
if (!Array.isArray(center) || center.length !== 2 || !Number.isFinite(center[0]) || !Number.isFinite(center[1]) || center[0] < -180 || center[0] > 180 || center[1] < -mercatorLatitudeLimit || center[1] > mercatorLatitudeLimit) {
|
|
1525
|
+
throw new Error(
|
|
1526
|
+
`Feature inspection center must be [longitude, latitude] inside Web Mercator bounds.`
|
|
1527
|
+
);
|
|
96
1528
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
1529
|
+
if (!Number.isFinite(input.zoom) || input.zoom < 0 || input.zoom > 24) {
|
|
1530
|
+
throw new Error("Feature inspection zoom must be between 0 and 24.");
|
|
1531
|
+
}
|
|
1532
|
+
const width = boundedInteger(input.width ?? 512, 64, 2048, "width");
|
|
1533
|
+
const height = boundedInteger(input.height ?? 512, 64, 2048, "height");
|
|
1534
|
+
const limit = boundedInteger(input.limit ?? 200, 1, 500, "limit");
|
|
1535
|
+
const timeoutMs = boundedInteger(input.timeoutMs ?? 1e4, 100, 6e4, "timeout");
|
|
1536
|
+
const sourceLayers = normalizeNames(input.sourceLayers, 1, 12, "source layer");
|
|
1537
|
+
const properties = normalizeNames(input.properties ?? [], 0, 16, "property");
|
|
1538
|
+
return {
|
|
1539
|
+
...input,
|
|
1540
|
+
center: [center[0], center[1]],
|
|
1541
|
+
height,
|
|
1542
|
+
limit,
|
|
1543
|
+
properties,
|
|
1544
|
+
sourceLayers,
|
|
1545
|
+
timeoutMs,
|
|
1546
|
+
width
|
|
1547
|
+
};
|
|
107
1548
|
}
|
|
108
|
-
|
|
109
|
-
if (!
|
|
110
|
-
throw new Error(
|
|
1549
|
+
function boundedInteger(value, minimum, maximum, label) {
|
|
1550
|
+
if (!Number.isInteger(value) || value < minimum || value > maximum) {
|
|
1551
|
+
throw new Error(
|
|
1552
|
+
`Feature inspection ${label} must be an integer from ${minimum} to ${maximum}.`
|
|
1553
|
+
);
|
|
111
1554
|
}
|
|
112
|
-
|
|
113
|
-
return entries.filter((entry) => entry.isFile() && iconFileExtensions.has(extname(entry.name).toLowerCase())).map((entry) => ({
|
|
114
|
-
name: entry.name.slice(0, -extname(entry.name).length),
|
|
115
|
-
path: resolve(sourceDir, entry.name)
|
|
116
|
-
})).sort((left, right) => left.name.localeCompare(right.name));
|
|
1555
|
+
return value;
|
|
117
1556
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
const
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const column = indexNumber % columns;
|
|
129
|
-
const row = Math.floor(indexNumber / columns);
|
|
130
|
-
const left = column * cellSize;
|
|
131
|
-
const top = row * cellSize;
|
|
132
|
-
index[icon.name] = {
|
|
133
|
-
height: cellSize,
|
|
134
|
-
pixelRatio,
|
|
135
|
-
width: cellSize,
|
|
136
|
-
x: left,
|
|
137
|
-
y: top
|
|
138
|
-
};
|
|
139
|
-
return {
|
|
140
|
-
input: await sharp(icon.path, { density: 72 * pixelRatio }).resize(cellSize, cellSize, {
|
|
141
|
-
background: { alpha: 0, b: 0, g: 0, r: 0 },
|
|
142
|
-
fit: "contain"
|
|
143
|
-
}).png().toBuffer(),
|
|
144
|
-
left,
|
|
145
|
-
top
|
|
146
|
-
};
|
|
147
|
-
})
|
|
148
|
-
);
|
|
149
|
-
const image = await sharp({
|
|
150
|
-
create: {
|
|
151
|
-
background: { alpha: 0, b: 0, g: 0, r: 0 },
|
|
152
|
-
channels: 4,
|
|
153
|
-
height,
|
|
154
|
-
width
|
|
1557
|
+
function normalizeNames(values, minimum, maximum, label) {
|
|
1558
|
+
if (!Array.isArray(values) || values.length < minimum || values.length > maximum) {
|
|
1559
|
+
throw new Error(
|
|
1560
|
+
`Feature inspection requires ${minimum}-${maximum} ${label}${maximum === 1 ? "" : "s"}.`
|
|
1561
|
+
);
|
|
1562
|
+
}
|
|
1563
|
+
const normalized = [...new Set(values)].sort(compareCodeUnits2);
|
|
1564
|
+
for (const value of normalized) {
|
|
1565
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(value)) {
|
|
1566
|
+
throw new Error(`Invalid feature inspection ${label} "${value}".`);
|
|
155
1567
|
}
|
|
156
|
-
}
|
|
157
|
-
return
|
|
158
|
-
image,
|
|
159
|
-
index,
|
|
160
|
-
sourceDir
|
|
161
|
-
};
|
|
1568
|
+
}
|
|
1569
|
+
return normalized;
|
|
162
1570
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
1571
|
+
function resolveVectorSource(style, sourceLayers) {
|
|
1572
|
+
const requested = new Set(sourceLayers);
|
|
1573
|
+
const referencedSourceIds = new Set(
|
|
1574
|
+
style.layers.filter((layer) => requested.has(String(layer["source-layer"] ?? ""))).map((layer) => layer.source).filter((sourceId) => typeof sourceId === "string")
|
|
1575
|
+
);
|
|
1576
|
+
const vectorSources = Object.entries(style.sources).filter(
|
|
1577
|
+
([, definition2]) => definition2.type === "vector"
|
|
1578
|
+
);
|
|
1579
|
+
const candidates = referencedSourceIds.size > 0 ? vectorSources.filter(([sourceId]) => referencedSourceIds.has(sourceId)) : vectorSources;
|
|
1580
|
+
if (candidates.length !== 1) {
|
|
167
1581
|
throw new Error(
|
|
168
|
-
|
|
169
|
-
{ cause: error }
|
|
1582
|
+
`Feature inspection requires exactly one vector source for the selected layers; found ${candidates.length}.`
|
|
170
1583
|
);
|
|
171
1584
|
}
|
|
1585
|
+
const [id, definition] = candidates[0];
|
|
1586
|
+
return { id, definition };
|
|
172
1587
|
}
|
|
173
|
-
function
|
|
1588
|
+
async function resolveTileSource(definition, fetchImplementation, options, origins) {
|
|
1589
|
+
if (Array.isArray(definition.tiles) && typeof definition.tiles[0] === "string") {
|
|
1590
|
+
const template2 = safeHttpUrl(definition.tiles[0], "vector tile template");
|
|
1591
|
+
origins.add(template2.origin);
|
|
1592
|
+
return {
|
|
1593
|
+
maxzoom: finiteZoom(definition.maxzoom, 22),
|
|
1594
|
+
minzoom: finiteZoom(definition.minzoom, 0),
|
|
1595
|
+
origin: template2.origin,
|
|
1596
|
+
scheme: definition.scheme === "tms" ? "tms" : "xyz",
|
|
1597
|
+
template: template2,
|
|
1598
|
+
tileJsonPath: null
|
|
1599
|
+
};
|
|
1600
|
+
}
|
|
1601
|
+
if (typeof definition.url !== "string") {
|
|
1602
|
+
throw new Error("Feature inspection vector source must define an HTTP(S) TileJSON URL.");
|
|
1603
|
+
}
|
|
1604
|
+
const tileJsonUrl = safeHttpUrl(definition.url, "TileJSON URL");
|
|
1605
|
+
const response = await fetchBytes(tileJsonUrl, {
|
|
1606
|
+
fetchImplementation,
|
|
1607
|
+
label: "TileJSON",
|
|
1608
|
+
limit: maxTileJsonBytes,
|
|
1609
|
+
signal: options.signal,
|
|
1610
|
+
timeoutMs: options.timeoutMs
|
|
1611
|
+
});
|
|
1612
|
+
const finalTileJsonUrl = safeHttpUrl(response.finalUrl, "TileJSON response URL");
|
|
1613
|
+
origins.add(finalTileJsonUrl.origin);
|
|
1614
|
+
let parsed;
|
|
1615
|
+
try {
|
|
1616
|
+
parsed = JSON.parse(new TextDecoder().decode(response.body));
|
|
1617
|
+
} catch {
|
|
1618
|
+
throw new Error("Feature inspection received invalid TileJSON JSON.");
|
|
1619
|
+
}
|
|
1620
|
+
const tileJson = parseTileJson(parsed);
|
|
1621
|
+
const template = safeHttpUrl(
|
|
1622
|
+
new URL(tileJson.tiles[0], finalTileJsonUrl).toString(),
|
|
1623
|
+
"vector tile template"
|
|
1624
|
+
);
|
|
1625
|
+
origins.add(template.origin);
|
|
174
1626
|
return {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
1627
|
+
maxzoom: finiteZoom(tileJson.maxzoom, 22),
|
|
1628
|
+
minzoom: finiteZoom(tileJson.minzoom, 0),
|
|
1629
|
+
origin: finalTileJsonUrl.origin,
|
|
1630
|
+
scheme: tileJson.scheme === "tms" ? "tms" : "xyz",
|
|
1631
|
+
template,
|
|
1632
|
+
tileJsonPath: finalTileJsonUrl.pathname
|
|
179
1633
|
};
|
|
180
1634
|
}
|
|
181
|
-
function
|
|
1635
|
+
function parseTileJson(value) {
|
|
1636
|
+
if (!isRecord(value) || !Array.isArray(value.tiles) || value.tiles.length === 0) {
|
|
1637
|
+
throw new Error("Feature inspection TileJSON must contain a non-empty tiles array.");
|
|
1638
|
+
}
|
|
1639
|
+
const tiles = value.tiles.filter((entry) => typeof entry === "string");
|
|
1640
|
+
if (tiles.length !== value.tiles.length || tiles.length > 8) {
|
|
1641
|
+
throw new Error("Feature inspection TileJSON tiles must contain 1-8 URL templates.");
|
|
1642
|
+
}
|
|
182
1643
|
return {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
1644
|
+
tiles,
|
|
1645
|
+
...typeof value.maxzoom === "number" ? { maxzoom: value.maxzoom } : {},
|
|
1646
|
+
...typeof value.minzoom === "number" ? { minzoom: value.minzoom } : {},
|
|
1647
|
+
...typeof value.scheme === "string" ? { scheme: value.scheme } : {}
|
|
186
1648
|
};
|
|
187
1649
|
}
|
|
188
|
-
function
|
|
189
|
-
return
|
|
1650
|
+
function finiteZoom(value, fallback) {
|
|
1651
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 24 ? value : fallback;
|
|
190
1652
|
}
|
|
191
|
-
function
|
|
192
|
-
|
|
1653
|
+
function resolveTileZoom(zoom, minzoom, maxzoom) {
|
|
1654
|
+
if (minzoom > maxzoom) throw new Error("Feature inspection source minzoom exceeds maxzoom.");
|
|
1655
|
+
return Math.max(minzoom, Math.min(maxzoom, Math.floor(zoom)));
|
|
193
1656
|
}
|
|
194
|
-
function
|
|
195
|
-
const
|
|
196
|
-
const
|
|
197
|
-
|
|
1657
|
+
function viewportBounds(center, zoom, width, height) {
|
|
1658
|
+
const centerX = longitudeToWorldX(center[0]);
|
|
1659
|
+
const centerY = latitudeToWorldY(center[1]);
|
|
1660
|
+
const scale = 512 * 2 ** zoom;
|
|
1661
|
+
const westX = centerX - width / 2 / scale;
|
|
1662
|
+
const eastX = centerX + width / 2 / scale;
|
|
1663
|
+
if (westX < 0 || eastX > 1) {
|
|
1664
|
+
throw new Error("Feature inspection viewports that cross the antimeridian are not supported.");
|
|
1665
|
+
}
|
|
1666
|
+
const northY = Math.max(0, centerY - height / 2 / scale);
|
|
1667
|
+
const southY = Math.min(1, centerY + height / 2 / scale);
|
|
1668
|
+
return [
|
|
1669
|
+
worldXToLongitude(westX),
|
|
1670
|
+
worldYToLatitude(southY),
|
|
1671
|
+
worldXToLongitude(eastX),
|
|
1672
|
+
worldYToLatitude(northY)
|
|
1673
|
+
];
|
|
198
1674
|
}
|
|
199
|
-
function
|
|
200
|
-
|
|
1675
|
+
function tileCover(bounds, zoom) {
|
|
1676
|
+
const count = 2 ** zoom;
|
|
1677
|
+
const minimumX = clampTile(Math.floor(longitudeToWorldX(bounds[0]) * count), count);
|
|
1678
|
+
const maximumX = clampTile(Math.floor(longitudeToWorldX(bounds[2]) * count), count);
|
|
1679
|
+
const minimumY = clampTile(Math.floor(latitudeToWorldY(bounds[3]) * count), count);
|
|
1680
|
+
const maximumY = clampTile(Math.floor(latitudeToWorldY(bounds[1]) * count), count);
|
|
1681
|
+
const coordinates = [];
|
|
1682
|
+
for (let y = minimumY; y <= maximumY; y += 1) {
|
|
1683
|
+
for (let x = minimumX; x <= maximumX; x += 1) coordinates.push({ x, y, z: zoom });
|
|
1684
|
+
}
|
|
1685
|
+
return coordinates;
|
|
1686
|
+
}
|
|
1687
|
+
function clampTile(value, count) {
|
|
1688
|
+
return Math.max(0, Math.min(count - 1, value));
|
|
1689
|
+
}
|
|
1690
|
+
function resolveTileUrl(template, coordinate, scheme) {
|
|
1691
|
+
const y = scheme === "tms" ? 2 ** coordinate.z - 1 - coordinate.y : coordinate.y;
|
|
1692
|
+
const replacements = {
|
|
1693
|
+
z: coordinate.z,
|
|
1694
|
+
x: coordinate.x,
|
|
1695
|
+
y,
|
|
1696
|
+
"-y": 2 ** coordinate.z - 1 - coordinate.y
|
|
1697
|
+
};
|
|
1698
|
+
let value = template.toString();
|
|
1699
|
+
for (const [token, replacement] of Object.entries(replacements)) {
|
|
1700
|
+
value = value.replace(
|
|
1701
|
+
new RegExp(`(?:\\{${token}\\}|%7B${token}%7D)`, "giu"),
|
|
1702
|
+
String(replacement)
|
|
1703
|
+
);
|
|
1704
|
+
}
|
|
1705
|
+
if (/(?:\{(?:z|x|-?y)\}|%7B(?:z|x|-?y)%7D)/iu.test(value)) {
|
|
1706
|
+
throw new Error("Feature inspection tile template contains unresolved coordinates.");
|
|
1707
|
+
}
|
|
1708
|
+
return new URL(value);
|
|
1709
|
+
}
|
|
1710
|
+
async function fetchBytes(url, options) {
|
|
1711
|
+
const timeout = AbortSignal.timeout(options.timeoutMs);
|
|
1712
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
1713
|
+
const response = await options.fetchImplementation(url, { signal });
|
|
1714
|
+
if (!response.ok) {
|
|
1715
|
+
throw new Error(`${options.label} request failed with HTTP ${response.status}.`);
|
|
1716
|
+
}
|
|
1717
|
+
const declaredLength = Number(response.headers.get("content-length"));
|
|
1718
|
+
if (Number.isFinite(declaredLength) && declaredLength > options.limit) {
|
|
1719
|
+
throw new Error(`${options.label} exceeds the ${options.limit}-byte limit.`);
|
|
1720
|
+
}
|
|
1721
|
+
if (!response.body) throw new Error(`${options.label} response had no body.`);
|
|
1722
|
+
const chunks = [];
|
|
1723
|
+
let length = 0;
|
|
1724
|
+
const reader = response.body.getReader();
|
|
1725
|
+
while (true) {
|
|
1726
|
+
const result = await reader.read();
|
|
1727
|
+
if (result.done) break;
|
|
1728
|
+
length += result.value.byteLength;
|
|
1729
|
+
if (length > options.limit) {
|
|
1730
|
+
await reader.cancel();
|
|
1731
|
+
throw new Error(`${options.label} exceeds the ${options.limit}-byte limit.`);
|
|
1732
|
+
}
|
|
1733
|
+
chunks.push(result.value);
|
|
1734
|
+
}
|
|
1735
|
+
const body = new Uint8Array(length);
|
|
1736
|
+
let offset = 0;
|
|
1737
|
+
for (const chunk of chunks) {
|
|
1738
|
+
body.set(chunk, offset);
|
|
1739
|
+
offset += chunk.byteLength;
|
|
1740
|
+
}
|
|
1741
|
+
return { body, finalUrl: response.url || url.toString() };
|
|
1742
|
+
}
|
|
1743
|
+
function summarizeGeometry(value) {
|
|
1744
|
+
if (!isRecord(value) || typeof value.type !== "string" || !("coordinates" in value)) return;
|
|
1745
|
+
const points = [];
|
|
1746
|
+
collectCoordinates(value.coordinates, points);
|
|
1747
|
+
if (points.length === 0) return;
|
|
1748
|
+
let west = Infinity;
|
|
1749
|
+
let south = Infinity;
|
|
1750
|
+
let east = -Infinity;
|
|
1751
|
+
let north = -Infinity;
|
|
1752
|
+
for (const [longitude, latitude] of points) {
|
|
1753
|
+
west = Math.min(west, longitude);
|
|
1754
|
+
south = Math.min(south, latitude);
|
|
1755
|
+
east = Math.max(east, longitude);
|
|
1756
|
+
north = Math.max(north, latitude);
|
|
1757
|
+
}
|
|
1758
|
+
return {
|
|
1759
|
+
type: value.type,
|
|
1760
|
+
center: [roundCoordinate((west + east) / 2), roundCoordinate((south + north) / 2)],
|
|
1761
|
+
bounds: [
|
|
1762
|
+
roundCoordinate(west),
|
|
1763
|
+
roundCoordinate(south),
|
|
1764
|
+
roundCoordinate(east),
|
|
1765
|
+
roundCoordinate(north)
|
|
1766
|
+
]
|
|
1767
|
+
};
|
|
1768
|
+
}
|
|
1769
|
+
function collectCoordinates(value, points) {
|
|
1770
|
+
if (!Array.isArray(value)) return;
|
|
1771
|
+
if (value.length >= 2 && typeof value[0] === "number" && Number.isFinite(value[0]) && typeof value[1] === "number" && Number.isFinite(value[1])) {
|
|
1772
|
+
points.push([value[0], value[1]]);
|
|
1773
|
+
return;
|
|
1774
|
+
}
|
|
1775
|
+
for (const child of value) collectCoordinates(child, points);
|
|
1776
|
+
}
|
|
1777
|
+
function boundsIntersect(left, right) {
|
|
1778
|
+
return left[0] <= right[2] && left[2] >= right[0] && left[1] <= right[3] && left[3] >= right[1];
|
|
1779
|
+
}
|
|
1780
|
+
function projectProperties(source, properties) {
|
|
1781
|
+
const projected = {};
|
|
1782
|
+
for (const property of properties) {
|
|
1783
|
+
const value = source[property];
|
|
1784
|
+
if (typeof value === "string") projected[property] = value.slice(0, maxStringLength);
|
|
1785
|
+
else if (typeof value === "boolean") projected[property] = value;
|
|
1786
|
+
else if (typeof value === "number" && Number.isFinite(value)) projected[property] = value;
|
|
1787
|
+
}
|
|
1788
|
+
return projected;
|
|
1789
|
+
}
|
|
1790
|
+
function deduplicateFeatures(features) {
|
|
1791
|
+
const unique = /* @__PURE__ */ new Map();
|
|
1792
|
+
for (const feature of features) {
|
|
1793
|
+
const key = feature.id === null ? `${feature.sourceLayer}|${JSON.stringify(feature.geometry)}|${JSON.stringify(feature.properties)}` : `${feature.sourceLayer}|id:${feature.id}`;
|
|
1794
|
+
if (!unique.has(key)) unique.set(key, feature);
|
|
1795
|
+
}
|
|
1796
|
+
return [...unique.values()];
|
|
1797
|
+
}
|
|
1798
|
+
function compareInspectedFeatures(left, right) {
|
|
1799
|
+
const leftName = typeof left.properties.name === "string" ? left.properties.name : "";
|
|
1800
|
+
const rightName = typeof right.properties.name === "string" ? right.properties.name : "";
|
|
1801
|
+
return compareCodeUnits2(left.sourceLayer, right.sourceLayer) || Number(rightName.length > 0) - Number(leftName.length > 0) || compareCodeUnits2(leftName, rightName) || (left.id ?? Number.MAX_SAFE_INTEGER) - (right.id ?? Number.MAX_SAFE_INTEGER) || compareCodeUnits2(JSON.stringify(left), JSON.stringify(right));
|
|
1802
|
+
}
|
|
1803
|
+
function safeHttpUrl(value, label) {
|
|
1804
|
+
let parsed;
|
|
1805
|
+
try {
|
|
1806
|
+
parsed = new URL(value);
|
|
1807
|
+
} catch {
|
|
1808
|
+
throw new Error(`Feature inspection ${label} is not a valid URL.`);
|
|
1809
|
+
}
|
|
1810
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
1811
|
+
throw new Error(`Feature inspection ${label} must use HTTP or HTTPS.`);
|
|
1812
|
+
}
|
|
1813
|
+
return parsed;
|
|
1814
|
+
}
|
|
1815
|
+
function safeOrigin(value) {
|
|
1816
|
+
return safeHttpUrl(value, "response URL").origin;
|
|
1817
|
+
}
|
|
1818
|
+
function longitudeToWorldX(longitude) {
|
|
1819
|
+
return (longitude + 180) / 360;
|
|
1820
|
+
}
|
|
1821
|
+
function worldXToLongitude(x) {
|
|
1822
|
+
return x * 360 - 180;
|
|
1823
|
+
}
|
|
1824
|
+
function latitudeToWorldY(latitude) {
|
|
1825
|
+
const radians = latitude * Math.PI / 180;
|
|
1826
|
+
return (1 - Math.log(Math.tan(radians) + 1 / Math.cos(radians)) / Math.PI) / 2;
|
|
1827
|
+
}
|
|
1828
|
+
function worldYToLatitude(y) {
|
|
1829
|
+
return Math.atan(Math.sinh(Math.PI * (1 - 2 * y))) * 180 / Math.PI;
|
|
1830
|
+
}
|
|
1831
|
+
function roundCoordinate(value) {
|
|
1832
|
+
return Math.round(value * 1e7) / 1e7;
|
|
1833
|
+
}
|
|
1834
|
+
function isRecord(value) {
|
|
1835
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
201
1836
|
}
|
|
202
1837
|
|
|
203
1838
|
// src/index.ts
|
|
@@ -206,7 +1841,9 @@ var defaultTileflowConfigPath = "tileflow.config.ts";
|
|
|
206
1841
|
var defaultTileflowManifestPath = "public/tileflow/manifest.json";
|
|
207
1842
|
var defaultTileflowTileset = "world";
|
|
208
1843
|
var TileflowValidationError = class extends Error {
|
|
1844
|
+
code = "CONFIG_INVALID";
|
|
209
1845
|
messages;
|
|
1846
|
+
phase = "config-validation";
|
|
210
1847
|
constructor(messages) {
|
|
211
1848
|
super("Invalid Tileflow config");
|
|
212
1849
|
this.name = "TileflowValidationError";
|
|
@@ -215,10 +1852,13 @@ var TileflowValidationError = class extends Error {
|
|
|
215
1852
|
};
|
|
216
1853
|
async function loadTileflowConfig(configPath = defaultTileflowConfigPath, options = {}) {
|
|
217
1854
|
const cwd = options.cwd ?? process.cwd();
|
|
218
|
-
const resolvedPath =
|
|
219
|
-
if (!
|
|
1855
|
+
const resolvedPath = resolve3(cwd, configPath);
|
|
1856
|
+
if (!existsSync(resolvedPath)) {
|
|
220
1857
|
throw new Error(`Config not found: ${configPath}`);
|
|
221
1858
|
}
|
|
1859
|
+
if (options.fresh) {
|
|
1860
|
+
clearTileflowLocalModuleCache(resolvedPath, cwd);
|
|
1861
|
+
}
|
|
222
1862
|
const jiti = createJiti(import.meta.url, {
|
|
223
1863
|
fsCache: false,
|
|
224
1864
|
moduleCache: !options.fresh
|
|
@@ -271,7 +1911,22 @@ function createTileflowManifest(project, options = {}) {
|
|
|
271
1911
|
return createManifest(project, options);
|
|
272
1912
|
}
|
|
273
1913
|
function createTileflowStyle(project, mapName, options = {}) {
|
|
274
|
-
|
|
1914
|
+
const style = createStyleFromProject2(project, mapName, options);
|
|
1915
|
+
assertValidTileflowStyle(style, mapName);
|
|
1916
|
+
return style;
|
|
1917
|
+
}
|
|
1918
|
+
function createTileflowStyles(project, options = {}) {
|
|
1919
|
+
const styleEntries = [];
|
|
1920
|
+
const issues = [];
|
|
1921
|
+
for (const mapName of getTileflowMapNames(project).sort(compareCodeUnits3)) {
|
|
1922
|
+
const style = createStyleFromProject2(project, mapName, options);
|
|
1923
|
+
styleEntries.push([mapName, style]);
|
|
1924
|
+
issues.push(...validateTileflowStyle(style, mapName));
|
|
1925
|
+
}
|
|
1926
|
+
if (issues.length > 0) {
|
|
1927
|
+
throw new TileflowStyleValidationError(normalizeTileflowStyleValidationIssues(issues));
|
|
1928
|
+
}
|
|
1929
|
+
return Object.fromEntries(styleEntries);
|
|
275
1930
|
}
|
|
276
1931
|
async function createTileflowBuildArtifacts(options = {}) {
|
|
277
1932
|
const project = await loadValidTileflowConfig(options.config ?? defaultTileflowConfigPath, {
|
|
@@ -283,22 +1938,21 @@ async function createTileflowBuildArtifacts(options = {}) {
|
|
|
283
1938
|
cwd: options.cwd ?? process.cwd()
|
|
284
1939
|
});
|
|
285
1940
|
const styleOptions = { tileBaseUrl: options.tileBaseUrl };
|
|
286
|
-
const styles =
|
|
287
|
-
getTileflowMapNames(prepared.project).map((mapName) => [
|
|
288
|
-
mapName,
|
|
289
|
-
createStyleFromProject(prepared.project, mapName, styleOptions)
|
|
290
|
-
])
|
|
291
|
-
);
|
|
1941
|
+
const styles = createTileflowStyles(prepared.project, styleOptions);
|
|
292
1942
|
return {
|
|
293
1943
|
assets: prepared.assets,
|
|
294
1944
|
manifest: createManifest(prepared.project, {
|
|
295
1945
|
styleBaseUrl: options.styleBaseUrl,
|
|
296
1946
|
tileBaseUrl: options.tileBaseUrl
|
|
297
1947
|
}),
|
|
1948
|
+
project: prepared.project,
|
|
298
1949
|
styles,
|
|
299
1950
|
watchPaths: prepared.watchPaths
|
|
300
1951
|
};
|
|
301
1952
|
}
|
|
1953
|
+
function createTileflowArtifactSession(options = {}) {
|
|
1954
|
+
return createTileflowArtifactSessionWithBuilder(options, createTileflowBuildArtifacts);
|
|
1955
|
+
}
|
|
302
1956
|
async function getTileflowWatchPaths(options = {}) {
|
|
303
1957
|
const cwd = options.cwd ?? process.cwd();
|
|
304
1958
|
const project = await loadValidTileflowConfig(options.config ?? defaultTileflowConfigPath, {
|
|
@@ -309,25 +1963,25 @@ async function getTileflowWatchPaths(options = {}) {
|
|
|
309
1963
|
}
|
|
310
1964
|
async function writeTileflowBuildArtifacts(options) {
|
|
311
1965
|
const cwd = options.cwd ?? process.cwd();
|
|
312
|
-
const outDir =
|
|
313
|
-
const stylesDir =
|
|
1966
|
+
const outDir = resolve3(cwd, options.outDir);
|
|
1967
|
+
const stylesDir = resolve3(outDir, "styles");
|
|
314
1968
|
const artifacts = await createTileflowBuildArtifacts(options);
|
|
315
1969
|
await mkdir(stylesDir, { recursive: true });
|
|
316
1970
|
for (const [mapName, style] of Object.entries(artifacts.styles)) {
|
|
317
1971
|
await writeFile(
|
|
318
|
-
|
|
1972
|
+
resolve3(stylesDir, `${mapName}.json`),
|
|
319
1973
|
`${JSON.stringify(style, null, 2)}
|
|
320
1974
|
`,
|
|
321
1975
|
"utf8"
|
|
322
1976
|
);
|
|
323
1977
|
}
|
|
324
1978
|
for (const asset of artifacts.assets) {
|
|
325
|
-
const outputPath =
|
|
326
|
-
await mkdir(
|
|
1979
|
+
const outputPath = resolve3(outDir, asset.fileName);
|
|
1980
|
+
await mkdir(dirname2(outputPath), { recursive: true });
|
|
327
1981
|
await writeFile(outputPath, asset.source);
|
|
328
1982
|
}
|
|
329
1983
|
await writeFile(
|
|
330
|
-
|
|
1984
|
+
resolve3(outDir, "manifest.json"),
|
|
331
1985
|
`${JSON.stringify(artifacts.manifest, null, 2)}
|
|
332
1986
|
`,
|
|
333
1987
|
"utf8"
|
|
@@ -353,7 +2007,25 @@ async function writeTileflowNodeResponse(response, tileflowResponse) {
|
|
|
353
2007
|
tileflowResponse.headers.forEach((value, key) => {
|
|
354
2008
|
response.setHeader(key, value);
|
|
355
2009
|
});
|
|
356
|
-
|
|
2010
|
+
if (!tileflowResponse.body) {
|
|
2011
|
+
response.end();
|
|
2012
|
+
return;
|
|
2013
|
+
}
|
|
2014
|
+
const reader = tileflowResponse.body.getReader();
|
|
2015
|
+
try {
|
|
2016
|
+
while (true) {
|
|
2017
|
+
const { done, value } = await reader.read();
|
|
2018
|
+
if (done) break;
|
|
2019
|
+
if (response.destroyed) {
|
|
2020
|
+
await reader.cancel();
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
response.write(Buffer.from(value));
|
|
2024
|
+
}
|
|
2025
|
+
response.end();
|
|
2026
|
+
} finally {
|
|
2027
|
+
reader.releaseLock();
|
|
2028
|
+
}
|
|
357
2029
|
}
|
|
358
2030
|
function joinTileflowPublicUrl(publicBase, basePath) {
|
|
359
2031
|
const trimmedBase = publicBase.replace(/\/+$/g, "");
|
|
@@ -383,64 +2055,63 @@ function createTileflowDevRequestHandler(options = {}) {
|
|
|
383
2055
|
}
|
|
384
2056
|
const url = new URL(request.url);
|
|
385
2057
|
const path = stripTileflowBasePath(url.pathname, basePath);
|
|
386
|
-
const loadPreparedProject = async () => {
|
|
387
|
-
const project = await loadValidTileflowConfig(configPath, {
|
|
388
|
-
cwd,
|
|
389
|
-
fresh: true
|
|
390
|
-
});
|
|
391
|
-
return prepareTileflowProjectIcons(project, {
|
|
392
|
-
assetBaseUrl: `${url.origin}${basePath}`,
|
|
393
|
-
cwd
|
|
394
|
-
});
|
|
395
|
-
};
|
|
396
2058
|
if (path === null) {
|
|
397
2059
|
return jsonResponse({ error: "Not found" }, 404);
|
|
398
2060
|
}
|
|
399
2061
|
try {
|
|
400
|
-
if (path === "/"
|
|
401
|
-
|
|
2062
|
+
if (path === "/__events") {
|
|
2063
|
+
return options.session ? eventStreamResponse(options.session) : jsonResponse({ error: "Live events require a development session." }, 404);
|
|
2064
|
+
}
|
|
2065
|
+
if (path === "/__runtime/maplibre-gl.js") {
|
|
2066
|
+
return textAssetResponse(getLocalMapLibreAsset("js"), "text/javascript; charset=utf-8");
|
|
2067
|
+
}
|
|
2068
|
+
if (path === "/__runtime/maplibre-gl.css") {
|
|
2069
|
+
return textAssetResponse(getLocalMapLibreAsset("css"), "text/css; charset=utf-8");
|
|
2070
|
+
}
|
|
2071
|
+
let artifacts;
|
|
2072
|
+
let state;
|
|
2073
|
+
if (options.session) {
|
|
2074
|
+
artifacts = getSessionArtifacts(options.session);
|
|
2075
|
+
state = options.session.getState();
|
|
2076
|
+
} else {
|
|
2077
|
+
artifacts = await createTileflowBuildArtifacts({
|
|
2078
|
+
assetBaseUrl: `${url.origin}${basePath}`,
|
|
2079
|
+
config: configPath,
|
|
402
2080
|
cwd,
|
|
403
|
-
|
|
2081
|
+
styleBaseUrl: options.styleBaseUrl ?? `${url.origin}${basePath}`,
|
|
2082
|
+
tileBaseUrl
|
|
404
2083
|
});
|
|
405
|
-
|
|
2084
|
+
state = {
|
|
2085
|
+
artifacts,
|
|
2086
|
+
generation: 1,
|
|
2087
|
+
lastGoodGeneration: 1,
|
|
2088
|
+
status: "ready"
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
if (path === "/__status") {
|
|
2092
|
+
return jsonResponse(createTileflowArtifactStatus(state));
|
|
2093
|
+
}
|
|
2094
|
+
if (path === "/" || path === "") {
|
|
2095
|
+
const mapName = artifacts ? getFirstTileflowMapName(artifacts.project) : void 0;
|
|
2096
|
+
return htmlResponse(previewHtml(mapName, basePath, state));
|
|
406
2097
|
}
|
|
2098
|
+
if (!artifacts) return unavailableArtifactsResponse(state);
|
|
407
2099
|
if (path === "/manifest.json") {
|
|
408
|
-
|
|
409
|
-
cwd,
|
|
410
|
-
fresh: true
|
|
411
|
-
});
|
|
412
|
-
const styleBaseUrl = options.styleBaseUrl ?? `${url.origin}${basePath}`;
|
|
413
|
-
return jsonResponse(
|
|
414
|
-
createManifest(project, {
|
|
415
|
-
styleBaseUrl,
|
|
416
|
-
tileBaseUrl
|
|
417
|
-
})
|
|
418
|
-
);
|
|
2100
|
+
return jsonResponse(artifacts.manifest);
|
|
419
2101
|
}
|
|
420
2102
|
if (path === "/style.json") {
|
|
421
|
-
|
|
422
|
-
return jsonResponse(
|
|
423
|
-
createStyleFromProject(prepared.project, getFirstTileflowMapName(prepared.project), {
|
|
424
|
-
tileBaseUrl
|
|
425
|
-
})
|
|
426
|
-
);
|
|
2103
|
+
return jsonResponse(artifacts.styles[getFirstTileflowMapName(artifacts.project)]);
|
|
427
2104
|
}
|
|
428
2105
|
if (path.startsWith("/styles/")) {
|
|
429
|
-
const prepared = await loadPreparedProject();
|
|
430
2106
|
const mapName = getTileflowStyleMapName(path);
|
|
431
|
-
if (!
|
|
2107
|
+
if (!Object.hasOwn(artifacts.styles, mapName)) {
|
|
432
2108
|
return jsonResponse({ error: `Unknown map: ${mapName}` }, 404);
|
|
433
2109
|
}
|
|
434
|
-
return jsonResponse(
|
|
435
|
-
createStyleFromProject(prepared.project, mapName, {
|
|
436
|
-
tileBaseUrl
|
|
437
|
-
})
|
|
438
|
-
);
|
|
2110
|
+
return jsonResponse(artifacts.styles[mapName]);
|
|
439
2111
|
}
|
|
440
2112
|
if (path.startsWith("/icons/")) {
|
|
441
|
-
const prepared = await loadPreparedProject();
|
|
442
2113
|
const assetName = path.replace(/^\/+/, "");
|
|
443
|
-
const asset =
|
|
2114
|
+
const asset = artifacts.assets.find((candidate) => candidate.fileName === assetName);
|
|
444
2115
|
if (!asset) {
|
|
445
2116
|
return jsonResponse({ error: `Unknown icon asset: ${assetName}` }, 404);
|
|
446
2117
|
}
|
|
@@ -453,6 +2124,60 @@ function createTileflowDevRequestHandler(options = {}) {
|
|
|
453
2124
|
}
|
|
454
2125
|
};
|
|
455
2126
|
}
|
|
2127
|
+
function createTileflowArtifactStatus(state) {
|
|
2128
|
+
return {
|
|
2129
|
+
schemaVersion: tileflowArtifactSessionSchemaVersion,
|
|
2130
|
+
generation: state.generation,
|
|
2131
|
+
status: state.status,
|
|
2132
|
+
..."lastGoodGeneration" in state && state.lastGoodGeneration !== void 0 ? { lastGoodGeneration: state.lastGoodGeneration } : {},
|
|
2133
|
+
...state.status === "invalid" ? { diagnostics: state.diagnostics } : {}
|
|
2134
|
+
};
|
|
2135
|
+
}
|
|
2136
|
+
function getSessionArtifacts(session) {
|
|
2137
|
+
const state = session.getState();
|
|
2138
|
+
return state.status === "ready" ? state.artifacts : session.getLastGoodArtifacts();
|
|
2139
|
+
}
|
|
2140
|
+
function unavailableArtifactsResponse(state) {
|
|
2141
|
+
return jsonResponse(
|
|
2142
|
+
{
|
|
2143
|
+
error: "No valid Tileflow artifact generation is available.",
|
|
2144
|
+
...createTileflowArtifactStatus(state)
|
|
2145
|
+
},
|
|
2146
|
+
409
|
|
2147
|
+
);
|
|
2148
|
+
}
|
|
2149
|
+
function eventStreamResponse(session) {
|
|
2150
|
+
const encoder = new TextEncoder();
|
|
2151
|
+
let unsubscribe = () => {
|
|
2152
|
+
};
|
|
2153
|
+
const stream = new ReadableStream({
|
|
2154
|
+
start(controller) {
|
|
2155
|
+
const enqueue = (state) => {
|
|
2156
|
+
const status = createTileflowArtifactStatus(state);
|
|
2157
|
+
controller.enqueue(
|
|
2158
|
+
encoder.encode(`event: ${status.status}
|
|
2159
|
+
data: ${JSON.stringify(status)}
|
|
2160
|
+
|
|
2161
|
+
`)
|
|
2162
|
+
);
|
|
2163
|
+
};
|
|
2164
|
+
enqueue(session.getState());
|
|
2165
|
+
unsubscribe = session.subscribe(enqueue);
|
|
2166
|
+
},
|
|
2167
|
+
cancel() {
|
|
2168
|
+
unsubscribe();
|
|
2169
|
+
}
|
|
2170
|
+
});
|
|
2171
|
+
return new Response(stream, {
|
|
2172
|
+
headers: {
|
|
2173
|
+
"Access-Control-Allow-Origin": "*",
|
|
2174
|
+
"Cache-Control": "no-cache, no-transform",
|
|
2175
|
+
Connection: "keep-alive",
|
|
2176
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
2177
|
+
"X-Accel-Buffering": "no"
|
|
2178
|
+
}
|
|
2179
|
+
});
|
|
2180
|
+
}
|
|
456
2181
|
function getNodeHeader(request, name) {
|
|
457
2182
|
const value = request.headers[name];
|
|
458
2183
|
return Array.isArray(value) ? value[0] : value;
|
|
@@ -474,6 +2199,15 @@ function stripTileflowBasePath(pathname, basePath) {
|
|
|
474
2199
|
return null;
|
|
475
2200
|
}
|
|
476
2201
|
function tileflowErrorResponse(error) {
|
|
2202
|
+
if (error instanceof TileflowStyleValidationError) {
|
|
2203
|
+
return jsonResponse(
|
|
2204
|
+
{
|
|
2205
|
+
error: error.message,
|
|
2206
|
+
issues: error.issues
|
|
2207
|
+
},
|
|
2208
|
+
400
|
|
2209
|
+
);
|
|
2210
|
+
}
|
|
477
2211
|
if (error instanceof TileflowValidationError) {
|
|
478
2212
|
return jsonResponse(
|
|
479
2213
|
{
|
|
@@ -529,21 +2263,19 @@ function resolveAssetBaseUrl(options) {
|
|
|
529
2263
|
function isRelativePublicUrl(value) {
|
|
530
2264
|
return !(value.startsWith("http://") || value.startsWith("https://") || value.startsWith("/") || value.startsWith("data:"));
|
|
531
2265
|
}
|
|
532
|
-
function previewHtml(mapName, basePath) {
|
|
533
|
-
const styleUrl = `${basePath}/styles/${mapName}.json
|
|
2266
|
+
function previewHtml(mapName, basePath, state) {
|
|
2267
|
+
const styleUrl = mapName ? `${basePath}/styles/${mapName}.json` : void 0;
|
|
2268
|
+
const initialStatus = createTileflowArtifactStatus(state);
|
|
534
2269
|
return `<!doctype html>
|
|
535
2270
|
<html lang="en">
|
|
536
2271
|
<head>
|
|
537
2272
|
<meta charset="utf-8" />
|
|
538
2273
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
539
2274
|
<title>Tileflow Preview</title>
|
|
540
|
-
<link rel="
|
|
541
|
-
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
542
|
-
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet" />
|
|
543
|
-
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.css" />
|
|
2275
|
+
<link rel="stylesheet" href="${basePath}/__runtime/maplibre-gl.css" />
|
|
544
2276
|
<style>
|
|
545
2277
|
html, body, #map { height: 100%; margin: 0; }
|
|
546
|
-
body { font-family:
|
|
2278
|
+
body { font-family: ui-sans-serif, system-ui, sans-serif; }
|
|
547
2279
|
.badge {
|
|
548
2280
|
position: fixed;
|
|
549
2281
|
left: 16px;
|
|
@@ -556,35 +2288,131 @@ function previewHtml(mapName, basePath) {
|
|
|
556
2288
|
padding: 10px 12px;
|
|
557
2289
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.12);
|
|
558
2290
|
}
|
|
2291
|
+
.status {
|
|
2292
|
+
position: fixed;
|
|
2293
|
+
left: 16px;
|
|
2294
|
+
right: 16px;
|
|
2295
|
+
bottom: 16px;
|
|
2296
|
+
z-index: 2;
|
|
2297
|
+
display: none;
|
|
2298
|
+
max-width: 720px;
|
|
2299
|
+
border: 1px solid rgba(160, 46, 46, 0.35);
|
|
2300
|
+
border-radius: 8px;
|
|
2301
|
+
background: rgba(255, 244, 244, 0.96);
|
|
2302
|
+
color: #702020;
|
|
2303
|
+
padding: 12px;
|
|
2304
|
+
white-space: pre-wrap;
|
|
2305
|
+
}
|
|
559
2306
|
</style>
|
|
560
2307
|
</head>
|
|
561
2308
|
<body>
|
|
562
|
-
<div class="badge">Tileflow preview</div>
|
|
2309
|
+
<div class="badge" id="badge">Tileflow preview</div>
|
|
2310
|
+
<div class="status" id="status" role="status"></div>
|
|
563
2311
|
<div id="map"></div>
|
|
564
|
-
<script
|
|
565
|
-
|
|
2312
|
+
<script src="${basePath}/__runtime/maplibre-gl.js"></script>
|
|
2313
|
+
<script>
|
|
2314
|
+
const initialStatus = ${JSON.stringify(initialStatus)};
|
|
2315
|
+
const initialGeneration = initialStatus.generation;
|
|
2316
|
+
const badge = document.getElementById("badge");
|
|
2317
|
+
const status = document.getElementById("status");
|
|
2318
|
+
const styleUrl = ${JSON.stringify(styleUrl)};
|
|
566
2319
|
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
2320
|
+
if (styleUrl) {
|
|
2321
|
+
const map = new maplibregl.Map({
|
|
2322
|
+
container: "map",
|
|
2323
|
+
style: styleUrl,
|
|
2324
|
+
center: [-3.7038, 40.4168],
|
|
2325
|
+
zoom: 12
|
|
2326
|
+
});
|
|
2327
|
+
map.addControl(new maplibregl.NavigationControl(), "top-right");
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
function applyStatus(next) {
|
|
2331
|
+
badge.textContent = "Tileflow preview \xB7 " + next.status;
|
|
2332
|
+
if (next.status === "invalid") {
|
|
2333
|
+
const diagnostics = next.diagnostics || [];
|
|
2334
|
+
status.textContent = diagnostics.map((item) =>
|
|
2335
|
+
(item.path ? item.path + ": " : "") + item.message
|
|
2336
|
+
).join("\\n") || "Tileflow config is invalid.";
|
|
2337
|
+
status.style.display = "block";
|
|
2338
|
+
return;
|
|
2339
|
+
}
|
|
2340
|
+
status.style.display = "none";
|
|
2341
|
+
if (next.status === "ready" && next.generation > initialGeneration) {
|
|
2342
|
+
location.reload();
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
573
2345
|
|
|
574
|
-
|
|
2346
|
+
applyStatus(initialStatus);
|
|
2347
|
+
const events = new EventSource(${JSON.stringify(`${basePath}/__events`)});
|
|
2348
|
+
for (const eventName of ["building", "ready", "invalid"]) {
|
|
2349
|
+
events.addEventListener(eventName, (event) => applyStatus(JSON.parse(event.data)));
|
|
2350
|
+
}
|
|
575
2351
|
</script>
|
|
576
2352
|
</body>
|
|
577
2353
|
</html>`;
|
|
578
2354
|
}
|
|
2355
|
+
var localRequire = createRequire(import.meta.url);
|
|
2356
|
+
var localMapLibreJavaScript;
|
|
2357
|
+
var localMapLibreStylesheet;
|
|
2358
|
+
function getLocalMapLibreAsset(kind) {
|
|
2359
|
+
if (kind === "js" && localMapLibreJavaScript !== void 0) return localMapLibreJavaScript;
|
|
2360
|
+
if (kind === "css" && localMapLibreStylesheet !== void 0) return localMapLibreStylesheet;
|
|
2361
|
+
const packagePath = localRequire.resolve("maplibre-gl/package.json");
|
|
2362
|
+
const source = readFileSync(
|
|
2363
|
+
join(dirname2(packagePath), "dist", kind === "js" ? "maplibre-gl.js" : "maplibre-gl.css"),
|
|
2364
|
+
"utf8"
|
|
2365
|
+
);
|
|
2366
|
+
if (kind === "js") localMapLibreJavaScript = source;
|
|
2367
|
+
else localMapLibreStylesheet = source;
|
|
2368
|
+
return source;
|
|
2369
|
+
}
|
|
2370
|
+
function textAssetResponse(body, contentType) {
|
|
2371
|
+
return new Response(body, {
|
|
2372
|
+
headers: {
|
|
2373
|
+
"Access-Control-Allow-Origin": "*",
|
|
2374
|
+
"Cache-Control": "no-store",
|
|
2375
|
+
"Content-Type": contentType
|
|
2376
|
+
}
|
|
2377
|
+
});
|
|
2378
|
+
}
|
|
2379
|
+
function clearTileflowLocalModuleCache(configPath, cwd) {
|
|
2380
|
+
const roots = [canonicalPath2(cwd), canonicalPath2(dirname2(resolve3(configPath)))];
|
|
2381
|
+
for (const cachePath of Object.keys(localRequire.cache)) {
|
|
2382
|
+
if (cachePath.split(sep3).includes("node_modules")) continue;
|
|
2383
|
+
if (roots.some((root) => isPathWithin(root, canonicalPath2(cachePath)))) {
|
|
2384
|
+
delete localRequire.cache[cachePath];
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
function canonicalPath2(path) {
|
|
2389
|
+
try {
|
|
2390
|
+
return realpathSync2.native(resolve3(path));
|
|
2391
|
+
} catch {
|
|
2392
|
+
return resolve3(path);
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
function isPathWithin(root, candidate) {
|
|
2396
|
+
const path = relative3(resolve3(root), resolve3(candidate));
|
|
2397
|
+
return path === "" || !isAbsolute3(path) && path !== ".." && !path.startsWith(`..${sep3}`);
|
|
2398
|
+
}
|
|
579
2399
|
export {
|
|
2400
|
+
TileflowIconCompilationError,
|
|
2401
|
+
TileflowStyleValidationError,
|
|
580
2402
|
TileflowValidationError,
|
|
581
2403
|
asTileflowProjectConfig,
|
|
582
2404
|
assertValidTileflowConfig,
|
|
2405
|
+
assertValidTileflowStyle,
|
|
2406
|
+
compileTileflowIconPackages,
|
|
2407
|
+
createTileflowArtifactDiagnostics,
|
|
2408
|
+
createTileflowArtifactSession,
|
|
2409
|
+
createTileflowArtifactStatus,
|
|
583
2410
|
createTileflowBuildArtifacts,
|
|
584
2411
|
createTileflowDevRequestHandler,
|
|
585
2412
|
createTileflowManifest,
|
|
586
2413
|
createTileflowNodeRequest,
|
|
587
2414
|
createTileflowStyle,
|
|
2415
|
+
createTileflowStyles,
|
|
588
2416
|
defaultTileflowApiUrl,
|
|
589
2417
|
defaultTileflowConfigPath,
|
|
590
2418
|
defaultTileflowManifestPath,
|
|
@@ -595,11 +2423,17 @@ export {
|
|
|
595
2423
|
getTileflowMapNames,
|
|
596
2424
|
getTileflowStyleMapName,
|
|
597
2425
|
getTileflowWatchPaths,
|
|
2426
|
+
iconFileExtensions,
|
|
2427
|
+
inspectTileflowFeatures,
|
|
2428
|
+
inspectTileflowIconCatalogs,
|
|
598
2429
|
isTileflowRequestUrl,
|
|
599
2430
|
joinTileflowPublicUrl,
|
|
600
2431
|
loadTileflowConfig,
|
|
601
2432
|
loadValidTileflowConfig,
|
|
602
2433
|
normalizeTileflowBasePath,
|
|
2434
|
+
prepareTileflowProjectIcons,
|
|
2435
|
+
tileflowArtifactSessionSchemaVersion,
|
|
2436
|
+
validateTileflowStyle,
|
|
603
2437
|
writeTileflowBuildArtifacts,
|
|
604
2438
|
writeTileflowNodeResponse
|
|
605
2439
|
};
|