@openfairygui/functions 0.2.0-alpha.3 → 0.2.0-alpha.31

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 (55) hide show
  1. package/README.md +50 -6
  2. package/dist/atlas-C6tbl7nn.d.ts +193 -0
  3. package/dist/atlas-CHsu2Y8i.d.cts +193 -0
  4. package/dist/index.cjs +16 -3603
  5. package/dist/index.d.cts +5 -294
  6. package/dist/index.d.ts +5 -294
  7. package/dist/index.js +3 -3594
  8. package/dist/node.cjs +256 -0
  9. package/dist/node.d.cts +36 -0
  10. package/dist/node.d.ts +36 -0
  11. package/dist/node.js +254 -0
  12. package/dist/publish-BJk8UzRP.js +3246 -0
  13. package/dist/publish-DCP0AYx2.cjs +3335 -0
  14. package/dist/restore-BUaCK8ui.cjs +911 -0
  15. package/dist/restore-BeWaJNjR.d.cts +288 -0
  16. package/dist/restore-C98ugT2H.js +906 -0
  17. package/dist/restore-Dh0-Nvms.d.ts +288 -0
  18. package/dist/uam-transaction.cjs +44 -1
  19. package/dist/uam-transaction.d.cts +16 -1
  20. package/dist/uam-transaction.d.ts +16 -1
  21. package/dist/uam-transaction.js +44 -1
  22. package/dist/web.cjs +274 -0
  23. package/dist/web.d.cts +41 -0
  24. package/dist/web.d.ts +41 -0
  25. package/dist/web.js +273 -0
  26. package/package.json +28 -4
  27. package/src/adapters/node/plugins.ts +82 -0
  28. package/src/adapters/node/publish.ts +130 -0
  29. package/src/adapters/node/restore.ts +187 -0
  30. package/src/adapters/web/publish.ts +159 -0
  31. package/src/adapters/web/raster.ts +251 -0
  32. package/src/atlas/font.ts +95 -0
  33. package/src/atlas/inputs.ts +480 -0
  34. package/src/atlas/jta.ts +211 -0
  35. package/src/atlas/packing.ts +762 -0
  36. package/src/atlas.ts +118 -1221
  37. package/src/codegen.ts +108 -82
  38. package/src/index.ts +43 -3
  39. package/src/node.ts +8 -0
  40. package/src/path-utils.ts +40 -0
  41. package/src/plugins/types.ts +56 -0
  42. package/src/publish/contracts.ts +80 -0
  43. package/src/publish/external-resources.ts +117 -0
  44. package/src/publish/options.ts +180 -0
  45. package/src/publish/package-context.ts +608 -0
  46. package/src/publish/resource-references.ts +210 -0
  47. package/src/publish.ts +286 -977
  48. package/src/restore-internals/font.ts +100 -0
  49. package/src/restore-internals/movie-clip.ts +104 -0
  50. package/src/restore-internals/output-transaction.ts +124 -0
  51. package/src/restore.ts +112 -311
  52. package/src/shared-types.ts +4 -8
  53. package/src/uam-transaction.ts +68 -0
  54. package/src/utils.ts +28 -0
  55. package/src/web.ts +11 -0
package/src/publish.ts CHANGED
@@ -1,282 +1,86 @@
1
1
  import {
2
- type BinaryWriterOptions,
3
2
  BinaryWriter,
4
- type Component,
5
- type DragonBonesResource,
3
+ type BinaryWriterOptions,
6
4
  type Document,
7
5
  type FileSystem,
8
- type FontResource,
9
- type ImageResource,
10
- type MiscResource,
11
- type MovieClipResource,
12
6
  type Package,
13
- ProjectType,
14
- type SpineResource,
15
- type SoundResource,
16
7
  type Transform,
17
8
  } from '@openfairygui/core';
9
+ import { atlas } from './atlas.js';
10
+ import { publishCodeGeneration, resolveProjectBasePath } from './codegen.js';
11
+ import { dirname, isAbsolutePathLike, trimTrailingSlashes } from './path-utils.js';
12
+ import { formatPluginError, type LoadedPlugin } from './plugins/types.js';
13
+ import type { PublishFileSystem } from './publish/contracts.js';
14
+ import {
15
+ annotatePackagePublishArtifacts,
16
+ } from './publish/package-context.js';
17
+ import {
18
+ exportPackageExternalResources,
19
+ exportPackageSounds,
20
+ } from './publish/external-resources.js';
21
+ import {
22
+ resolvePublishAtlasRuntimeOptions,
23
+ resolvePublishFileName,
24
+ resolvePublishOptions,
25
+ type PublishOptions,
26
+ type ResolvedPublishAtlasOptions,
27
+ type ResolvedPublishOptions,
28
+ } from './publish/options.js';
29
+ import { collectPackageResourceReferences } from './publish/resource-references.js';
30
+ import type { CliPublishSettings, RootProjectSettings } from './shared-types.js';
18
31
  import { createTransform } from './utils.js';
