Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

export-brand-icons.ts

810 lines25.1 KB

1#!/usr/bin/env node
2​
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
6import * as Console from "effect/Console";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import { Command, Flag } from "effect/cli";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15​
16import { BRAND_ASSET_PATHS, DEVELOPMENT_PUBLIC_ICON_OVERRIDES } from "./lib/brand-assets.ts";
17import { encodePngIco, readPngDimensions, WINDOWS_ICON_SIZES } from "./lib/icon-export.ts";
18​
19const DESIGN_GENERATION = 26;
20const ICON_COMPOSER_EXECUTABLE_PARTS = [
21 "Contents",
22 "Applications",
23 "Icon Composer.app",
24 "Contents",
25 "Executables",
26 "ictool",
27] as const;
28const STANDALONE_ICON_COMPOSER_EXECUTABLE_PARTS = [
29 "Icon Composer.app",
30 "Contents",
31 "Executables",
32 "ictool",
33] as const;
34const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
35​
36const IconComposerVersion = Schema.Struct({
37 "bundle-version": Schema.NonEmptyString,
38 "short-bundle-version": Schema.NonEmptyString,
39});
40const decodeIconComposerVersion = Schema.decodeUnknownEffect(
41 Schema.fromJsonString(IconComposerVersion),
42);
43​
44type IconPlatform = "iOS";
45​
46interface VariantOutputs {
47 readonly ios: string;
48 readonly macos: string;
49 readonly universal: string;
50 readonly appleTouch: string;
51 readonly favicon16: string;
52 readonly favicon32: string;
53 readonly faviconIco: string;
54 readonly windowsIco: string;
56​
57interface IconVariant {
58 readonly label: string;
59 readonly source: string;
60 readonly outputs: VariantOutputs;
62​
63interface IconComposerTool {
64 readonly path: string;
65 readonly version: string;
66 readonly bundleVersion: string;
67 readonly supportsDesignGeneration: boolean;
69​
70interface CommandResult {
71 readonly stdout: string;
72 readonly stderr: string;
73 readonly exitCode: number;
75​
76export class IconExportFileSystemError extends Schema.TaggedError<IconExportFileSystemError>()(
77 "IconExportFileSystemError",
78 {
79 operation: Schema.Literals([
80 "resolve-repository-root",
81 "check-path",
82 "read-directory",
83 "read-file",
84 "make-directory",
85 "make-temp-directory",
86 "make-temp-file",
87 "write-file",
88 "rename-file",
89 ]),
90 path: Schema.String,
91 cause: Schema.Defect(),
92 },
93) {
94 override get message(): string {
95 return `Icon export file-system operation '${this.operation}' failed for ${this.path}.`;
96 }
98​
99export class IconExportProcessError extends Schema.TaggedError<IconExportProcessError>()(
100 "IconExportProcessError",
101 {
102 operation: Schema.Literals(["spawn", "collect-stdout", "collect-stderr", "wait-for-exit"]),
103 command: Schema.String,
104 argumentCount: NonNegativeInt,
105 cause: Schema.Defect(),
106 },
107) {
108 override get message(): string {
109 return `Icon export process operation '${this.operation}' failed for ${this.command}.`;
110 }
112​
113export class IconExportCommandFailedError extends Schema.TaggedError<IconExportCommandFailedError>()(
114 "IconExportCommandFailedError",
115 {
116 command: Schema.String,
117 argumentCount: NonNegativeInt,
118 exitCode: Schema.Int,
119 sourcePath: Schema.String,
120 size: Schema.Int,
121 stdout: Schema.optional(Schema.String),
122 stderr: Schema.optional(Schema.String),
123 },
124) {
125 override get message(): string {
126 return `Icon Composer failed to export ${this.sourcePath} at ${this.size}x${this.size}.`;
127 }
129​
130export class IconExportToolResolutionError extends Schema.TaggedError<IconExportToolResolutionError>()(
131 "IconExportToolResolutionError",
132 {
133 reason: Schema.Literals(["configured-invalid", "configured-outdated", "not-found"]),
134 designGeneration: Schema.Int,
135 toolPath: Schema.optional(Schema.String),
136 version: Schema.optional(Schema.String),
137 },
138) {
139 override get message(): string {
140 switch (this.reason) {
141 case "configured-invalid":
142 return `ICON_COMPOSER_TOOL does not point to Icon Composer's export-capable ictool: ${this.toolPath}`;
143 case "configured-outdated":
144 return `ICON_COMPOSER_TOOL points to Icon Composer ${this.version}, but version 2 or newer is required for design generation ${this.designGeneration}.`;
145 case "not-found":
146 return `Could not find an Icon Composer 2.x exporter compatible with design generation ${this.designGeneration}. Install a compatible Icon Composer/Xcode or set ICON_COMPOSER_TOOL to Icon Composer.app/Contents/Executables/ictool.`;
147 }
148 }
150​
151export class IconExportSourceMissingError extends Schema.TaggedError<IconExportSourceMissingError>()(
152 "IconExportSourceMissingError",
153 {
154 sourcePath: Schema.String,
155 },
156) {
157 override get message(): string {
158 return `Missing Icon Composer source project: ${this.sourcePath}`;
159 }
161​
162export class IconExportRenditionError extends Schema.TaggedError<IconExportRenditionError>()(
163 "IconExportRenditionError",
164 {
165 sourcePath: Schema.String,
166 outputPath: Schema.String,
167 expectedSize: Schema.Int,
168 actualWidth: Schema.optional(Schema.Int),
169 actualHeight: Schema.optional(Schema.Int),
170 cause: Schema.optional(Schema.Defect()),
171 },
172) {
173 override get message(): string {
174 const actual =
175 this.actualWidth === undefined || this.actualHeight === undefined
176 ? "an invalid PNG"
177 : `${this.actualWidth}x${this.actualHeight}`;
178 return `Icon Composer produced ${actual}; expected ${this.expectedSize}x${this.expectedSize} for ${this.sourcePath}.`;
179 }
181​
182export class IconExportEncodingError extends Schema.TaggedError<IconExportEncodingError>()(
183 "IconExportEncodingError",
184 {
185 variant: Schema.String,
186 cause: Schema.Defect(),
187 },
188) {
189 override get message(): string {
190 return `Failed to encode ICO renditions for the ${this.variant} icon.`;
191 }
193​
194export class IconExportAssetsStaleError extends Schema.TaggedError<IconExportAssetsStaleError>()(
195 "IconExportAssetsStaleError",
196 {
197 paths: Schema.Array(Schema.String),
198 },
199) {
200 override get message(): string {
201 return `Generated icon assets are stale:\n${this.paths.map((path) => `- ${path}`).join("\n")}`;
202 }
204​
205const ICON_VARIANTS = [
206 {
207 label: "development",
208 source: BRAND_ASSET_PATHS.developmentIconComposerProject,
209 outputs: {
210 ios: BRAND_ASSET_PATHS.developmentIosIconPng,
211 macos: BRAND_ASSET_PATHS.developmentDesktopIconPng,
212 universal: BRAND_ASSET_PATHS.developmentUniversalIconPng,
213 appleTouch: BRAND_ASSET_PATHS.developmentWebAppleTouchIconPng,
214 favicon16: BRAND_ASSET_PATHS.developmentWebFavicon16Png,
215 favicon32: BRAND_ASSET_PATHS.developmentWebFavicon32Png,
216 faviconIco: BRAND_ASSET_PATHS.developmentWebFaviconIco,
217 windowsIco: BRAND_ASSET_PATHS.developmentWindowsIconIco,
218 },
219 },
220 {
221 label: "preview",
222 source: BRAND_ASSET_PATHS.nightlyIconComposerProject,
223 outputs: {
224 ios: BRAND_ASSET_PATHS.nightlyIosIconPng,
225 macos: BRAND_ASSET_PATHS.nightlyMacIconPng,
226 universal: BRAND_ASSET_PATHS.nightlyLinuxIconPng,
227 appleTouch: BRAND_ASSET_PATHS.nightlyWebAppleTouchIconPng,
228 favicon16: BRAND_ASSET_PATHS.nightlyWebFavicon16Png,
229 favicon32: BRAND_ASSET_PATHS.nightlyWebFavicon32Png,
230 faviconIco: BRAND_ASSET_PATHS.nightlyWebFaviconIco,
231 windowsIco: BRAND_ASSET_PATHS.nightlyWindowsIconIco,
232 },
233 },
234 {
235 label: "production",
236 source: BRAND_ASSET_PATHS.productionIconComposerProject,
237 outputs: {
238 ios: BRAND_ASSET_PATHS.productionIosIconPng,
239 macos: BRAND_ASSET_PATHS.productionMacIconPng,
240 universal: BRAND_ASSET_PATHS.productionLinuxIconPng,
241 appleTouch: BRAND_ASSET_PATHS.productionWebAppleTouchIconPng,
242 favicon16: BRAND_ASSET_PATHS.productionWebFavicon16Png,
243 favicon32: BRAND_ASSET_PATHS.productionWebFavicon32Png,
244 faviconIco: BRAND_ASSET_PATHS.productionWebFaviconIco,
245 windowsIco: BRAND_ASSET_PATHS.productionWindowsIconIco,
246 },
247 },
248] as const satisfies ReadonlyArray<IconVariant>;
249​
250const MACOS_EXPORT_CODEX_PROMPT = [
251 "Use [@Computer](plugin://computer-use@openai-bundled) and the Icon Composer app to export the three macOS app icons in this repository.",
252 "For each project below, use Platform: macOS pre-Tahoe, Appearance: Default, Size: 1024pt, and Scale: 1×, then save the PNG to the exact destination:",
253 ...ICON_VARIANTS.map((variant) => `- ${variant.source} -> ${variant.outputs.macos}`),
254 "Do not resize, composite, or otherwise post-process the exported PNGs.",
255 "Verify every result is 1024×1024 and has the classic macOS safe area: an 824×824 opaque body inset 100px on every side, with only Icon Composer's native shadow extending beyond it.",
256];
257​
258const RepositoryRoot = Effect.service(Path.Path).pipe(
259 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
260 Effect.mapError(
261 (cause) =>
262 new IconExportFileSystemError({
263 operation: "resolve-repository-root",
264 path: new URL("..", import.meta.url).pathname,
265 cause,
266 }),
267 ),
268);
269​
270const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>) =>
271 stream.pipe(
272 Stream.decodeText(),
273 Stream.runFold(
274 () => "",
275 (acc, chunk) => acc + chunk,
276 ),
277 );
278​
279const runCommand = Effect.fn("iconExport.runCommand")(function* (
280 command: string,
281 args: ReadonlyArray<string>,
282) {
283 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
284 const child = yield* spawner.spawn(ChildProcess.make(command, args)).pipe(
285 Effect.mapError(
286 (cause) =>
287 new IconExportProcessError({
288 operation: "spawn",
289 command,
290 argumentCount: args.length,
291 cause,
292 }),
293 ),
294 );
295 const [stdout, stderr, exitCode] = yield* Effect.all(
296 [
297 collectStreamAsString(child.stdout).pipe(
298 Effect.mapError(
299 (cause) =>
300 new IconExportProcessError({
301 operation: "collect-stdout",
302 command,
303 argumentCount: args.length,
304 cause,
305 }),
306 ),
307 ),
308 collectStreamAsString(child.stderr).pipe(
309 Effect.mapError(
310 (cause) =>
311 new IconExportProcessError({
312 operation: "collect-stderr",
313 command,
314 argumentCount: args.length,
315 cause,
316 }),
317 ),
318 ),
319 child.exitCode.pipe(
320 Effect.map(Number),
321 Effect.mapError(
322 (cause) =>
323 new IconExportProcessError({
324 operation: "wait-for-exit",
325 command,
326 argumentCount: args.length,
327 cause,
328 }),
329 ),
330 ),
331 ],
332 { concurrency: "unbounded" },
333 );
334​
335 return { stdout, stderr, exitCode } satisfies CommandResult;
336});
337​
338const iconComposerToolFromDeveloperDirectory = (developerDirectory: string, path: Path.Path) =>
339 path.resolve(developerDirectory, "..", ...ICON_COMPOSER_EXECUTABLE_PARTS.slice(1));
340​
341const readSelectedDeveloperDirectory = Effect.fn("iconExport.readSelectedDeveloperDirectory")(
342 function* () {
343 const result = yield* runCommand("xcode-select", ["-p"]).pipe(Effect.option);
344 return Option.flatMap(result, (output) => {
345 const developerDirectory = output.stdout.trim();
346 return output.exitCode === 0 && developerDirectory.length > 0
347 ? Option.some(developerDirectory)
348 : Option.none();
349 });
350 },
351);
352​
353const findXcodeAppCandidates = Effect.fn("iconExport.findXcodeAppCandidates")(function* (
354 directory: string,
355) {
356 const fs = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const entries = yield* fs.readDirectory(directory).pipe(
359 Effect.mapError(
360 (cause) =>
361 new IconExportFileSystemError({
362 operation: "read-directory",
363 path: directory,
364 cause,
365 }),
366 ),
367 Effect.orElseSucceed(() => []),
368 );
369 return entries
370 .filter((entry) => /^Xcode.*\.app$/.test(entry))
371 .map((entry) => path.join(directory, entry, ...ICON_COMPOSER_EXECUTABLE_PARTS));
372});
373​
374const probeIconComposerTool = Effect.fn("iconExport.probeIconComposerTool")(function* (
375 candidate: string,
376) {
377 const fs = yield* FileSystem.FileSystem;
378 const exists = yield* fs.exists(candidate).pipe(
379 Effect.mapError(
380 (cause) =>
381 new IconExportFileSystemError({
382 operation: "check-path",
383 path: candidate,
384 cause,
385 }),
386 ),
387 Effect.orElseSucceed(() => false),
388 );
389 if (!exists) return Option.none<IconComposerTool>();
390​
391 const result = yield* runCommand(candidate, ["--version"]).pipe(Effect.option);
392 if (Option.isNone(result) || result.value.exitCode !== 0) {
393 return Option.none<IconComposerTool>();
394 }
395​
396 const version = yield* decodeIconComposerVersion(result.value.stdout).pipe(Effect.option);
397 if (Option.isNone(version)) return Option.none<IconComposerTool>();
398​
399 const bundleVersion = version.value["bundle-version"];
400 const shortVersion = version.value["short-bundle-version"];
401 return Option.some({
402 path: candidate,
403 version: `${shortVersion} (${bundleVersion})`,
404 bundleVersion,
405 supportsDesignGeneration: Number.parseInt(shortVersion, 10) >= 2,
406 });
407});
408​
409const resolveIconComposerTool = Effect.fn("iconExport.resolveIconComposerTool")(function* () {
410 const path = yield* Path.Path;
411 const environment = yield* HostProcessEnvironment;
412 const configuredTool = environment.ICON_COMPOSER_TOOL?.trim();
413 if (configuredTool) {
414 const tool = yield* probeIconComposerTool(configuredTool);
415 if (Option.isNone(tool)) {
416 return yield* new IconExportToolResolutionError({
417 reason: "configured-invalid",
418 designGeneration: DESIGN_GENERATION,
419 toolPath: configuredTool,
420 });
421 }
422 if (!tool.value.supportsDesignGeneration) {
423 return yield* new IconExportToolResolutionError({
424 reason: "configured-outdated",
425 designGeneration: DESIGN_GENERATION,
426 toolPath: configuredTool,
427 version: tool.value.version,
428 });
429 }
430 return tool.value;
431 }
432​
433 const selectedDeveloperDirectory = yield* readSelectedDeveloperDirectory();
434 const configuredDeveloperDirectory = environment.DEVELOPER_DIR?.trim();
435 const homeDirectory = environment.HOME?.trim();
436 const searchDirectories = [
437 "/Applications",
438 ...(homeDirectory ? [path.join(homeDirectory, "Downloads")] : []),
439 ];
440 const xcodeCandidates = yield* Effect.forEach(searchDirectories, findXcodeAppCandidates, {
441 concurrency: "unbounded",
442 });
443 const candidates = new Set<string>([
444 ...(configuredDeveloperDirectory
445 ? [iconComposerToolFromDeveloperDirectory(configuredDeveloperDirectory, path)]
446 : []),
447 ...Option.match(selectedDeveloperDirectory, {
448 onNone: () => [],
449 onSome: (developerDirectory) => [
450 iconComposerToolFromDeveloperDirectory(developerDirectory, path),
451 ],
452 }),
453 path.join("/Applications", ...STANDALONE_ICON_COMPOSER_EXECUTABLE_PARTS),
454 ...(homeDirectory
455 ? [path.join(homeDirectory, "Applications", ...STANDALONE_ICON_COMPOSER_EXECUTABLE_PARTS)]
456 : []),
457 ...xcodeCandidates.flat(),
458 ]);
459 const probed = yield* Effect.forEach([...candidates], probeIconComposerTool, {
460 concurrency: "unbounded",
461 });
462 const compatibleTools = probed
463 .filter(Option.isSome)
464 .map((tool) => tool.value)
465 .filter((tool) => tool.supportsDesignGeneration)
466 .sort((left, right) =>
467 right.bundleVersion.localeCompare(left.bundleVersion, undefined, { numeric: true }),
468 );
469 const newestTool = compatibleTools[0];
470 if (newestTool) return newestTool;
471​
472 return yield* new IconExportToolResolutionError({
473 reason: "not-found",
474 designGeneration: DESIGN_GENERATION,
475 });
476});
477​
478const renderIcon = Effect.fn("iconExport.renderIcon")(function* (
479 toolPath: string,
480 sourcePath: string,
481 outputPath: string,
482 platform: IconPlatform,
483 size: number,
484) {
485 const fs = yield* FileSystem.FileSystem;
486 const args = [
487 sourcePath,
488 "--export-image",
489 "--output-file",
490 outputPath,
491 "--platform",
492 platform,
493 "--rendition",
494 "Default",
495 "--width",
496 String(size),
497 "--height",
498 String(size),
499 "--scale",
500 "1",
501 "--design-generation",
502 String(DESIGN_GENERATION),
503 ];
504 const result = yield* runCommand(toolPath, args);
505 if (result.exitCode !== 0) {
506 return yield* new IconExportCommandFailedError({
507 command: toolPath,
508 argumentCount: args.length,
509 exitCode: result.exitCode,
510 sourcePath,
511 size,
512 ...(result.stdout.trim() ? { stdout: result.stdout.trim() } : {}),
513 ...(result.stderr.trim() ? { stderr: result.stderr.trim() } : {}),
514 });
515 }
516​
517 const contents = yield* fs.readFile(outputPath).pipe(
518 Effect.mapError(
519 (cause) =>
520 new IconExportFileSystemError({
521 operation: "read-file",
522 path: outputPath,
523 cause,
524 }),
525 ),
526 );
527 const buffer = Buffer.from(contents);
528 const dimensions = yield* Effect.try({
529 try: () => readPngDimensions(buffer),
530 catch: (cause) =>
531 new IconExportRenditionError({
532 sourcePath,
533 outputPath,
534 expectedSize: size,
535 cause,
536 }),
537 });
538 if (dimensions.width !== size || dimensions.height !== size) {
539 return yield* new IconExportRenditionError({
540 sourcePath,
541 outputPath,
542 expectedSize: size,
543 actualWidth: dimensions.width,
544 actualHeight: dimensions.height,
545 });
546 }
547 return buffer;
548});
549​
550const renderVariant = Effect.fn("iconExport.renderVariant")(function* (
551 toolPath: string,
552 repositoryRoot: string,
553 temporaryDirectory: string,
554 variant: IconVariant,
555) {
556 const fs = yield* FileSystem.FileSystem;
557 const path = yield* Path.Path;
558 const sourcePath = path.join(repositoryRoot, variant.source);
559 const sourceExists = yield* fs.exists(sourcePath).pipe(
560 Effect.mapError(
561 (cause) =>
562 new IconExportFileSystemError({
563 operation: "check-path",
564 path: sourcePath,
565 cause,
566 }),
567 ),
568 );
569 if (!sourceExists) {
570 return yield* new IconExportSourceMissingError({ sourcePath: variant.source });
571 }
572​
573 const renditionCache = new Map<string, Buffer>();
574 const render = Effect.fn("iconExport.renderVariant.rendition")(function* (
575 platform: IconPlatform,
576 size: number,
577 ) {
578 const cacheKey = `${platform}-${size}`;
579 const cached = renditionCache.get(cacheKey);
580 if (cached) return cached;
581​
582 const outputPath = path.join(temporaryDirectory, `${variant.label}-${platform}-${size}.png`);
583 const contents = yield* renderIcon(toolPath, sourcePath, outputPath, platform, size);
584 renditionCache.set(cacheKey, contents);
585 return contents;
586 });
587​
588 const ios = yield* render("iOS", 1024);
589 const icoRenditions = yield* Effect.forEach(
590 WINDOWS_ICON_SIZES,
591 (size) => render("iOS", size).pipe(Effect.map((contents) => ({ size, contents }))),
592 { concurrency: 1 },
593 );
594 const ico = yield* Effect.try({
595 try: () => encodePngIco(icoRenditions),
596 catch: (cause) => new IconExportEncodingError({ variant: variant.label, cause }),
597 });
598​
599 return new Map<string, Buffer>([
600 [variant.outputs.ios, ios],
601 [variant.outputs.universal, ios],
602 [variant.outputs.appleTouch, yield* render("iOS", 180)],
603 [variant.outputs.favicon16, yield* render("iOS", 16)],
604 [variant.outputs.favicon32, yield* render("iOS", 32)],
605 [variant.outputs.faviconIco, ico],
606 [variant.outputs.windowsIco, ico],
607 ]);
608});
609​
610const logManualMacOsExportInstructions = Effect.fn("iconExport.logManualMacOsExportInstructions")(
611 function* () {
612 yield* Console.warn(
613 [
614 "macOS icons require Icon Composer's GUI-only pre-Tahoe preset and were not changed.",
615 "Export each source with Platform: macOS pre-Tahoe, Appearance: Default, Size: 1024pt, Scale: 1×:",
616 ...ICON_VARIANTS.map((variant) => `- ${variant.source} -> ${variant.outputs.macos}`),
617 "See assets/README.md for the complete workflow.",
618 "",
619 "Copy/paste this prompt into Codex to perform the native exports:",
620 "---",
621 ...MACOS_EXPORT_CODEX_PROMPT,
622 "---",
623 ].join("\n"),
624 );
625 },
626);
627​
628const writeAtomically = Effect.fn("iconExport.writeAtomically")(function* (
629 repositoryRoot: string,
630 relativePath: string,
631 contents: Buffer,
632) {
633 const fs = yield* FileSystem.FileSystem;
634 const path = yield* Path.Path;
635 const targetPath = path.join(repositoryRoot, relativePath);
636 const targetDirectory = path.dirname(targetPath);
637 yield* fs.makeDirectory(targetDirectory, { recursive: true }).pipe(
638 Effect.mapError(
639 (cause) =>
640 new IconExportFileSystemError({
641 operation: "make-directory",
642 path: targetDirectory,
643 cause,
644 }),
645 ),
646 );
647 const temporaryPath = yield* fs
648 .makeTempFileScoped({
649 directory: targetDirectory,
650 prefix: ".t3-icon-export-",
651 suffix: ".tmp",
652 })
653 .pipe(
654 Effect.mapError(
655 (cause) =>
656 new IconExportFileSystemError({
657 operation: "make-temp-file",
658 path: targetDirectory,
659 cause,
660 }),
661 ),
662 );
663 yield* fs.writeFile(temporaryPath, contents).pipe(
664 Effect.mapError(
665 (cause) =>
666 new IconExportFileSystemError({
667 operation: "write-file",
668 path: temporaryPath,
669 cause,
670 }),
671 ),
672 );
673 yield* fs.rename(temporaryPath, targetPath).pipe(
674 Effect.mapError(
675 (cause) =>
676 new IconExportFileSystemError({
677 operation: "rename-file",
678 path: targetPath,
679 cause,
680 }),
681 ),
682 );
683});
684​
685const isCurrent = Effect.fn("iconExport.isCurrent")(function* (
686 repositoryRoot: string,
687 relativePath: string,
688 expected: Buffer,
689) {
690 const fs = yield* FileSystem.FileSystem;
691 const path = yield* Path.Path;
692 const targetPath = path.join(repositoryRoot, relativePath);
693 const exists = yield* fs.exists(targetPath).pipe(
694 Effect.mapError(
695 (cause) =>
696 new IconExportFileSystemError({
697 operation: "check-path",
698 path: targetPath,
699 cause,
700 }),
701 ),
702 );
703 if (!exists) return false;
704​
705 const actual = yield* fs.readFile(targetPath).pipe(
706 Effect.mapError(
707 (cause) =>
708 new IconExportFileSystemError({
709 operation: "read-file",
710 path: targetPath,
711 cause,
712 }),
713 ),
714 );
715 return Buffer.from(actual).equals(expected);
716});
717​
718export const exportBrandIcons = Effect.fn("exportBrandIcons")(function* (checkOnly: boolean) {
719 const fs = yield* FileSystem.FileSystem;
720 const repositoryRoot = yield* RepositoryRoot;
721 const tool = yield* resolveIconComposerTool();
722 const temporaryDirectory = yield* fs
723 .makeTempDirectoryScoped({
724 prefix: "t3-icon-export-",
725 })
726 .pipe(
727 Effect.mapError(
728 (cause) =>
729 new IconExportFileSystemError({
730 operation: "make-temp-directory",
731 path: "system temporary directory",
732 cause,
733 }),
734 ),
735 );
736 yield* Console.log(
737 `Exporting icons with Icon Composer ${tool.version}, design generation ${DESIGN_GENERATION}.`,
738 );
739​
740 const generated = new Map<string, Buffer>();
741 for (const variant of ICON_VARIANTS) {
742 yield* Console.log(`Rendering ${variant.label} from ${variant.source}...`);
743 const variantAssets = yield* renderVariant(
744 tool.path,
745 repositoryRoot,
746 temporaryDirectory,
747 variant,
748 );
749 for (const [relativePath, contents] of variantAssets) {
750 generated.set(relativePath, contents);
751 }
752 }
753​
754 for (const override of DEVELOPMENT_PUBLIC_ICON_OVERRIDES) {
755 const sourceContents = generated.get(override.sourceRelativePath);
756 if (sourceContents === undefined) {
757 return yield* Effect.die(
758 new Error(`Generated development web icon is missing: ${override.sourceRelativePath}`),
759 );
760 }
761 generated.set(override.targetRelativePath, sourceContents);
762 }
763​
764 if (checkOnly) {
765 const stale = yield* Effect.filter(
766 [...generated.entries()],
767 ([relativePath, contents]) =>
768 isCurrent(repositoryRoot, relativePath, contents).pipe(Effect.map((current) => !current)),
769 { concurrency: "unbounded" },
770 );
771 if (stale.length > 0) {
772 return yield* new IconExportAssetsStaleError({
773 paths: stale.map(([relativePath]) => relativePath),
774 });
775 }
776 yield* Console.log(`All ${generated.size} generated icon assets are current.`);
777 yield* logManualMacOsExportInstructions();
778 return;
779 }
780​
781 yield* Effect.forEach(
782 generated,
783 ([relativePath, contents]) => writeAtomically(repositoryRoot, relativePath, contents),
784 { concurrency: 1, discard: true },
785 );
786 yield* Console.log(`Updated ${generated.size} generated icon assets.`);
787 yield* logManualMacOsExportInstructions();
788});
789​
790export const exportBrandIconsCommand = Command.make(
791 "export-brand-icons",
792 {
793 check: Flag.Boolean("check").pipe(
794 Flag.withDescription("Verify generated icon assets without modifying files."),
795 Flag.withDefault(false),
796 ),
797 },
798 ({ check }) => exportBrandIcons(check).pipe(Effect.scoped),
799).pipe(
800 Command.withDescription(
801 "Export development, preview, and production assets from Icon Composer projects.",
802 ),
803);
804​
805if (import.meta.main) {
806 Command.run(exportBrandIconsCommand, { version: "0.0.0" }).pipe(
807 Effect.provide(NodeServices.layer),
808 NodeRuntime.runMain,
809 );