ugcinc 5.4.0 → 5.5.0

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.
@@ -118,8 +118,8 @@ exports.matchTextStyleSchema = zod_1.z.object({ url: videoUrl,
118
118
  if (value.renderer === 'tiktok-native' && value.text !== undefined && value.text.split('\n').some(line => line.replace(/ /g, '').length === 0))
119
119
  ctx.addIssue({ code: 'custom', path: ['text'], message: 'Native text does not support empty or space-only paragraphs.' });
120
120
  });
121
- const matchedTextElement = zod_1.z.object({ id: zod_1.z.string(), type: zod_1.z.literal('text'), x: finiteNumber, y: finiteNumber, width: finiteNumber, height: finiteNumber, zIndex: zod_1.z.number(), textIsVariable: zod_1.z.literal(false), text: zod_1.z.string(), font: zod_1.z.enum(['arial', 'tiktok', 'apple']), fontSize: finiteNumber,
122
- fontWeight: zod_1.z.union([zod_1.z.literal(400), zod_1.z.literal(500), zod_1.z.literal(600), zod_1.z.literal(700), zod_1.z.literal(800), zod_1.z.literal(900)]), color: zod_1.z.string(), strokeColor: zod_1.z.string(), outlineWidth: finiteNumber, lineHeight: finiteNumber, letterSpacing: finiteNumber, textAlign: zod_1.z.enum(['left', 'center', 'right']), verticalAlign: zod_1.z.literal('top'), autoWidth: zod_1.z.literal(false), paddingTop: finiteNumber, paddingRight: finiteNumber, paddingBottom: finiteNumber, paddingLeft: finiteNumber });
121
+ const matchedTextElement = zod_1.z.object({ id: zod_1.z.string(), type: zod_1.z.literal('text'), x: finiteNumber, y: finiteNumber, width: finiteNumber, height: finiteNumber, zIndex: zod_1.z.number(), textIsVariable: zod_1.z.literal(false), text: zod_1.z.string(), fontFamily: zod_1.z.string().min(1), fontSize: finiteNumber,
122
+ fontWeight: zod_1.z.union([zod_1.z.literal(100), zod_1.z.literal(200), zod_1.z.literal(300), zod_1.z.literal(400), zod_1.z.literal(500), zod_1.z.literal(600), zod_1.z.literal(700), zod_1.z.literal(800), zod_1.z.literal(900)]), color: zod_1.z.string(), strokeColor: zod_1.z.string(), outlineWidth: finiteNumber, lineHeight: finiteNumber, letterSpacing: finiteNumber, textAlign: zod_1.z.enum(['left', 'center', 'right']), verticalAlign: zod_1.z.literal('top'), autoWidth: zod_1.z.literal(false), paddingTop: finiteNumber, paddingRight: finiteNumber, paddingBottom: finiteNumber, paddingLeft: finiteNumber });
123
123
  const nativeTextMatchSchema = zod_1.z.object({
124
124
  profile: zod_1.z.literal('tiktok-classic-ios-47'), settings: native_text_1.tiktokNativeTextStickerSchema,
125
125
  stickerUrl: videoUrl,
@@ -132,14 +132,18 @@ const nativeTextMatchSchema = zod_1.z.object({
132
132
  maskMetric: zod_1.z.literal('white-fill-iou'), outlineIoU: zod_1.z.number().min(0).max(1), emojiPixelCount: zod_1.z.number().int().nonnegative(),
133
133
  residualMetric: zod_1.z.literal('segmented-text-outline-and-warm-emoji'), foregroundMetric: zod_1.z.literal('estimated-background-composite-MAE') }),
134
134
  });
