@tileflow/dev 0.1.0-alpha.18 → 0.1.0-alpha.19

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