19
- import { atlas, type AtlasOptions } from './atlas.js';
20
- import { publishCodeGeneration } from './codegen.js';
21
- import type {
22
- CliPublishSettings,
23
- HasOptionalFont,
24
- PackagePublishArtifactsExtras,
25
- PublishFileSystem,
26
- RootProjectSettings,
27
- } from './shared-types.js';
28
-
29
- export interface PublishOptions {
30
- /**
31
- * Output directory for published files (.fui + atlas PNGs).
32
- * Required.
33
- */
34
- output: string;
35
-
36
- /**
37
- * Compress the binary data with zlib raw deflate. Default: false.
38
- */
39
- compressed?: boolean;
40
-
41
- /**
42
- * File extension for the binary output. Default: 'fui'.
43
- * Unity projects typically use 'bytes'.
44
- */
45
- fileExtension?: string;
46
-
47
- /**
48
- * Sharp module instance for atlas image compositing.
49
- * If not provided, atlas packing only computes layout (no PNGs generated).
50
- */
51
- encoder?: unknown;
52
-
53
- /**
54
- * Base path for reading source images (project assets root).
55
- * Required when encoder is provided.
56
- */
57
- basePath?: string;
58
32
 
59
- /**
60
- * Atlas packing options.
61
- */
62
- atlas?: Omit<AtlasOptions, 'encoder' | 'basePath' | 'outputPath'>;
33
+ export * from './publish/options.js';
63
34
 
64
- /**
65
- * Filter which packages to publish by name. If not set, all packages are published.
66
- */
67
- packages?: string[];
68
-
69
- /**
70
- * FileSystem abstraction for writing output files.
71
- * Required for actual file output. Without it, only the Document model
72
- * is updated (atlas layout computed, sprite nodes created).
73
- */
74
- fs?: PublishFileSystem;
75
-
76
- /**
77
- * Active branch name used when branchProcessing is "主干合并活跃分支".
78
- * Empty or omitted means publishing the main branch.
79
- */
80
- branch?: string;
81
- }
82
-
83
- export interface ResolvedPublishAtlasOptions extends Pick<AtlasOptions, 'maxSize' | 'fast' | 'allowRotation' | 'padding' | 'powerOfTwo' | 'square' | 'multiPage' | 'trimImage' | 'extractAlpha'> {}
84
-
85
- export interface ResolvePublishOptionsOverrides {
86
- compressed?: boolean;
87
- fileExtension?: string;
88
- packages?: string[];
89
- atlas?: Partial<ResolvedPublishAtlasOptions>;
90
- }
91
-
92
- export interface ResolvedPublishOptions {
35
+ interface ResolvedProjectPublishConfig extends ResolvedPublishOptions {
36
+ projectType: number;
37
+ includeBranches: boolean;
38
+ activeBranch: string;
39
+ includeHighResolution: number;
40
+ separatedAtlasForBranch: boolean;
41
+ globalOutputPath: string;
42
+ globalBranchOutputPath: string;
43
+ }
44
+
45
+ interface ResolvedPackagePublishPlan {
46
+ pkg: Package;
47
+ outputDir?: string;
48
+ publishName: string;
49
+ fileName: string;
93
50
  compressed: boolean;
94
51
  fileExtension: string;
95
- packages?: string[];
96
- atlas: ResolvedPublishAtlasOptions;
97
- }
98
-
99
- interface ImageResourceExtras extends Record<string, unknown> {
100
- _fileName?: string;
101
- }
102
-
103
- interface PublishFileExtras extends Record<string, unknown> {
104
- _publishedFile?: string;
105
- _publishedId?: string;
106
- }
107
-
108
- interface BranchAwarePublishedResource {
109
- getBranch?(): string;
110
- }
111
-
112
- interface PackagePublishContext {
113
- referencedIds: Set<string>;
114
- publishedResourceIds: Set<string>;
115
- pixelHitTestImageIds: Set<string>;
116
- effectiveResourceIds: Map<string, string>;
117
52
  includeBranches: boolean;
53
+ activeBranch: string;
54
+ includeHighResolution: number;
55
+ separatedAtlasForBranch: boolean;
56
+ atlas: ResolvedPublishAtlasOptions;
118
57
  }
119
58
 
120
- interface ChildReferenceItem {
121
- icon?: string | null;
122
- url?: string | null;
123
- }
124
-
125
- interface GearWithPublishRefs {
126
- getValues?(): string;
127
- getDefaultValue?(): unknown;
128
- }
129
-
130
- interface TransitionItemWithPublishRefs {
131
- getStartValue?(): unknown;
132
- getEndValue?(): unknown;
133
- }
134
-
135
- interface TransitionWithPublishRefs {
136
- listItems?(): TransitionItemWithPublishRefs[];
137
- }
138
-
139
- interface ChildWithPublishRefs extends HasOptionalFont {
140
- getId?(): string;
141
- getSrc?(): string;
142
- getUrl?(): string;
143
- getDefaultItem?(): string;
144
- getIcon?(): string;
145
- getSelectedIcon?(): string;
146
- getDropdown?(): string;
147
- getSound?(): string;
148
- getText?(): string;
149
- getInstanceIcon?(): string;
150
- getInstanceSelectedIcon?(): string;
151
- getVtScrollBarRes?(): string;
152
- getHzScrollBarRes?(): string;
153
- getHeaderRes?(): string;
154
- getFooterRes?(): string;
155
- getInstanceComboItems?(): Array<{ icon: string | null }>;
156
- getListItems?(): ChildReferenceItem[];
157
- listGears?(): GearWithPublishRefs[];
158
- }
159
-
160
- interface ComponentWithPublishRefs {
161
- getId(): string;
162
- getExported(): boolean;
163
- listChildren(): ChildWithPublishRefs[];
164
- getHitTest?(): string;
165
- getDropdown?(): string;
166
- getHeaderRes?(): string;
167
- getFooterRes?(): string;
168
- getVtScrollBarRes?(): string;
169
- getHzScrollBarRes?(): string;
170
- getSound?(): string;
171
- getFont?(): string | string[] | null | undefined;
172
- listTransitions?(): TransitionWithPublishRefs[];
173
- }
174
-
175
- interface PublishEncoderMetadata {
176
- width?: number;
177
- height?: number;
178
- channels?: number;
179
- }
180
-
181
- interface PublishEncoderResolvedBuffer {
182
- data: Uint8Array;
183
- info: Required<Pick<PublishEncoderMetadata, 'width' | 'height' | 'channels'>> & PublishEncoderMetadata;
184
- }
185
-
186
- interface PublishEncoderPipeline {
187
- ensureAlpha(): PublishEncoderPipeline;
188
- resize(options: { width: number; height: number; fit: 'fill' }): PublishEncoderPipeline;
189
- raw(): PublishEncoderPipeline;
190
- toBuffer(options: { resolveWithObject: true }): Promise<PublishEncoderResolvedBuffer>;
191
- metadata(): Promise<PublishEncoderMetadata>;
192
- }
193
-
194
- type PublishEncoder = (input: string | Uint8Array) => PublishEncoderPipeline;
195
-
196
- const UNITY_PROJECT_TYPE = ProjectType.Unity;
197
- const COCOS_CREATOR_PROJECT_TYPE = ProjectType.CocosCreator;
198
-
199
- function resolveDefaultPublishFileExtension(projectType: number, publishSettings: CliPublishSettings): string {
200
- if (projectType === UNITY_PROJECT_TYPE) {
201
- return 'bytes';
202
- }
203
- if (projectType === COCOS_CREATOR_PROJECT_TYPE) {
204
- return publishSettings.fileExtension || 'bin';
205
- }
206
- // publish() is currently a binary forward-publish path. For non-Unity projects,
207
- // keep the emitted contract driven by the configured extension, falling back to
208
- // `fui`, which intentionally covers the shared generic binary contract outside
209
- // Unity and the Creator-specific default-to-bin rule.
210
- return publishSettings.fileExtension || 'fui';
211
- }
212
-
213
- export interface PublishAtlasRuntimeOptions {
214
- preserveInputOrderOnTie: boolean;
215
- directSingleImageOutput: boolean;
216
- }
217
-
218
- export function resolvePublishAtlasRuntimeOptions(fileExtension: string): PublishAtlasRuntimeOptions {
219
- return {
220
- preserveInputOrderOnTie: fileExtension === 'fui',
221
- directSingleImageOutput: fileExtension === 'bytes',
222
- };
223
- }
224
-
225
- function resolvePublishFileName(publishName: string, fileExtension: string): string {
226
- if (fileExtension === 'bytes') {
227
- return `${publishName}_fui.bytes`;
228
- }
229
- return `${publishName}.${fileExtension}`;
230
- }
231
-
232
- /**
233
- * Resolve publish defaults from the document's project settings.
234
- *
235
- * This keeps the editor-aligned publish rules reusable across environments,
236
- * while callers still provide environment-specific concerns such as fs/encoder/basePath.
237
- */
238
- export function resolvePublishOptions(
59
+ async function runPublishPluginHook(
60
+ plugins: LoadedPlugin[],
61
+ hook: 'onPublishStart' | 'onPublishEnd',
239
62
  doc: Document,
240
- overrides: ResolvePublishOptionsOverrides = {},
241
- ): ResolvedPublishOptions {
242
- const root = doc.getRoot();
243
- const settings = (root.getSettings?.() ?? {}) as RootProjectSettings;
244
- const publishSettings: CliPublishSettings = settings.publish ?? {};
245
- const atlasSetting = publishSettings.atlasSetting ?? {};
246
- const projectType = root.getProjectType();
247
-
248
- const fileExtension = overrides.fileExtension
249
- ?? resolveDefaultPublishFileExtension(projectType, publishSettings);
250
-
251
- let compressed = overrides.compressed ?? publishSettings.compressDesc ?? false;
252
- if (projectType === UNITY_PROJECT_TYPE) {
253
- compressed = overrides.compressed ?? false;
63
+ options: PublishOptions,
64
+ ): Promise<void> {
65
+ const logger = doc.getLogger();
66
+ for (const plugin of plugins) {
67
+ const fn = plugin.plugin[hook];
68
+ if (typeof fn !== 'function') continue;
69
+ try {
70
+ await fn(doc, options);
71
+ } catch (error) {
72
+ logger.warn(`publish: Plugin "${plugin.name}" ${hook} failed: ${formatPluginError(error)}`);
73
+ }
254
74
  }
255
-
256
- const atlasOptions: ResolvedPublishAtlasOptions = {
257
- maxSize: overrides.atlas?.maxSize ?? atlasSetting.maxSize ?? 2048,
258
- fast: overrides.atlas?.fast ?? atlasSetting.fast ?? true,
259
- allowRotation: overrides.atlas?.allowRotation ?? atlasSetting.allowRotation ?? false,
260
- padding: overrides.atlas?.padding ?? atlasSetting.padding ?? 2,
261
- powerOfTwo: overrides.atlas?.powerOfTwo ?? atlasSetting.sizeOption === 'pot',
262
- square: overrides.atlas?.square ?? atlasSetting.forceSquare ?? false,
263
- multiPage: overrides.atlas?.multiPage ?? atlasSetting.paging ?? true,
264
- trimImage: overrides.atlas?.trimImage ?? atlasSetting.trimImage ?? false,
265
- extractAlpha: overrides.atlas?.extractAlpha ?? atlasSetting.extractAlpha ?? false,
266
- };
267
-
268
- return {
269
- compressed,
270
- fileExtension,
271
- packages: overrides.packages,
272
- atlas: atlasOptions,
273
- };
274
75
  }
275
76
 
276
- function dirname(filePath: string): string {
277
- const trimmed = filePath.replace(/[/\\]+$/, '');
278
- const match = trimmed.match(/^(.*)[/\\][^/\\]+$/);
279
- return match?.[1] ?? '';
77
+ function joinPathSegments(left: string, right: string): string {
78
+ const normalizedLeft = trimTrailingSlashes(left);
79
+ const normalizedRight = right.replace(/^[/\\]+/, '');
80
+ if (!normalizedLeft) return normalizedRight;
81
+ if (!normalizedRight) return normalizedLeft;
82
+ const separator = normalizedLeft.includes('\\') ? '\\' : '/';
83
+ return `${normalizedLeft}${separator}${normalizedRight}`;
280
84
  }
281
85
 
282
86
  function createUnsupportedFsOperation(name: keyof FileSystem) {
@@ -299,650 +103,181 @@ function toBinaryWriterFileSystem(fs: PublishFileSystem): FileSystem {
299
103
  };
300
104
  }
301
105
 
302
- function isComponentResource(resource: ReturnType<Package['listResources']>[number]): resource is Component {
303
- return resource.propertyType === 'Component';
304
- }
305
-
306
- function isImageResource(resource: ReturnType<Package['listResources']>[number]): resource is ImageResource {
307
- return resource.propertyType === 'ImageResource';
308
- }
309
-
310
- function isMovieClipResource(resource: ReturnType<Package['listResources']>[number]): resource is MovieClipResource {
311
- return resource.propertyType === 'MovieClipResource';
312
- }
313
-
314
- function isMiscResource(resource: ReturnType<Package['listResources']>[number]): resource is MiscResource {
315
- return resource.propertyType === 'MiscResource';
316
- }
317
-
318
- function isFontResource(resource: ReturnType<Package['listResources']>[number]): resource is FontResource {
319
- return resource.propertyType === 'FontResource';
320
- }
321
-
322
- function isSoundResource(resource: ReturnType<Package['listResources']>[number]): resource is SoundResource {
323
- return resource.propertyType === 'SoundResource';
324
- }
325
-
326
- function isSpineResource(resource: ReturnType<Package['listResources']>[number]): resource is SpineResource {
327
- return resource.propertyType === 'SpineResource';
328
- }
329
-
330
- function isDragonBonesResource(resource: ReturnType<Package['listResources']>[number]): resource is DragonBonesResource {
331
- return resource.propertyType === 'DragonBonesResource';
332
- }
333
-
334
- function isSkeletonResource(
335
- resource: ReturnType<Package['listResources']>[number],
336
- ): resource is SpineResource | DragonBonesResource {
337
- return isSpineResource(resource) || isDragonBonesResource(resource);
338
- }
339
-
340
- function addLocalUiResourceRef(target: Set<string>, pkgId: string, value: string | null | undefined): void {
341
- if (!value || typeof value !== 'string' || !value.startsWith(`ui://${pkgId}`) || value.length <= 13) return;
342
- target.add(value.slice(13));
343
- }
344
-
345
- function addLocalUiResourceRefsFromText(target: Set<string>, pkgId: string, value: string | null | undefined): void {
346
- if (!value || typeof value !== 'string') return;
347
- const prefix = `ui://${pkgId}`;
348
- let index = value.indexOf(prefix);
349
- while (index !== -1) {
350
- const start = index + prefix.length;
351
- let end = start;
352
- while (end < value.length && /[0-9a-z]/i.test(value[end] ?? '')) end++;
353
- if (end > start) target.add(value.slice(start, end));
354
- index = value.indexOf(prefix, end);
355
- }
356
- }
357
-
358
- function addLocalUiResourceRefsFromUnknown(target: Set<string>, pkgId: string, value: unknown): void {
359
- if (Array.isArray(value)) {
360
- for (const entry of value) addLocalUiResourceRefsFromUnknown(target, pkgId, entry);
361
- return;
362
- }
363
- if (typeof value === 'string') {
364
- addLocalUiResourceRef(target, pkgId, value);
365
- addLocalUiResourceRefsFromText(target, pkgId, value);
366
- }
367
- }
368
-
369
- function addLocalFontRef(target: Set<string>, pkgId: string, value: string | string[] | null | undefined): void {
370
- if (Array.isArray(value)) {
371
- for (const entry of value) addLocalUiResourceRef(target, pkgId, entry);
372
- return;
373
- }
374
- addLocalUiResourceRef(target, pkgId, value ?? undefined);
375
- }
376
-
377
- function resolvePackageAssetsBasePath(
378
- basePath: string,
379
- resource: BranchAwarePublishedResource | undefined,
380
- ): string {
381
- const branchName = resource?.getBranch?.() ?? '';
382
- if (!branchName) return basePath;
383
- const normalized = basePath.replace(/[/\\]+$/, '');
384
- if (/[\\/]assets$/i.test(normalized)) {
385
- return normalized.replace(/([\\/])assets$/i, `$1assets_${branchName}`);
386
- }
387
- return `${normalized}_${branchName}`;
388
- }
389
-
390
- function resolveImagePath(resource: ImageResource, pkg: Package, basePath: string): string {
391
- const fileName = resolveImageFileName(resource);
392
- const resourcePath = resource.getPath() ?? '/';
393
- const packageBasePath = resolvePackageAssetsBasePath(basePath, resource);
394
- return `${packageBasePath}/${pkg.getName()}${resourcePath}${fileName}`;
395
- }
396
-
397
- function resolveImageFileName(resource: ImageResource): string {
398
- const extras = (resource.getExtras() as ImageResourceExtras | undefined) ?? {};
399
- return resource.getFileName() || extras._fileName || resource.getName();
400
- }
401
-
402
- function resolveSoundPath(resource: SoundResource, pkg: Package, basePath: string): string {
403
- const resourcePath = resource.getPath() ?? '/';
404
- const packageBasePath = resolvePackageAssetsBasePath(basePath, resource);
405
- return `${packageBasePath}/${pkg.getName()}${resourcePath}${resource.getFile()}`;
406
- }
407
-
408
- function resolveGenericResourcePath(
409
- resource: { getPath(): string; getFile(): string; getBranch?(): string },
410
- pkg: Package,
411
- basePath: string,
412
- ): string {
413
- const resourcePath = resource.getPath() ?? '/';
414
- const packageBasePath = resolvePackageAssetsBasePath(basePath, resource);
415
- return `${packageBasePath}/${pkg.getName()}${resourcePath}${resource.getFile()}`;
416
- }
417
-
418
- function extname(fileName: string): string {
419
- const normalized = fileName.replace(/\\/g, '/');
420
- const lastSlash = normalized.lastIndexOf('/');
421
- const lastDot = normalized.lastIndexOf('.');
422
- if (lastDot <= lastSlash) return '';
423
- return normalized.slice(lastDot);
424
- }
425
-
426
- function resolvePublishedMiscFileName(resource: MiscResource): string {
427
- const file = resource.getFile();
428
- if (file.toLowerCase().endsWith('.atlas')) return `${file}.txt`;
429
- return file;
430
- }
431
-
432
- function resolvePublishedSkeletonFileName(resource: SpineResource | DragonBonesResource): string {
433
- if (isSpineResource(resource) && resource.getFile().toLowerCase().endsWith('.skel')) {
434
- return `${resource.getFile()}.bytes`;
435
- }
436
- return resource.getFile();
437
- }
438
-
439
- function setPublishedFileExtra(
440
- resource: { getExtras(): Record<string, unknown> | undefined; setExtras(value: Record<string, unknown>): unknown },
441
- fileName: string,
442
- ): void {
443
- const extras = (resource.getExtras() as PublishFileExtras | undefined) ?? {};
444
- resource.setExtras({
445
- ...extras,
446
- _publishedFile: fileName,
447
- });
448
- }
449
-
450
- function setPublishedIdExtra(
451
- resource: { getId(): string; getExtras(): Record<string, unknown> | undefined; setExtras(value: Record<string, unknown>): unknown },
452
- effectiveId: string | null,
453
- ): void {
454
- const extras = (resource.getExtras() as PublishFileExtras | undefined) ?? {};
455
- if (!effectiveId || effectiveId === resource.getId()) {
456
- if (!('_publishedId' in extras)) return;
457
- const { _publishedId: _ignored, ...rest } = extras;
458
- resource.setExtras(rest);
459
- return;
460
- }
461
- resource.setExtras({
462
- ...extras,
463
- _publishedId: effectiveId,
464
- });
465
- }
466
-
467
- function getPublishedId(resource: { getId(): string; getExtras(): Record<string, unknown> | undefined }): string {
468
- const extras = (resource.getExtras() as PublishFileExtras | undefined) ?? {};
469
- return extras._publishedId ?? resource.getId();
470
- }
471
-
472
- function getBranchName(resource: BranchAwarePublishedResource | undefined): string {
473
- return resource?.getBranch?.() ?? '';
474
- }
475
-
476
- function buildBranchResourceKey(resource: {
477
- propertyType: string;
478
- getPath(): string;
479
- getName(): string;
480
- }): string {
481
- return `${resource.propertyType}|${resource.getPath() ?? ''}|${resource.getName() ?? ''}`;
482
- }
483
-
484
- function collectPackagePublishContext(
485
- pkg: Package,
486
- options: {
487
- includeBranches: boolean;
488
- activeBranch: string;
489
- },
490
- ): PackagePublishContext {
491
- const pkgId = pkg.getId();
492
- const resources = pkg.listResources();
493
- const resourceMap = new Map(resources.map((resource) => [resource.getId(), resource]));
494
- const referencedIds = new Set<string>();
495
- const pixelHitTestImageIds = new Set<string>();
496
- const spriteItemIds = new Set<string>();
497
-
498
- for (const atlas of pkg.listAtlases()) {
499
- for (const sprite of atlas.listSprites()) {
500
- spriteItemIds.add(sprite.getItemId());
501
- }
502
- }
503
-
504
- for (const resource of resources) {
505
- if (!isComponentResource(resource)) continue;
506
- const component = resource as ComponentWithPublishRefs;
507
- const children = component.listChildren();
508
- const childMap = new Map(children.map((child) => [child.getId?.() ?? '', child]));
509
-
510
- const hitTest = component.getHitTest?.()?.trim();
511
- if (hitTest && !hitTest.includes(',')) {
512
- const targetChild = childMap.get(hitTest);
513
- const sourceId = targetChild?.getSrc?.();
514
- if (sourceId) {
515
- const sourceResource = resourceMap.get(sourceId);
516
- if (sourceResource && isImageResource(sourceResource)) {
517
- pixelHitTestImageIds.add(sourceId);
518
- }
519
- }
520
- }
521
-
522
- for (const child of children) {
523
- const src = child.getSrc?.();
524
- if (src) referencedIds.add(src);
525
- addLocalFontRef(referencedIds, pkgId, child.getFont?.());
526
- addLocalUiResourceRefsFromText(referencedIds, pkgId, child.getText?.());
527
- for (const ref of [
528
- child.getUrl?.(),
529
- child.getDefaultItem?.(),
530
- child.getIcon?.(),
531
- child.getSelectedIcon?.(),
532
- child.getDropdown?.(),
533
- child.getSound?.(),
534
- child.getInstanceIcon?.(),
535
- child.getInstanceSelectedIcon?.(),
536
- child.getVtScrollBarRes?.(),
537
- child.getHzScrollBarRes?.(),
538
- child.getHeaderRes?.(),
539
- child.getFooterRes?.(),
540
- ]) {
541
- addLocalUiResourceRef(referencedIds, pkgId, ref);
542
- }
543
- for (const item of child.getInstanceComboItems?.() ?? []) {
544
- addLocalUiResourceRef(referencedIds, pkgId, item.icon ?? undefined);
545
- }
546
- for (const item of child.getListItems?.() ?? []) {
547
- addLocalUiResourceRef(referencedIds, pkgId, item.icon ?? undefined);
548
- addLocalUiResourceRef(referencedIds, pkgId, item.url ?? undefined);
549
- }
550
- for (const gear of child.listGears?.() ?? []) {
551
- addLocalUiResourceRefsFromUnknown(referencedIds, pkgId, gear.getValues?.());
552
- addLocalUiResourceRefsFromUnknown(referencedIds, pkgId, gear.getDefaultValue?.());
553
- }
554
- }
555
-
556
- addLocalFontRef(referencedIds, pkgId, component.getFont?.());
557
- for (const ref of [
558
- component.getDropdown?.(),
559
- component.getHeaderRes?.(),
560
- component.getFooterRes?.(),
561
- component.getVtScrollBarRes?.(),
562
- component.getHzScrollBarRes?.(),
563
- component.getSound?.(),
564
- ]) {
565
- addLocalUiResourceRef(referencedIds, pkgId, ref);
566
- }
567
- for (const transition of component.listTransitions?.() ?? []) {
568
- for (const item of transition.listItems?.() ?? []) {
569
- addLocalUiResourceRefsFromUnknown(referencedIds, pkgId, item.getStartValue?.());
570
- addLocalUiResourceRefsFromUnknown(referencedIds, pkgId, item.getEndValue?.());
571
- }
572
- }
573
- }
574
-
575
- const publishedResourceIds = new Set<string>(spriteItemIds);
576
- for (const resource of resources) {
577
- const resourceId = resource.getId();
578
- if (!resourceId) continue;
579
- if (isComponentResource(resource)) {
580
- if (resource.getExported() || referencedIds.has(resourceId)) {
581
- publishedResourceIds.add(resourceId);
582
- }
583
- continue;
584
- }
585
- if (isImageResource(resource)) {
586
- if (resource.getExported() || referencedIds.has(resourceId) || spriteItemIds.has(resourceId) || pixelHitTestImageIds.has(resourceId)) {
587
- publishedResourceIds.add(resourceId);
588
- }
589
- continue;
590
- }
591
- if (isMovieClipResource(resource) || isSoundResource(resource)) {
592
- if (resource.getExported() || referencedIds.has(resourceId)) publishedResourceIds.add(resourceId);
593
- continue;
594
- }
595
- if (isMiscResource(resource) || isSkeletonResource(resource)) {
596
- if (resource.getExported() || referencedIds.has(resourceId)) publishedResourceIds.add(resourceId);
597
- continue;
598
- }
599
- if (isFontResource(resource)) {
600
- if (resource.getExported() || referencedIds.has(resourceId)) {
601
- publishedResourceIds.add(resourceId);
602
- }
603
- continue;
604
- }
605
- const genericResource = resource as ReturnType<Package['listResources']>[number];
606
- if (genericResource.getExported() || referencedIds.has(resourceId)) {
607
- publishedResourceIds.add(resourceId);
608
- }
609
- }
610
-
611
- let changed = true;
612
- while (changed) {
613
- changed = false;
614
- for (const resource of resources) {
615
- if (!isSkeletonResource(resource)) continue;
616
- if (!publishedResourceIds.has(resource.getId())) continue;
617
- for (const requiredId of resource.getRequireIds()) {
618
- if (!requiredId || publishedResourceIds.has(requiredId)) continue;
619
- publishedResourceIds.add(requiredId);
620
- changed = true;
621
- }
622
- }
623
- }
624
-
625
- if (!options.includeBranches) {
626
- const mainByKey = new Map<string, ReturnType<Package['listResources']>[number]>();
627
- const activeBranchByKey = new Map<string, ReturnType<Package['listResources']>[number]>();
628
- for (const resource of resources) {
629
- const branchName = getBranchName(resource);
630
- const key = buildBranchResourceKey(resource);
631
- if (!branchName) {
632
- mainByKey.set(key, resource);
633
- } else if (branchName === options.activeBranch) {
634
- activeBranchByKey.set(key, resource);
635
- }
636
- }
637
-
638
- const mergedPublishedResourceIds = new Set<string>();
639
- const effectiveResourceIds = new Map<string, string>();
640
- for (const resource of resources) {
641
- const resourceId = resource.getId();
642
- if (!publishedResourceIds.has(resourceId)) continue;
643
-
644
- const branchName = getBranchName(resource);
645
- const key = buildBranchResourceKey(resource);
646
- if (branchName) {
647
- if (branchName !== options.activeBranch) continue;
648
- const mainResource = mainByKey.get(key);
649
- mergedPublishedResourceIds.add(resourceId);
650
- effectiveResourceIds.set(resourceId, mainResource?.getId() ?? resourceId);
651
- continue;
652
- }
653
-
654
- const override = activeBranchByKey.get(key);
655
- if (override) {
656
- mergedPublishedResourceIds.add(override.getId());
657
- effectiveResourceIds.set(override.getId(), resourceId);
658
- continue;
659
- }
660
-
661
- mergedPublishedResourceIds.add(resourceId);
662
- effectiveResourceIds.set(resourceId, resourceId);
663
- }
664
-
665
- publishedResourceIds.clear();
666
- for (const resourceId of mergedPublishedResourceIds) {
667
- publishedResourceIds.add(resourceId);
668
- }
669
-
670
- const mergedPixelHitTestImageIds = new Set<string>();
671
- for (const resource of resources) {
672
- if (!isImageResource(resource)) continue;
673
- const resourceId = resource.getId();
674
- if (!publishedResourceIds.has(resourceId)) continue;
675
- const effectiveId = effectiveResourceIds.get(resourceId) ?? resourceId;
676
- if (pixelHitTestImageIds.has(effectiveId)) {
677
- mergedPixelHitTestImageIds.add(resourceId);
678
- }
679
- }
680
- pixelHitTestImageIds.clear();
681
- for (const resourceId of mergedPixelHitTestImageIds) {
682
- pixelHitTestImageIds.add(resourceId);
683
- }
684
-
685
- return {
686
- referencedIds,
687
- publishedResourceIds,
688
- pixelHitTestImageIds,
689
- effectiveResourceIds,
690
- includeBranches: false,
691
- };
692
- }
693
-
694
- return {
695
- referencedIds,
696
- publishedResourceIds,
697
- pixelHitTestImageIds,
698
- effectiveResourceIds: new Map([...publishedResourceIds].map((resourceId) => [resourceId, resourceId])),
699
- includeBranches: true,
700
- };
701
- }
702
-
703
- async function applyPixelHitTests(
704
- pkg: Package,
705
- imageIds: Set<string>,
706
- basePath: string | undefined,
707
- encoder: PublishEncoder | undefined,
708
- ): Promise<void> {
709
- const images = pkg.listImageResources();
710
- for (const image of images) {
711
- image.setPixelHitTestData(null);
712
- }
713
- if (!basePath || !encoder || imageIds.size === 0) return;
714
-
715
- for (const image of images) {
716
- const imageId = image.getId();
717
- if (!imageIds.has(imageId)) continue;
718
- try {
719
- const sourcePath = resolveImagePath(image, pkg, basePath);
720
- const metadata = await encoder(sourcePath).metadata();
721
- if (!metadata.width || !metadata.height) continue;
722
-
723
- const resizedWidth = Math.max(1, Math.floor(metadata.width / 2));
724
- const resizedHeight = Math.max(1, Math.floor(metadata.height / 2));
725
- const { data, info } = await encoder(sourcePath)
726
- .ensureAlpha()
727
- .resize({
728
- width: resizedWidth,
729
- height: resizedHeight,
730
- fit: 'fill',
731
- })
732
- .raw()
733
- .toBuffer({ resolveWithObject: true });
734
-
735
- const pixelCount = info.width * info.height;
736
- const maskBytes = new Uint8Array(Math.ceil(pixelCount / 8));
737
- let byteValue = 0;
738
- let bitIndex = 0;
739
- let maskIndex = 0;
740
-
741
- for (let pixel = 0; pixel < pixelCount; pixel++) {
742
- const alpha = data[pixel * info.channels + 3];
743
- if (alpha > 10) byteValue |= 1 << bitIndex;
744
- bitIndex++;
745
- if (bitIndex === 8) {
746
- maskBytes[maskIndex++] = byteValue;
747
- bitIndex = 0;
748
- byteValue = 0;
749
- }
750
- }
751
- if (bitIndex !== 0) {
752
- maskBytes[maskIndex] = byteValue;
753
- }
754
-
755
- image.setPixelHitTestData({
756
- pixelWidth: info.width,
757
- scaleDenominator: 2,
758
- pixels: maskBytes,
759
- });
760
- } catch {
761
- image.setPixelHitTestData(null);
762
- }
763
- }
764
- }
765
-
766
- async function annotatePackagePublishArtifacts(
767
- pkg: Package,
768
- basePath: string | undefined,
769
- encoder: PublishEncoder | undefined,
770
- options: {
771
- includeBranches: boolean;
772
- activeBranch: string;
773
- },
774
- ): Promise<void> {
775
- const { publishedResourceIds, pixelHitTestImageIds, effectiveResourceIds, includeBranches } = collectPackagePublishContext(pkg, options);
776
- for (const resource of pkg.listResources()) {
777
- setPublishedIdExtra(resource, effectiveResourceIds.get(resource.getId()) ?? null);
778
- }
779
- await applyPixelHitTests(pkg, pixelHitTestImageIds, basePath, encoder);
780
- const extras = (pkg.getExtras() as PackagePublishArtifactsExtras | undefined) ?? {};
781
- pkg.setExtras({
782
- ...extras,
783
- publishedResourceIds: [...publishedResourceIds].sort((a, b) => a.localeCompare(b)),
784
- publishedIncludeBranches: includeBranches,
785
- publishedEffectiveResourceIds: Object.fromEntries(effectiveResourceIds),
786
- });
787
- for (const resource of pkg.listResources()) {
788
- if (isMiscResource(resource)) {
789
- setPublishedFileExtra(resource, resolvePublishedMiscFileName(resource));
790
- continue;
791
- }
792
- if (isSkeletonResource(resource)) {
793
- setPublishedFileExtra(resource, resolvePublishedSkeletonFileName(resource));
794
- }
795
- }
796
- }
797
-
798
- function getAnnotatedPublishedResourceIds(pkg: Package): Set<string> {
799
- const extras = (pkg.getExtras() as PackagePublishArtifactsExtras | undefined) ?? {};
800
- return new Set(extras.publishedResourceIds ?? []);
801
- }
802
-
803
- function getPublishedSkeletonDependencyImageIds(
804
- pkg: Package,
805
- publishedResourceIds: Set<string>,
806
- ): Set<string> {
807
- const imageIds = new Set<string>();
808
- const resourcesById = new Map(pkg.listResources().map((resource) => [resource.getId(), resource] as const));
809
- for (const resource of pkg.listResources()) {
810
- if (!isSkeletonResource(resource)) continue;
811
- if (!publishedResourceIds.has(resource.getId())) continue;
812
- for (const requiredId of resource.getRequireIds()) {
813
- if (!requiredId) continue;
814
- const required = resourcesById.get(requiredId);
815
- if (required && isImageResource(required)) imageIds.add(requiredId);
816
- }
817
- }
818
- return imageIds;
819
- }
820
-
821
- async function exportPackageSounds(
822
- pkg: Package,
823
- outputDir: string,
824
- basePath: string | undefined,
825
- fs: PublishFileSystem,
826
- readFileRaw: PublishFileSystem['readFileRaw'] | undefined,
827
- logger: Document['getLogger'] extends () => infer T ? T : never,
828
- ): Promise<void> {
829
- const publishedResourceIds = getAnnotatedPublishedResourceIds(pkg);
830
- if (publishedResourceIds.size === 0) return;
831
- if (!basePath || !readFileRaw) {
832
- const hasPublishedSound = pkg.listResources().some((resource) => {
833
- return isSoundResource(resource) && publishedResourceIds.has(resource.getId());
834
- });
835
- if (hasPublishedSound) {
836
- logger.warn(`publish: Sound resources in package "${pkg.getName()}" were not exported because basePath/readFileRaw is unavailable.`);
837
- }
838
- return;
839
- }
840
-
841
- for (const resource of pkg.listResources()) {
842
- if (!isSoundResource(resource)) continue;
843
- if (!publishedResourceIds.has(resource.getId())) continue;
844
-
845
- const sourcePath = resolveSoundPath(resource, pkg, basePath);
846
- const targetName = `${pkg.getPublishName() || pkg.getName()}_${getPublishedId(resource)}${extname(resource.getFile() || '')}`;
847
- const targetPath = fs.join(outputDir, targetName);
848
-
849
- try {
850
- const data = await readFileRaw(sourcePath);
851
- await fs.writeFileRaw(targetPath, data);
852
- } catch {
853
- logger.warn(`publish: Could not export sound "${resource.getId()}" from package "${pkg.getName()}".`);
854
- }
855
- }
856
- }
857
-
858
- async function exportPackageExternalResources(
859
- pkg: Package,
860
- outputDir: string,
861
- basePath: string | undefined,
862
- fs: PublishFileSystem,
863
- readFileRaw: PublishFileSystem['readFileRaw'] | undefined,
864
- logger: Document['getLogger'] extends () => infer T ? T : never,
865
- ): Promise<void> {
866
- const publishedResourceIds = getAnnotatedPublishedResourceIds(pkg);
867
- const skeletonDependencyImageIds = getPublishedSkeletonDependencyImageIds(pkg, publishedResourceIds);
868
- if (publishedResourceIds.size === 0) return;
869
- if (!basePath || !readFileRaw) {
870
- const hasPublishedExternal = pkg.listResources().some((resource) => {
871
- return (
872
- (isMiscResource(resource) || isSkeletonResource(resource))
873
- && publishedResourceIds.has(resource.getId())
874
- ) || skeletonDependencyImageIds.has(resource.getId());
875
- });
876
- if (hasPublishedExternal) {
877
- logger.warn(`publish: External resources in package "${pkg.getName()}" were not exported because basePath/readFileRaw is unavailable.`);
878
- }
879
- return;
880
- }
881
-
882
- for (const resource of pkg.listResources()) {
883
- const resourceId = resource.getId();
884
- const isSkeletonExternal = publishedResourceIds.has(resourceId) && (isMiscResource(resource) || isSkeletonResource(resource));
885
- const isSkeletonImageDependency = skeletonDependencyImageIds.has(resourceId) && isImageResource(resource);
886
- if (!isSkeletonExternal && !isSkeletonImageDependency) continue;
887
-
888
- let sourcePath: string;
889
- let targetName: string;
890
- if (isSkeletonImageDependency) {
891
- sourcePath = resolveImagePath(resource, pkg, basePath);
892
- targetName = resolveImageFileName(resource);
893
- } else if (isMiscResource(resource) || isSkeletonResource(resource)) {
894
- sourcePath = resolveGenericResourcePath(resource, pkg, basePath);
895
- targetName = ((resource.getExtras() as PublishFileExtras | undefined) ?? {})._publishedFile ?? resource.getFile();
896
- } else {
897
- continue;
898
- }
899
- const targetPath = fs.join(outputDir, targetName);
900
-
901
- try {
902
- const data = await readFileRaw(sourcePath);
903
- await fs.writeFileRaw(targetPath, data);
904
- } catch {
905
- logger.warn(`publish: Could not export external resource "${resource.getId()}" from package "${pkg.getName()}".`);
906
- }
907
- }
908
- }
909
-
910
106
  /**
911
107
  * Publishes a FairyGUI project.
912
108
  *
913
109
  * Orchestrates:
914
- * 1. Atlas packing (MaxRects layout + optional sharp compositing)
110
+ * 1. Atlas packing (MaxRects layout + optional raster compositing)
915
111
  * 2. Per-package .fui binary serialization
916
112
  * 3. File writing to the output directory
917
113
  *
114
+ * This is the capability-injected core. Standard hosts should use
115
+ * `publishNode()` or `publishBrowser()` through their dedicated entries.
116
+ *
918
117
  * ```ts
919
- * import sharp from 'sharp';
920
- * const io = new NodeIO();
921
- * const doc = await io.readProject('./project.fairy');
118
+ * import { NodeIO } from '@openfairygui/core/node';
119
+ * import { publishNode } from '@openfairygui/functions/node';
120
+ * const doc = await new NodeIO().readProject('./project.fairy');
922
121
  *
923
- * await doc.transform(publish({
122
+ * await publishNode({
123
+ * document: doc,
924
124
  * output: './release/',
925
125
  * compressed: true,
926
- * encoder: sharp,
927
- * basePath: './assets/',
126
+ * assetsPath: './assets/',
928
127
  * fileExtension: 'bytes',
929
- * fs: io.createFileSystem(),
930
- * }));
128
+ * });
931
129
  * ```
932
130
  */
933
131
  export function publish(options: PublishOptions): Transform {
934
132
  return createTransform('publish', async (doc: Document): Promise<void> => {
133
+ const resolveConfiguredOutputPath = (value?: string, projectBasePath?: string): string | undefined => {
134
+ const trimmed = value?.trim();
135
+ if (!trimmed) return undefined;
136
+ if (isAbsolutePathLike(trimmed) || !projectBasePath) {
137
+ return trimTrailingSlashes(trimmed);
138
+ }
139
+ return trimTrailingSlashes(
140
+ options.fs ? options.fs.join(projectBasePath, trimmed) : joinPathSegments(projectBasePath, trimmed),
141
+ );
142
+ };
143
+
144
+ const resolveProjectPublishConfig = (): ResolvedProjectPublishConfig => {
145
+ const settings = (doc.getRoot().getSettings?.() ?? {}) as RootProjectSettings;
146
+ const publishSettings: CliPublishSettings = settings.publish ?? {};
147
+ const resolved = resolvePublishOptions(doc, {
148
+ compressed: options.compressed,
149
+ fileExtension: options.fileExtension,
150
+ packages: options.packages,
151
+ atlas: options.atlas,
152
+ });
153
+ const branchProcessing = publishSettings.branchProcessing ?? 0;
154
+ const includeBranches = branchProcessing === 0;
155
+
156
+ return {
157
+ ...resolved,
158
+ projectType: doc.getRoot().getProjectType(),
159
+ includeBranches,
160
+ activeBranch: includeBranches ? '' : (options.branch ?? ''),
161
+ includeHighResolution: publishSettings.includeHighResolution ?? 0,
162
+ separatedAtlasForBranch: includeBranches && publishSettings.seperatedAtlasForBranch === true,
163
+ globalOutputPath: publishSettings.path?.trim() ?? '',
164
+ globalBranchOutputPath: publishSettings.branchPath?.trim() ?? '',
165
+ };
166
+ };
167
+
168
+ const resolvePackagePublishPlan = (
169
+ pkg: Package,
170
+ config: ResolvedProjectPublishConfig,
171
+ projectBasePath?: string,
172
+ ): ResolvedPackagePublishPlan => {
173
+ let outputDir: string | undefined;
174
+
175
+ if (options.output) {
176
+ outputDir = trimTrailingSlashes(options.output);
177
+ } else {
178
+ const candidates: Array<string | undefined> = [];
179
+ if (!config.includeBranches && config.activeBranch) {
180
+ candidates.push(pkg.getPublishBranchPath(), config.globalBranchOutputPath);
181
+ }
182
+ candidates.push(pkg.getPublishPath(), config.globalOutputPath);
183
+
184
+ for (const candidate of candidates) {
185
+ const resolved = resolveConfiguredOutputPath(candidate, projectBasePath);
186
+ if (!resolved) continue;
187
+ outputDir = resolved;
188
+ break;
189
+ }
190
+ }
191
+ const publishName = pkg.getPublishName() || pkg.getName();
192
+
193
+ return {
194
+ pkg,
195
+ outputDir,
196
+ publishName,
197
+ fileName: resolvePublishFileName(publishName, config.fileExtension),
198
+ compressed: config.compressed,
199
+ fileExtension: config.fileExtension,
200
+ includeBranches: config.includeBranches,
201
+ activeBranch: config.activeBranch,
202
+ includeHighResolution: config.includeHighResolution,
203
+ separatedAtlasForBranch: config.separatedAtlasForBranch,
204
+ atlas: config.atlas,
205
+ };
206
+ };
207
+
208
+ const createNoopPublishFs = (): PublishFileSystem => ({
209
+ async writeFileRaw(): Promise<void> {
210
+ // No-op for layout-only publish flows.
211
+ },
212
+ async mkdir(): Promise<void> {
213
+ // No-op for layout-only publish flows.
214
+ },
215
+ join(...paths: string[]): string {
216
+ return paths.join('/');
217
+ },
218
+ });
219
+
220
+ const publishPackage = async (plan: ResolvedPackagePublishPlan, writerFs: FileSystem, packageIndex: number) => {
221
+ if (options.fs && !plan.outputDir) {
222
+ throw new Error(
223
+ 'publish: no output directory resolved. Provide --output, or configure global publish.path / package publishPath.',
224
+ );
225
+ }
226
+
227
+ if (options.fs) {
228
+ await options.fs.mkdir(plan.outputDir!);
229
+ await exportPackageSounds(
230
+ plan.pkg,
231
+ plan.outputDir!,
232
+ options.basePath,
233
+ options.fs,
234
+ options.atlas?.readFileRaw ?? options.fs.readFileRaw,
235
+ );
236
+ await exportPackageExternalResources(
237
+ plan.pkg,
238
+ plan.outputDir!,
239
+ options.basePath,
240
+ options.fs,
241
+ options.atlas?.readFileRaw ?? options.fs.readFileRaw,
242
+ );
243
+ }
244
+
245
+ const atlasRuntimeOptions = resolvePublishAtlasRuntimeOptions(plan.fileExtension);
246
+ await atlas({
247
+ ...plan.atlas,
248
+ ...(options.atlas ?? {}),
249
+ separatedAtlasForBranch: plan.separatedAtlasForBranch,
250
+ encoder: options.encoder,
251
+ basePath: options.basePath,
252
+ outputPath: options.fs ? plan.outputDir : undefined,
253
+ mkdir: options.fs ? options.fs.mkdir : undefined,
254
+ readFileRaw: options.atlas?.readFileRaw ?? options.fs?.readFileRaw,
255
+ strictOutput: options.fs !== undefined,
256
+ packages: [plan.pkg.getName()],
257
+ ...atlasRuntimeOptions,
258
+ })(doc);
259
+
260
+ if (!options.fs) return;
261
+
262
+ const filePath = options.fs.join(plan.outputDir!, plan.fileName);
263
+ const bwOptions: BinaryWriterOptions = {
264
+ compressed: plan.compressed,
265
+ packageIndex,
266
+ };
267
+
268
+ const bw = new BinaryWriter(writerFs);
269
+ await bw.write(doc, filePath, bwOptions);
270
+
271
+ logger.info(`publish: Written ${plan.fileName}`);
272
+ };
273
+
935
274
  const root = doc.getRoot();
936
275
  const logger = doc.getLogger();
937
- const settings = (root.getSettings?.() ?? {}) as RootProjectSettings;
938
- const publishSettings: CliPublishSettings = settings.publish ?? {};
939
- const resolved = resolvePublishOptions(doc, {
940
- compressed: options.compressed,
941
- fileExtension: options.fileExtension,
942
- packages: options.packages,
943
- atlas: options.atlas,
944
- });
945
- const ext = resolved.fileExtension;
276
+ const projectBasePath = resolveProjectBasePath(options.basePath) || doc.getProjectDir?.() || '';
277
+ const plugins = options.plugins ?? [];
278
+ await runPublishPluginHook(plugins, 'onPublishStart', doc, options);
279
+
280
+ const resolved = resolveProjectPublishConfig();
946
281
 
947
282
  // Step 1: Determine which packages to publish
948
283
  let allPackages = root.listPackages();
@@ -953,14 +288,10 @@ export function publish(options: PublishOptions): Transform {
953
288
 
954
289
  if (allPackages.length === 0) {
955
290
  logger.warn('publish: No packages to publish.');
291
+ await runPublishPluginHook(plugins, 'onPublishEnd', doc, options);
956
292
  return;
957
293
  }
958
294
 
959
- const branchProcessing = publishSettings.branchProcessing ?? 0;
960
- const includeBranches = branchProcessing === 0;
961
- const activeBranch = includeBranches ? '' : (options.branch ?? '');
962
- const atlasRuntimeOptions = resolvePublishAtlasRuntimeOptions(ext);
963
-
964
295
  const allDocPackages = root.listPackages();
965
296
  // Build a pkgId→name map for dependency resolution
966
297
  const pkgMap = new Map<string, Package>();
@@ -971,82 +302,69 @@ export function publish(options: PublishOptions): Transform {
971
302
  for (const pkg of allPackages) {
972
303
  // Compute dependency list and selected publish artifacts before atlas packing,
973
304
  // so merged-branch publishes can pack the overridden resources with main IDs.
974
- _computeDependencies(pkg, pkgMap);
975
- await annotatePackagePublishArtifacts(
976
- pkg,
977
- options.basePath,
978
- options.encoder as PublishEncoder | undefined,
979
- {
980
- includeBranches,
981
- activeBranch,
982
- },
983
- );
305
+ _computeDependencies(doc, pkg, pkgMap);
306
+ await annotatePackagePublishArtifacts(pkg, options.basePath, options.encoder, {
307
+ projectType: resolved.projectType,
308
+ includeBranches: resolved.includeBranches,
309
+ activeBranch: resolved.activeBranch,
310
+ includeHighResolution: resolved.includeHighResolution,
311
+ });
984
312
  }
985
313
 
986
- // Step 2: Atlas packing
987
- const atlasOpts: AtlasOptions = {
988
- ...resolved.atlas,
989
- ...(options.atlas ?? {}),
990
- separatedAtlasForBranch: includeBranches && publishSettings.seperatedAtlasForBranch === true,
991
- encoder: options.encoder,
992
- basePath: options.basePath,
993
- outputPath: options.fs ? options.output : undefined,
994
- mkdir: options.fs ? options.fs.mkdir : undefined,
995
- readFileRaw: options.atlas?.readFileRaw ?? options.fs?.readFileRaw,
996
- ...atlasRuntimeOptions,
997
- };
998
- await atlas(atlasOpts)(doc);
314
+ const plans = allPackages.map((pkg) => resolvePackagePublishPlan(pkg, resolved, projectBasePath));
999
315
 
1000
- // Step 3: Write .fui binary per package
1001
316
  if (!options.fs) {
1002
- logger.info(`publish: No fs provided — layout computed for ${allPackages.length} package(s), skipping file output.`);
317
+ const outputPlan = plans.find((plan) => !!plan.outputDir);
318
+ if (outputPlan) {
319
+ throw new Error(
320
+ `publish: Output for package "${outputPlan.pkg.getName()}" requires a filesystem. ` +
321
+ 'Omit output and publish paths to run a layout-only transform.',
322
+ );
323
+ }
324
+ logger.info(
325
+ `publish: Layout computed for ${allPackages.length} package(s); no output directory was requested.`,
326
+ );
327
+ const noopWriterFs = toBinaryWriterFileSystem(createNoopPublishFs());
328
+ for (const plan of plans) {
329
+ await publishPackage(plan, noopWriterFs, allDocPackages.indexOf(plan.pkg));
330
+ }
331
+ await runPublishPluginHook(plugins, 'onPublishEnd', doc, options);
1003
332
  return;
1004
333
  }
1005
334
 
1006
- await options.fs.mkdir(options.output);
335
+ const unresolvedPlan = plans.find((plan) => !plan.outputDir);
336
+ if (unresolvedPlan) {
337
+ throw new Error(
338
+ `publish: no output directory resolved for package "${unresolvedPlan.pkg.getName()}". ` +
339
+ 'Provide --output, or configure global publish.path / package publishPath.',
340
+ );
341
+ }
1007
342
 
1008
343
  const writerFs = toBinaryWriterFileSystem(options.fs);
1009
344
 
1010
- for (const pkg of allPackages) {
1011
- const pkgIndex = allDocPackages.indexOf(pkg);
1012
- const publishName = pkg.getPublishName() || pkg.getName();
1013
- const fileName = resolvePublishFileName(publishName, ext);
1014
- const filePath = options.fs.join(options.output, fileName);
1015
-
1016
- const bwOptions: BinaryWriterOptions = {
1017
- compressed: resolved.compressed,
1018
- packageIndex: pkgIndex,
1019
- };
1020
-
1021
- const bw = new BinaryWriter(writerFs);
1022
- await bw.write(doc, filePath, bwOptions);
1023
- await exportPackageSounds(
1024
- pkg,
1025
- options.output,
1026
- options.basePath,
1027
- options.fs,
1028
- options.atlas?.readFileRaw ?? options.fs.readFileRaw,
1029
- logger,
1030
- );
1031
- await exportPackageExternalResources(
1032
- pkg,
1033
- options.output,
1034
- options.basePath,
1035
- options.fs,
1036
- options.atlas?.readFileRaw ?? options.fs.readFileRaw,
1037
- logger,
1038
- );
1039
-
1040
- logger.info(`publish: Written ${fileName}`);
345
+ for (const plan of plans) {
346
+ const pkgIndex = allDocPackages.indexOf(plan.pkg);
347
+ await publishPackage(plan, writerFs, pkgIndex);
1041
348
  }
1042
349
 
1043
- await publishCodeGeneration(doc, {
1044
- basePath: options.basePath,
1045
- fs: options.fs,
1046
- packages: allPackages,
1047
- });
350
+ if (options.codeGeneration !== false) {
351
+ await publishCodeGeneration(doc, {
352
+ basePath: options.basePath,
353
+ fs: options.fs,
354
+ packages: allPackages,
355
+ plugins,
356
+ });
357
+ }
1048
358
 
1049
- logger.info(`publish: Published ${allPackages.length} package(s) to ${options.output}`);
359
+ const publishedTargets = [
360
+ ...new Set(plans.map((plan) => plan.outputDir).filter((value): value is string => Boolean(value))),
361
+ ];
362
+ logger.info(
363
+ publishedTargets.length > 0
364
+ ? `publish: Published ${allPackages.length} package(s) to ${publishedTargets.join(', ')}`
365
+ : `publish: Published ${allPackages.length} package(s)`,
366
+ );
367
+ await runPublishPluginHook(plugins, 'onPublishEnd', doc, options);
1050
368
  });
1051
369
  }
1052
370
 
@@ -1055,34 +373,25 @@ export function publish(options: PublishOptions): Transform {
1055
373
  * The editor only adds dependencies for packages referenced via bitmap font URLs.
1056
374
  * @internal
1057
375
  */
1058
- function _computeDependencies(pkg: Package, pkgMap: Map<string, Package>): void {
1059
- const referencedPkgIds = new Set<string>();
1060
-
1061
- function scanFontUrl(font: string | string[] | null | undefined): void {
1062
- if (!font) return;
1063
- const fontStr = Array.isArray(font) ? font[0] : String(font);
1064
- if (typeof fontStr !== 'string' || !fontStr.startsWith('ui://')) return;
1065
- const rest = fontStr.slice(5);
1066
- if (rest.length >= 8) {
1067
- const depPkgId = rest.slice(0, 8);
1068
- if (depPkgId !== pkg.getId()) referencedPkgIds.add(depPkgId);
1069
- }
1070
- }
1071
-
1072
- for (const res of pkg.listResources()) {
1073
- if (res.propertyType !== 'Component') continue;
1074
- for (const child of res.listChildren?.() ?? []) {
1075
- // Only font="ui://..." references generate dependencies
1076
- scanFontUrl((child as HasOptionalFont).getFont?.());
1077
- }
1078
- }
1079
-
376
+ function _computeDependencies(doc: Document, pkg: Package, pkgMap: Map<string, Package>): void {
377
+ const referencedPkgIds = collectPackageResourceReferences(pkg).packageIds;
378
+ const packageOrder = new Map(
379
+ doc
380
+ .getRoot()
381
+ .listPackages()
382
+ .map((entry, index) => [entry.getId(), index] as const),
383
+ );
1080
384
  for (const dep of pkg.listDependencies()) {
1081
385
  pkg.removeDependency(dep);
1082
386
  }
1083
387
 
1084
388
  if (referencedPkgIds.size > 0) {
1085
- const sortedIds = [...referencedPkgIds].sort((a, b) => a.localeCompare(b));
389
+ const sortedIds = [...referencedPkgIds].sort((a, b) => {
390
+ const orderA = packageOrder.get(a) ?? Number.MAX_SAFE_INTEGER;
391
+ const orderB = packageOrder.get(b) ?? Number.MAX_SAFE_INTEGER;
392
+ if (orderA !== orderB) return orderA - orderB;
393
+ return a.localeCompare(b);
394
+ });
1086
395
  for (const refId of sortedIds) {
1087
396
  const depPkg = pkgMap.get(refId);
1088
397
  if (depPkg) {