135
- exports.matchTextStyleResultSchema = zod_1.z.object({ version: zod_1.z.union([zod_1.z.literal(1), zod_1.z.literal(2)]), operation: zod_1.z.literal('match_text_style'), source: visualSource, box: boxSchema, surface: zod_1.z.enum(['image-editor-element', 'native-text-sticker']), status: zod_1.z.enum(['fitted', 'unavailable']), reason: zod_1.z.string().nullable(), text: zod_1.z.string().nullable(), textSource: zod_1.z.enum(['supplied', 'ocr']),
135
+ const fontIdentificationSchema = zod_1.z.object({ status: zod_1.z.enum(['identified', 'approximate']), family: zod_1.z.string(), weight: zod_1.z.number().int(), score: zod_1.z.number().min(0).max(1), margin: zod_1.z.number().nullable(),
136
+ topCandidates: zod_1.z.array(zod_1.z.object({ family: zod_1.z.string(), weight: zod_1.z.number().int(), score: zod_1.z.number().min(0).max(1) })).max(5),
137
+ fontsScanned: zod_1.z.number().int().nonnegative(), libraryFonts: zod_1.z.number().int().nonnegative(), libraryRefreshedAt: zod_1.z.number().int(), evidenceMode: zod_1.z.enum(['outlined', 'plain']), seconds: zod_1.z.number().nonnegative() });
138
+ exports.matchTextStyleResultSchema = zod_1.z.object({ version: zod_1.z.union([zod_1.z.literal(2), zod_1.z.literal(3)]), operation: zod_1.z.literal('match_text_style'), source: visualSource, box: boxSchema, surface: zod_1.z.enum(['image-editor-element', 'native-text-sticker']), status: zod_1.z.enum(['fitted', 'unavailable']), reason: zod_1.z.string().nullable(), text: zod_1.z.string().nullable(), textSource: zod_1.z.enum(['supplied', 'ocr']),
136
139
  renderer: zod_1.z.union([
137
- zod_1.z.object({ name: zod_1.z.literal('UGC-ImageEditorComposition'), ugcVersion: zod_1.z.string(), fonts: zod_1.z.array(zod_1.z.string()), fontHashes: zod_1.z.record(zod_1.z.string()), maxRenders: zod_1.z.number() }),
140
+ zod_1.z.object({ name: zod_1.z.literal('UGC-ImageEditorComposition'), ugcVersion: zod_1.z.string(), fontLibrary: zod_1.z.object({ source: zod_1.z.literal('google-fonts'), fonts: zod_1.z.number().int(), refreshedAt: zod_1.z.number().int() }).nullable(), maxRenders: zod_1.z.number() }),
138
141
  zod_1.z.object({ name: zod_1.z.literal('UGC-NativeTikTok'), profile: zod_1.z.literal('tiktok-classic-ios-47'), fontHashes: zod_1.z.record(zod_1.z.string()), maxRenders: zod_1.z.number() }),
139
142
  ]),
140
- candidates: zod_1.z.array(zod_1.z.object({ element: matchedTextElement, previewConfig: zod_1.z.object({ width: zod_1.z.number(), height: zod_1.z.number(), aspectRatio: zod_1.z.string(), dimensionPreset: zod_1.z.literal('custom'), elements: zod_1.z.array(matchedTextElement), backgroundType: zod_1.z.literal('color'), backgroundColor: zod_1.z.string() }), maskIoU: zod_1.z.number().min(0).max(1), foregroundMae: zod_1.z.number().min(0).max(1), fontIdentity: zod_1.z.literal('unverified'), quality: zod_1.z.enum(['close', 'approximate']) })).max(3),
143
+ candidates: zod_1.z.array(zod_1.z.object({ element: matchedTextElement, previewConfig: zod_1.z.object({ width: zod_1.z.number(), height: zod_1.z.number(), aspectRatio: zod_1.z.string(), dimensionPreset: zod_1.z.literal('custom'), elements: zod_1.z.array(matchedTextElement), backgroundType: zod_1.z.literal('color'), backgroundColor: zod_1.z.string() }), maskIoU: zod_1.z.number().min(0).max(1), outlineIoU: zod_1.z.number().min(0).max(1).nullable(), foregroundMae: zod_1.z.number().min(0).max(1).nullable(), fontIdentity: zod_1.z.enum(['identified', 'approximate']), quality: zod_1.z.enum(['close', 'approximate']) })).max(3),
144
+ fontIdentification: fontIdentificationSchema.nullable().optional(),
141
145
  nativeResult: nativeTextMatchSchema.optional(), reasonCode: zod_1.z.string().max(80).nullable().optional(), nextActions: zod_1.z.array(zod_1.z.string()).max(8).optional(), fitAttempted: zod_1.z.boolean().optional(),
142
- renders: zod_1.z.number().int().nonnegative(), backgroundColor: zod_1.z.string(), warnings: zod_1.z.array(zod_1.z.string()), previewUrl: zod_1.z.string().url(), manifestUrl: zod_1.z.string().url() });
146
+ renders: zod_1.z.number().int().nonnegative(), backgroundColor: zod_1.z.string().nullable(), warnings: zod_1.z.array(zod_1.z.string()), previewUrl: zod_1.z.string().url(), manifestUrl: zod_1.z.string().url() });
143
147
  exports.mediaAnalysisResultSchema = zod_1.z.discriminatedUnion('operation', [exports.framesResultSchema, exports.scenesResultSchema, exports.imageTextResultSchema, exports.videoTextResultSchema, exports.audioTranscriptResultSchema, exports.audioLevelsResultSchema, exports.sampleColorsResultSchema, exports.measureLayoutResultSchema, exports.matchTextStyleResultSchema]).superRefine((value, ctx) => {
144
148
  if (value.operation !== 'match_text_style')
145
149
  return;
@@ -149,7 +153,10 @@ exports.mediaAnalysisResultSchema = zod_1.z.discriminatedUnion('operation', [exp
149
153
  if ((value.status === 'fitted') !== (value.nativeResult !== undefined))
150
154
  ctx.addIssue({ code: 'custom', path: ['nativeResult'], message: 'A fitted native match requires its reproducible settings and sticker.' });
151
155
  }
152
- else if (value.version !== 1 || value.renderer.name !== 'UGC-ImageEditorComposition' || value.nativeResult !== undefined) {
153
- ctx.addIssue({ code: 'custom', message: 'Image-editor matching must retain the version1 image-editor result shape.' });
156
+ else if (value.version !== 3 || value.renderer.name !== 'UGC-ImageEditorComposition' || value.nativeResult !== undefined) {
157
+ ctx.addIssue({ code: 'custom', message: 'Image-editor matching returns the version 3 font-library result shape.' });
158
+ }
159
+ else if (value.status === 'fitted' && !value.fontIdentification) {
160
+ ctx.addIssue({ code: 'custom', path: ['fontIdentification'], message: 'A fitted image-editor match names its identified library font.' });
154
161
  }
155
162
  });
@@ -220,7 +220,7 @@ function TextElement({ segment, scale = 1 }) {
220
220
  const backgroundOpacity = segment.backgroundOpacity ?? defaults_1.TEXT_DEFAULTS.backgroundOpacity;
221
221
  const backgroundBorderRadius = segment.backgroundBorderRadius;
222
222
  // Get font family
223
- const fontFamily = (0, fonts_1.getFontFamily)(fontType);
223
+ const fontFamily = (0, fonts_1.getFontFamily)(fontType, segment.fontFamily);
224
224
  // Calculate width and line breaks
225
225
  const { calculatedWidth, calculatedLines, paddingTop, paddingRight, paddingBottom, paddingLeft } = (0, react_1.useMemo)(() => {
226
226
  let finalPaddingTop = basePaddingTop;
@@ -18,6 +18,7 @@ const TextElement_1 = require("../components/TextElement");
18
18
  const ImageElement_1 = require("../components/ImageElement");
19
19
  const positionResolver_1 = require("../utils/positionResolver");
20
20
  const cropBounds_1 = require("../utils/cropBounds");
21
+ const hooks_1 = require("../hooks");
21
22
  /**
22
23
  * Get all segments from all channels, sorted by zIndex
23
24
  */
@@ -52,6 +53,7 @@ function elementToTextSegment(elem) {
52
53
  opacity: elem.opacity,
53
54
  text: elem.text ?? '',
54
55
  fontType: elem.font ?? 'tiktok',
56
+ fontFamily: elem.fontFamily,
55
57
  fontSize: elem.fontSize ?? 40,
56
58
  fontWeight: elem.fontWeight ?? 'normal',
57
59
  color: elem.color ?? '#FFFFFF',
@@ -207,6 +209,16 @@ elements, width, height, backgroundType = 'image', backgroundColor, backgroundFi
207
209
  }
208
210
  };
209
211
  }, []);
212
+ // Font-library faces used by text (fontFamily) must be loaded before
213
+ // positions are measured and text is drawn.
214
+ const libraryFontItems = (0, react_1.useMemo)(() => {
215
+ if (elements)
216
+ return elements.filter((e) => e.type === 'text');
217
+ if (!config)
218
+ return [];
219
+ return getSortedSegments(config).filter((s) => s.type === 'text');
220
+ }, [elements, config]);
221
+ const libraryFontsReady = (0, hooks_1.useLibraryFonts)(libraryFontItems);
210
222
  // Get dimensions (from new props or legacy config)
211
223
  const canvasWidth = width ?? config?.width ?? 1080;
212
224
  const canvasHeight = height ?? config?.height ?? 1920;
@@ -219,7 +231,8 @@ elements, width, height, backgroundType = 'image', backgroundColor, backgroundFi
219
231
  console.warn('Position resolution errors:', result.errors);
220
232
  }
221
233
  return result.elements;
222
- }, [elements, textValues]);
234
+ // libraryFontsReady: re-measure auto-width text once library faces are loaded.
235
+ }, [elements, textValues, libraryFontsReady]);
223
236
  // Calculate crop bounds when dynamic crop is enabled
224
237
  const cropBounds = (0, react_1.useMemo)(() => {
225
238
  if (!(0, cropBounds_1.isDynamicCropEnabled)(dynamicCrop) || !resolvedElements)
@@ -280,7 +293,7 @@ elements, width, height, backgroundType = 'image', backgroundColor, backgroundFi
280
293
  ? backgroundColor
281
294
  : '#000000';
282
295
  // Don't render content until fonts are loaded (prevents incorrect measurements)
283
- if (!fontsLoaded) {
296
+ if (!fontsLoaded || !libraryFontsReady) {
284
297
  return ((0, jsx_runtime_1.jsx)(remotion_1.AbsoluteFill, { style: { backgroundColor: containerBgColor } }));
285
298
  }
286
299
  return ((0, jsx_runtime_1.jsx)(remotion_1.AbsoluteFill, { style: { backgroundColor: containerBgColor }, children: (0, jsx_runtime_1.jsxs)("div", { style: {
@@ -14,6 +14,7 @@ const remotion_1 = require("remotion");
14
14
  const TextElement_1 = require("../components/TextElement");
15
15
  const ImageElement_1 = require("../components/ImageElement");
16
16
  const VideoElement_1 = require("../components/VideoElement");
17
+ const hooks_1 = require("../hooks");
17
18
  /**
18
19
  * Calculate timing for all segments
19
20
  */
@@ -152,6 +153,9 @@ function VideoEditorComposition({ config, sources = {}, textContent = {}, }) {
152
153
  return aZ - bZ;
153
154
  });
154
155
  }, [segmentTimings]);
156
+ // Hold the render until font-library faces used by text segments are loaded.
157
+ const libraryFontItems = (0, react_1.useMemo)(() => segmentTimings.map(({ segment }) => segment).filter((s) => s.type === 'text'), [segmentTimings]);
158
+ const libraryFontsReady = (0, hooks_1.useLibraryFonts)(libraryFontItems);
155
159
  // Premount window for video sequences: in the Player, upcoming videos
156
160
  // mount invisibly this many frames early so they buffer and pre-seek
157
161
  // before becoming visible. No effect on server rendering.
@@ -171,6 +175,9 @@ function VideoEditorComposition({ config, sources = {}, textContent = {}, }) {
171
175
  const audioTimings = (0, react_1.useMemo)(() => {
172
176
  return segmentTimings.filter(({ segment }) => segment.type === 'audio');
173
177
  }, [segmentTimings]);
178
+ if (!libraryFontsReady) {
179
+ return (0, jsx_runtime_1.jsx)(remotion_1.AbsoluteFill, { style: { backgroundColor: '#000000' } });
180
+ }
174
181
  return ((0, jsx_runtime_1.jsxs)(remotion_1.AbsoluteFill, { style: { backgroundColor: '#000000' }, children: [visualTimings.map(({ segment, startFrame, durationInFrames }) => {
175
182
  if (segment.type === 'text') {
176
183
  const textSegment = segment;
@@ -4,6 +4,7 @@
4
4
  * Hooks for common operations like font loading, media preloading,
5
5
  * and position resolution.
6
6
  */
7
+ import type { FontWeight } from '../types';
7
8
  import { type PositionResolutionResult, type PositionResolutionError } from '../utils/positionResolver';
8
9
  import type { ImageEditorElement } from '../types/element';
9
10
  /**
@@ -11,6 +12,15 @@ import type { ImageEditorElement } from '../types/element';
11
12
  * Returns true when fonts are ready
12
13
  */
13
14
  export declare function useFontsLoaded(): boolean;
15
+ /**
16
+ * Hold the render until every font-library face used by the given text items
17
+ * is loaded (no-op when none uses `fontFamily`). Returns true once ready, so
18
+ * text is never measured or drawn with a fallback font.
19
+ */
20
+ export declare function useLibraryFonts(items: {
21
+ fontFamily?: string;
22
+ fontWeight?: FontWeight;
23
+ }[]): boolean;
14
24
  /**
15
25
  * Hook to load an image and return it when ready
16
26
  */
@@ -7,10 +7,12 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.useFontsLoaded = useFontsLoaded;
10
+ exports.useLibraryFonts = useLibraryFonts;
10
11
  exports.useImageLoader = useImageLoader;
11
12
  exports.useImagePreloader = useImagePreloader;
12
13
  exports.useResolvedPositions = useResolvedPositions;
13
14
  const react_1 = require("react");
15
+ const remotion_1 = require("remotion");
14
16
  const fonts_1 = require("../utils/fonts");
15
17
  const positionResolver_1 = require("../utils/positionResolver");
16
18
  /**
@@ -28,6 +30,54 @@ function useFontsLoaded() {
28
30
  }, [loaded]);
29
31
  return loaded;
30
32
  }
33
+ /**
34
+ * Hold the render until every font-library face used by the given text items
35
+ * is loaded (no-op when none uses `fontFamily`). Returns true once ready, so
36
+ * text is never measured or drawn with a fallback font.
37
+ */
38
+ function useLibraryFonts(items) {
39
+ const key = (0, react_1.useMemo)(() => {
40
+ const pairs = new Set();
41
+ for (const item of items) {
42
+ if (item.fontFamily)
43
+ pairs.add(JSON.stringify([item.fontFamily, item.fontWeight ?? 'normal']));
44
+ }
45
+ return JSON.stringify([...pairs].sort());
46
+ }, [items]);
47
+ const [readyKey, setReadyKey] = (0, react_1.useState)(key === '[]' ? key : null);
48
+ (0, react_1.useEffect)(() => {
49
+ if (key === '[]') {
50
+ setReadyKey(key);
51
+ return;
52
+ }
53
+ const requests = JSON.parse(key).map((pair) => {
54
+ const [family, weight] = JSON.parse(pair);
55
+ return { family, weight };
56
+ });
57
+ const handle = (0, remotion_1.delayRender)(`Loading library fonts ${key}`);
58
+ let active = true;
59
+ (0, fonts_1.loadLibraryFonts)(requests)
60
+ .then((failed) => {
61
+ if (!failed.length)
62
+ return;
63
+ const message = `Font library faces failed to load: ${JSON.stringify(failed)}`;
64
+ // A final render must never fall back silently to another font; previews log and continue.
65
+ if ((0, remotion_1.getRemotionEnvironment)().isRendering)
66
+ (0, remotion_1.cancelRender)(new Error(message));
67
+ else
68
+ console.error(`[ugcinc-render/fonts] ${message}`);
69
+ })
70
+ .finally(() => {
71
+ if (active)
72
+ setReadyKey(key);
73
+ (0, remotion_1.continueRender)(handle);
74
+ });
75
+ return () => {
76
+ active = false;
77
+ };
78
+ }, [key]);
79
+ return readyKey === key;
80
+ }
31
81
  /**
32
82
  * Hook to load an image and return it when ready
33
83
  */
@@ -109,6 +109,8 @@ export interface TextStyleProperties {
109
109
  multiLineExtraPaddingLeft?: number;
110
110
  /** Font family (default: 'arial') */
111
111
  fontType?: FontType;
112
+ /** Font-library family; takes precedence over fontType when set */
113
+ fontFamily?: string;
112
114
  /** Font size in pixels (default: 40) */
113
115
  fontSize?: number;
114
116
  /** Font weight (default: 'normal') */
@@ -78,6 +78,11 @@ export interface ImageEditorElement {
78
78
  strokeColor?: string;
79
79
  /** Font family */
80
80
  font?: FontType;
81
+ /**
82
+ * Font-library family (Google Fonts catalogue mirrored by UGC, e.g. "Google Sans").
83
+ * When set it takes precedence over `font`; `fontWeight` picks the nearest available weight.
84
+ */
85
+ fontFamily?: string;
81
86
  /** Font size in pixels */
82
87
  fontSize?: number;
83
88
  /** Font weight */
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Font utilities for the rendering system
3
3
  */
4
- import type { FontType } from '../types';
4
+ import type { FontType, FontWeight } from '../types';
5
5
  /**
6
6
  * Apple Color Emoji font name - used as fallback for emoji characters
7
7
  */
@@ -13,9 +13,51 @@ export declare const APPLE_EMOJI_FONT = "\"Apple Color Emoji\"";
13
13
  */
14
14
  export declare const FONT_FAMILIES: Record<FontType, string>;
15
15
  /**
16
- * Get the CSS font family string for a font type
16
+ * Get the CSS font family string for a font type, or for a font-library family
17
+ * when `fontFamily` is set (it takes precedence over `fontType`).
17
18
  */
18
- export declare function getFontFamily(fontType: FontType): string;
19
+ export declare function getFontFamily(fontType: FontType, fontFamily?: string): string;
20
+ /**
21
+ * Font library: the Google Fonts catalogue mirrored by UGC (open licences).
22
+ * `catalogue.json` lists every family with its available upright weights;
23
+ * files live at `<base>/files/<slug>/<weight>.ttf` (Latin subset).
24
+ */
25
+ export declare const FONT_LIBRARY_BASE_URL = "https://media.ugc.inc/owned-uploads/render/fonts/google";
26
+ export interface FontLibraryCatalogue {
27
+ version: number;
28
+ source: 'google-fonts';
29
+ refreshedAt: number;
30
+ baseUrl: string;
31
+ families: Record<string, {
32
+ category: string;
33
+ slug: string;
34
+ weights: number[];
35
+ }>;
36
+ }
37
+ /** CSS family name a library font is registered under (namespaced so it never collides with bundled fonts). */
38
+ export declare function libraryFontFace(family: string): string;
39
+ /** URL-safe family slug used in library file paths. */
40
+ export declare function libraryFontSlug(family: string): string;
41
+ /** Numeric CSS weight for a FontWeight value. */
42
+ export declare function numericFontWeight(weight: FontWeight | undefined): number;
43
+ /** Nearest available weight (ties go to the heavier weight, as CSS matching does above 500). */
44
+ export declare function nearestLibraryWeight(available: number[], wanted: number): number;
45
+ /** Fetch (once per page) the font library catalogue. Resolves null when unreachable. */
46
+ export declare function fetchFontLibraryCatalogue(): Promise<FontLibraryCatalogue | null>;
47
+ /**
48
+ * Load library font faces for the given (family, weight) pairs into
49
+ * `document.fonts`. Each requested weight is snapped to the nearest weight the
50
+ * library has for that family and registered under the requested weight too,
51
+ * so CSS matching picks the same file in every renderer. Resolves to the list
52
+ * of pairs that failed to load (empty on success).
53
+ */
54
+ export declare function loadLibraryFonts(requests: {
55
+ family: string;
56
+ weight: FontWeight | undefined;
57
+ }[]): Promise<{
58
+ family: string;
59
+ weight: number;
60
+ }[]>;
19
61
  /**
20
62
  * Build a CSS font string
21
63
  */
@@ -3,8 +3,14 @@
3
3
  * Font utilities for the rendering system
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.FONT_URLS = exports.FONT_FAMILIES = exports.APPLE_EMOJI_FONT = void 0;
6
+ exports.FONT_URLS = exports.FONT_LIBRARY_BASE_URL = exports.FONT_FAMILIES = exports.APPLE_EMOJI_FONT = void 0;
7
7
  exports.getFontFamily = getFontFamily;
8
+ exports.libraryFontFace = libraryFontFace;
9
+ exports.libraryFontSlug = libraryFontSlug;
10
+ exports.numericFontWeight = numericFontWeight;
11
+ exports.nearestLibraryWeight = nearestLibraryWeight;
12
+ exports.fetchFontLibraryCatalogue = fetchFontLibraryCatalogue;
13
+ exports.loadLibraryFonts = loadLibraryFonts;
8
14
  exports.buildFontString = buildFontString;
9
15
  exports.preloadFonts = preloadFonts;
10
16
  exports.areFontsLoaded = areFontsLoaded;
@@ -24,11 +30,86 @@ exports.FONT_FAMILIES = {
24
30
  arial: `Arial, ${exports.APPLE_EMOJI_FONT}, sans-serif`,
25
31
  };
26
32
  /**
27
- * Get the CSS font family string for a font type
33
+ * Get the CSS font family string for a font type, or for a font-library family
34
+ * when `fontFamily` is set (it takes precedence over `fontType`).
28
35
  */
29
- function getFontFamily(fontType) {
36
+ function getFontFamily(fontType, fontFamily) {
37
+ if (fontFamily) {
38
+ return `"${libraryFontFace(fontFamily)}", ${exports.APPLE_EMOJI_FONT}, sans-serif`;
39
+ }
30
40
  return exports.FONT_FAMILIES[fontType] ?? exports.FONT_FAMILIES.arial;
31
41
  }
42
+ /**
43
+ * Font library: the Google Fonts catalogue mirrored by UGC (open licences).
44
+ * `catalogue.json` lists every family with its available upright weights;
45
+ * files live at `<base>/files/<slug>/<weight>.ttf` (Latin subset).
46
+ */
47
+ exports.FONT_LIBRARY_BASE_URL = 'https://media.ugc.inc/owned-uploads/render/fonts/google';
48
+ /** CSS family name a library font is registered under (namespaced so it never collides with bundled fonts). */
49
+ function libraryFontFace(family) {
50
+ return `UGC Library ${family}`;
51
+ }
52
+ /** URL-safe family slug used in library file paths. */
53
+ function libraryFontSlug(family) {
54
+ return family.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
55
+ }
56
+ /** Numeric CSS weight for a FontWeight value. */
57
+ function numericFontWeight(weight) {
58
+ if (weight === undefined || weight === 'normal')
59
+ return 400;
60
+ if (weight === 'bold')
61
+ return 700;
62
+ return weight;
63
+ }
64
+ /** Nearest available weight (ties go to the heavier weight, as CSS matching does above 500). */
65
+ function nearestLibraryWeight(available, wanted) {
66
+ return available.reduce((best, w) => {
67
+ const d = Math.abs(w - wanted);
68
+ const bd = Math.abs(best - wanted);
69
+ return d < bd || (d === bd && w > best) ? w : best;
70
+ }, available[0] ?? wanted);
71
+ }
72
+ let cataloguePromise = null;
73
+ /** Fetch (once per page) the font library catalogue. Resolves null when unreachable. */
74
+ function fetchFontLibraryCatalogue() {
75
+ cataloguePromise ?? (cataloguePromise = fetch(`${exports.FONT_LIBRARY_BASE_URL}/catalogue.json`)
76
+ .then((r) => (r.ok ? r.json() : null))
77
+ .catch(() => null));
78
+ return cataloguePromise;
79
+ }
80
+ const loadedLibraryFaces = new Map();
81
+ /**
82
+ * Load library font faces for the given (family, weight) pairs into
83
+ * `document.fonts`. Each requested weight is snapped to the nearest weight the
84
+ * library has for that family and registered under the requested weight too,
85
+ * so CSS matching picks the same file in every renderer. Resolves to the list
86
+ * of pairs that failed to load (empty on success).
87
+ */
88
+ async function loadLibraryFonts(requests) {
89
+ if (typeof document === 'undefined' || !document.fonts || requests.length === 0)
90
+ return [];
91
+ const catalogue = await fetchFontLibraryCatalogue();
92
+ const failed = [];
93
+ await Promise.all(requests.map(async ({ family, weight }) => {
94
+ const wanted = numericFontWeight(weight);
95
+ const entry = catalogue?.families[family];
96
+ const fileWeight = entry ? nearestLibraryWeight(entry.weights, wanted) : wanted;
97
+ const slug = entry?.slug ?? libraryFontSlug(family);
98
+ const key = `${family}|${wanted}`;
99
+ let pending = loadedLibraryFaces.get(key);
100
+ if (!pending) {
101
+ const face = new FontFace(libraryFontFace(family), `url(${exports.FONT_LIBRARY_BASE_URL}/files/${slug}/${fileWeight}.ttf)`, { weight: String(wanted), style: 'normal' });
102
+ pending = face.load().then((loaded) => {
103
+ document.fonts.add(loaded);
104
+ return true;
105
+ }, () => false);
106
+ loadedLibraryFaces.set(key, pending);
107
+ }
108
+ if (!(await pending))
109
+ failed.push({ family, weight: wanted });
110
+ }));
111
+ return failed;
112
+ }
32
113
  /**
33
114
  * Build a CSS font string
34
115
  */
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Utility exports for ugcinc-render
3
3
  */
4
- export { FONT_FAMILIES, APPLE_EMOJI_FONT, getFontFamily, buildFontString, FONT_URLS, preloadFonts, areFontsLoaded, debugFontStatus, } from './fonts';
4
+ export { FONT_FAMILIES, APPLE_EMOJI_FONT, getFontFamily, buildFontString, FONT_URLS, preloadFonts, areFontsLoaded, debugFontStatus, FONT_LIBRARY_BASE_URL, libraryFontFace, libraryFontSlug, numericFontWeight, nearestLibraryWeight, fetchFontLibraryCatalogue, loadLibraryFonts, type FontLibraryCatalogue, } from './fonts';
5
5
  export { calculateFitDimensions, type FitDimensions } from './fit';
6
6
  export { TEXT_DEFAULTS, IMAGE_DEFAULTS, VIDEO_DEFAULTS, VISUAL_DEFAULTS, applyTextDefaults, applyImageDefaults, applyVideoDefaults, } from './defaults';
7
7
  export { wrapText, calculateLineWidth, getBorderRadii, parseHexColor, hexToRgba, getSFProLetterSpacing, } from './text';
@@ -3,7 +3,8 @@
3
3
  * Utility exports for ugcinc-render
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.calculateScreenshotAnimationDuration = exports.SCREENSHOT_ANIMATION_DEFAULTS = exports.colorNameToHex = exports.isValidCaptionPreset = exports.getCaptionPresetNames = exports.resolveCaptionStyle = exports.DEFAULT_CAPTION_STYLE = exports.CAPTION_PRESETS = exports.generateOverlayId = exports.generateSegmentId = exports.parseTime = exports.formatTime = exports.calculateTimelineContentEnd = exports.calculateEstimatedDuration = exports.isSegmentVisibleAtTime = exports.getSegmentTimelinePosition = exports.getOverlays = exports.getBaseSegments = exports.defaultOffset = exports.isDynamicCropEnabled = exports.calculateCropBounds = exports.getReferenceElementY = exports.getReferenceElementX = exports.getDependentElements = exports.canSetAsReference = exports.calculateAutoWidthDimensions = exports.resolveElementPositions = exports.getSFProLetterSpacing = exports.hexToRgba = exports.parseHexColor = exports.getBorderRadii = exports.calculateLineWidth = exports.wrapText = exports.applyVideoDefaults = exports.applyImageDefaults = exports.applyTextDefaults = exports.VISUAL_DEFAULTS = exports.VIDEO_DEFAULTS = exports.IMAGE_DEFAULTS = exports.TEXT_DEFAULTS = exports.calculateFitDimensions = exports.debugFontStatus = exports.areFontsLoaded = exports.preloadFonts = exports.FONT_URLS = exports.buildFontString = exports.getFontFamily = exports.APPLE_EMOJI_FONT = exports.FONT_FAMILIES = void 0;
6
+ exports.DEFAULT_CAPTION_STYLE = exports.CAPTION_PRESETS = exports.generateOverlayId = exports.generateSegmentId = exports.parseTime = exports.formatTime = exports.calculateTimelineContentEnd = exports.calculateEstimatedDuration = exports.isSegmentVisibleAtTime = exports.getSegmentTimelinePosition = exports.getOverlays = exports.getBaseSegments = exports.defaultOffset = exports.isDynamicCropEnabled = exports.calculateCropBounds = exports.getReferenceElementY = exports.getReferenceElementX = exports.getDependentElements = exports.canSetAsReference = exports.calculateAutoWidthDimensions = exports.resolveElementPositions = exports.getSFProLetterSpacing = exports.hexToRgba = exports.parseHexColor = exports.getBorderRadii = exports.calculateLineWidth = exports.wrapText = exports.applyVideoDefaults = exports.applyImageDefaults = exports.applyTextDefaults = exports.VISUAL_DEFAULTS = exports.VIDEO_DEFAULTS = exports.IMAGE_DEFAULTS = exports.TEXT_DEFAULTS = exports.calculateFitDimensions = exports.loadLibraryFonts = exports.fetchFontLibraryCatalogue = exports.nearestLibraryWeight = exports.numericFontWeight = exports.libraryFontSlug = exports.libraryFontFace = exports.FONT_LIBRARY_BASE_URL = exports.debugFontStatus = exports.areFontsLoaded = exports.preloadFonts = exports.FONT_URLS = exports.buildFontString = exports.getFontFamily = exports.APPLE_EMOJI_FONT = exports.FONT_FAMILIES = void 0;
7
+ exports.calculateScreenshotAnimationDuration = exports.SCREENSHOT_ANIMATION_DEFAULTS = exports.colorNameToHex = exports.isValidCaptionPreset = exports.getCaptionPresetNames = exports.resolveCaptionStyle = void 0;
7
8
  // Font utilities
8
9
  var fonts_1 = require("./fonts");
9
10
  Object.defineProperty(exports, "FONT_FAMILIES", { enumerable: true, get: function () { return fonts_1.FONT_FAMILIES; } });
@@ -14,6 +15,13 @@ Object.defineProperty(exports, "FONT_URLS", { enumerable: true, get: function ()
14
15
  Object.defineProperty(exports, "preloadFonts", { enumerable: true, get: function () { return fonts_1.preloadFonts; } });
15
16
  Object.defineProperty(exports, "areFontsLoaded", { enumerable: true, get: function () { return fonts_1.areFontsLoaded; } });
16
17
  Object.defineProperty(exports, "debugFontStatus", { enumerable: true, get: function () { return fonts_1.debugFontStatus; } });
18
+ Object.defineProperty(exports, "FONT_LIBRARY_BASE_URL", { enumerable: true, get: function () { return fonts_1.FONT_LIBRARY_BASE_URL; } });
19
+ Object.defineProperty(exports, "libraryFontFace", { enumerable: true, get: function () { return fonts_1.libraryFontFace; } });
20
+ Object.defineProperty(exports, "libraryFontSlug", { enumerable: true, get: function () { return fonts_1.libraryFontSlug; } });
21
+ Object.defineProperty(exports, "numericFontWeight", { enumerable: true, get: function () { return fonts_1.numericFontWeight; } });
22
+ Object.defineProperty(exports, "nearestLibraryWeight", { enumerable: true, get: function () { return fonts_1.nearestLibraryWeight; } });
23
+ Object.defineProperty(exports, "fetchFontLibraryCatalogue", { enumerable: true, get: function () { return fonts_1.fetchFontLibraryCatalogue; } });
24
+ Object.defineProperty(exports, "loadLibraryFonts", { enumerable: true, get: function () { return fonts_1.loadLibraryFonts; } });
17
25
  // Fit utilities
18
26
  var fit_1 = require("./fit");
19
27
  Object.defineProperty(exports, "calculateFitDimensions", { enumerable: true, get: function () { return fit_1.calculateFitDimensions; } });
@@ -13,6 +13,7 @@ exports.canSetAsReference = canSetAsReference;
13
13
  exports.getDependentElements = getDependentElements;
14
14
  exports.getReferenceElementX = getReferenceElementX;
15
15
  exports.getReferenceElementY = getReferenceElementY;
16
+ const fonts_1 = require("./fonts");
16
17
  // Font family mapping for text measurement
17
18
  const FONT_FAMILIES = {
18
19
  tiktok: '"TikTok Sans", sans-serif',
@@ -56,7 +57,7 @@ function calculateAutoWidthDimensions(elem, textContent, ctx) {
56
57
  const boxAlign = elem.boxAlign ?? 'left';
57
58
  const autoWidth = elem.autoWidth ?? false;
58
59
  // Set font for measurement
59
- const fontFamily = FONT_FAMILIES[fontType] ?? FONT_FAMILIES.tiktok;
60
+ const fontFamily = elem.fontFamily ? `"${(0, fonts_1.libraryFontFace)(elem.fontFamily)}", sans-serif` : (FONT_FAMILIES[fontType] ?? FONT_FAMILIES.tiktok);
60
61
  measureCtx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
61
62
  // Calculate available width for text wrapping
62
63
  const availableWidth = maxWidth - paddingLeft - paddingRight;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugcinc",
3
- "version": "5.4.0",
3
+ "version": "5.5.0",
4
4
  "description": "TypeScript/JavaScript client for the UGC Inc API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -57,8 +57,10 @@ or enabling recurring runs unless the user authorized those actions.
57
57
  size, not only on a large canvas. Keep important text away from platform UI;
58
58
  inspect the relevant target presentation rather than assuming universal margins.
59
59
  - Use sampled reference colors and real render previews. Judge font, stroke,
60
- kerning, line height and emoji spacing together. Treat text-style fitting as a
61
- measured candidate, not proof of an exact font or pixel-perfect output.
60
+ kerning, line height and emoji spacing together. To reuse a reference
61
+ caption's font, take `match_text_style`'s identified library font
62
+ (`fontFamily` in Image Composer text); when it reports `approximate`, the
63
+ reference font is not in the library and the result is the closest match.
62
64
  - Match the reference post's actual audio excerpt, mix, start and duration when
63
65
  requested. Preserve attribution separately. Empty transcription can mean music
64
66
  or unrecognized speech, not silence. Keep visual reveals and audio timing coherent.
@@ -78,18 +78,17 @@ coverage. A zero process exit code alone does not establish API success.
78
78
  establish silence. Model confidence scores are not a guarantee that wording is correct.
79
79
  - Color sampling measures decoded sRGB pixels, not guaranteed design hex values.
80
80
  Layout measurement does not detect objects or recover original layer files.
81
- - For text over photographic backgrounds, call `match_text_style` with
82
- `renderer: "auto"` or `"tiktok-native"` and exact text/line breaks when known.
83
- Native results include Unicode/emoji and a clean transparent sticker using
84
- the supported native TikTok profile. Omitted renderer keeps the older
85
- ASCII/plain-background image-editor path. Inspect `surface`/version and use
86
- `nativeResult` or generic `candidates` accordingly.
81
+ - To copy a caption's font, call `match_text_style` with exact text and line
82
+ breaks (default renderer). It identifies the font from the UGC font library
83
+ (Google Fonts catalogue, refreshed daily) for outlined captions on photos and
84
+ plain text on uniform backgrounds, and returns an Image Composer element with
85
+ `fontFamily` and fitted styling. `fontIdentification.status: approximate`
86
+ means the original font is not in the library; the closest one is returned.
87
+ Use `renderer: "tiktok-native"` for emoji captions.
87
88
  - A completed matching job can return inner `status: "unavailable"`. Check
88
- `reasonCode`, `fitAttempted`, `renders` and `nextActions`. Zero renders means
89
- no font fit was attempted: do not spend repeated calls on similar rejected
90
- crops or download replacement fonts. Font identity stays unverified; compare
91
- text/outline residuals and the preview before calling any result accurate.
92
- Equal line widths or matching positions alone do not prove identical text.
89
+ `reasonCode`, `fitAttempted`, `renders` and `nextActions`; do not spend
90
+ repeated calls on similar rejected crops. Compare `maskIoU` and the preview
91
+ before calling a result exact.
93
92
  - SAM/object segmentation, automatic overlay detection, element/mask tracking,
94
93
  motion measurement, extraction, media comparison/alignment and semantic search
95
94
  are not available through this tool set. Do not invent those calls or install
@@ -45,7 +45,7 @@ These return `{ok, data:{jobId,status,operation,result?,error?}}`. Use the compl
45
45
  | `measure_audio_levels` / `media.measureAudioLevels` | `{url,range?:{startMs,endMs},windowMs?:100,silenceThresholdDbfs?:-50}` | Native-channel RMS/sample peaks, loudness timeline/LUFS, silence, possible clipping, `previewUrl`. Windows20–5000ms, threshold−100to−10dBFS, range at most120seconds. |
46
46
  | `sample_colors` / `media.sampleColors` | `{url,maxColors?:8,point?:{x,y},box?:{x,y,width,height},mask?}`; choose at most one selection | Observed RGBA point or palette/proportions, omitted mass, declared color policy, `previewUrl`. Palette1–32colors. |
47
47
  | `measure_layout` / `media.measureLayout` | `{url,elements:[{id,box:{x,y,width,height}}]}`; each element may instead have `mask` | Margins, centers, spacing/alignment deltas, intersections/IoU and `previewUrl`.1–32unique IDs. Boxes are supplied, not automatically detected. |
48
- | `match_text_style` / `media.matchTextStyle` | `{url,box:{x,y,width,height},text?,renderer?}`; integer crop 16–1536 wide, 16–512 high. `renderer: auto` allows native fallback; `tiktok-native` requests the native profile. Omitted renderer keeps legacy image-editor behavior. Supply exact text and line breaks when available. | `status`, `reasonCode`, `fitAttempted`, `nextActions`, comparison and warnings. Generic v1 returns `candidates` with image-editor `element`/`previewConfig`. Native v2 returns `nativeResult` with actual native `settings`, clean transparent `stickerUrl`, source-pixel `composition`, masked residuals and diagnostics; `candidates` is empty. Native/auto accept Unicode/emoji, up to 160 UTF-16 code units/four lines; generic remains ASCII/plain-background only. Original font identity is unverified. |
48
+ | `match_text_style` / `media.matchTextStyle` | `{url,box:{x,y,width,height},text?,renderer?}`; integer crop 16–1536 wide, 16–512 high. Omitted renderer (`image-editor`) identifies the font from the UGC font library and fits an Image Composer text element; `auto` adds the native TikTok sticker as fallback (and uses it for emoji text); `tiktok-native` requests only the native profile. Supply exact text and line breaks. | `status`, `reasonCode`, `fitAttempted`, `nextActions`, comparison and warnings. Image-editor v3 returns `fontIdentification` (`family`, `weight`, `score`, `margin`, `status: identified|approximate`, ranked `topCandidates`) and up to 3 `candidates` whose `element` uses `fontFamily` (a library family) with fitted size, weight, spacing, line height, outline and colours. Native v2 returns `nativeResult` with native `settings`, a transparent `stickerUrl`, source-pixel `composition` and diagnostics; `candidates` is empty. Image-editor text is printable ASCII; native/auto accept Unicode/emoji, up to 160 UTF-16 code units/four lines. |
49
49
  | `get_media_analysis` / `media.getMediaAnalysis` | `{jobId}` | Current status/result in the current organization; use when automatic waiting returned pending/processing. |
50
50
 
51
51
  Boxes are half-open source-pixel rectangles. For masks used by colors/layout:
@@ -55,28 +55,33 @@ convention. Supply only masks you actually have; automatic segmentation is off.
55
55
 
56
56
  ## Text matching decisions
57
57
 
58
- For photographed TikTok captions, use `renderer: "auto"` or `"tiktok-native"`
59
- and supply the exact caption, including emoji and intended line breaks. The
60
- native candidate uses the supported `tiktok-classic-ios-47` profile: white text,
61
- dark outline, original native shaping and emoji. This does not imply every
62
- TikTok caption uses that profile. Unsupported styles remain unavailable or
63
- explicit approximations; no new font download or hosted model is required.
58
+ To copy a caption's font, call `match_text_style` with the default renderer
59
+ and the exact text with its line breaks. The tool compares the caption's letter
60
+ shapes with every font in the UGC font library (the Google Fonts catalogue,
61
+ about 1,800 families; refreshed daily, so new families become available without
62
+ a release). It works for an outlined caption (light or coloured fill, dark
63
+ outline) on any background and for plain text on a uniform background.
64
+
65
+ Read `fontIdentification`: `status: identified` names the library family and
66
+ weight; `approximate` means the caption's font is probably not in any free
67
+ library (for example a paid font), so the closest library font is returned.
68
+ `topCandidates` ranks the next best families; `equivalentFamilies` lists
69
+ families whose Latin letters are identical. Use `candidates[0].element`
70
+ directly in an Image Composer: it carries `fontFamily`, `fontWeight`, size,
71
+ letter spacing, line height, outline width and colours fitted with the real
72
+ renderer. Check `maskIoU` and the preview before calling a fit exact.
73
+
74
+ For emoji captions use `renderer: "tiktok-native"` (native TikTok sticker).
64
75
 
65
76
  Check all three levels: outer response `ok`, analysis job `status`, and inner
66
77
  matching `result.status`. A completed analysis can legitimately return
67
- `unavailable`. If `fitAttempted` is false or `renders` is zero, no font candidate
68
- was tested. Read `reasonCode` and `nextActions`; do not keep resubmitting nearly
69
- the same crop after a background/segmentation rejection. Keep the source frame
70
- and failure for a tool repair rather than claiming a missing font.
71
-
72
- Use `surface` and result version to choose the output. Generic image-editor
73
- results retain `candidates[].element` and `previewConfig`. Native results use
74
- `nativeResult.settings` with the native sticker renderer, or directly reuse
75
- `nativeResult.stickerUrl`. Its `composition` positions the clean PNG in source
76
- pixels; native settings themselves use points and produce 3× pixels. Do not
77
- paste extracted source-caption pixels onto a changed background. Compare the
78
- returned fit/difference preview and residuals; matching a line width or locating
79
- its top-left corner does not establish correct glyphs, spacing or emoji.
78
+ `unavailable`. If `fitAttempted` is false or `renders` is zero, no fit was
79
+ rendered. Read `reasonCode` and `nextActions` (for example
80
+ `TEXT_EVIDENCE_CLIPPED`: include the whole caption with a margin;
81
+ `AMBIGUOUS_TEXT_EVIDENCE`: supply the exact line breaks); do not keep
82
+ resubmitting nearly the same crop.
83
+
84
+ Do not paste extracted source-caption pixels onto a changed background.
80
85
 
81
86
  ## Existing media library
82
87