@drincs/pixi-vn-json 1.13.8 → 1.13.9

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.
@@ -1,8 +1,221 @@
1
+ import { ZodType } from 'zod';
1
2
  import { StepLabelPropsType } from '@drincs/pixi-vn';
2
3
  import { F as PixiVNJsonLabelStep, L as PixiVNJsonOperation } from './PixiVNJsonLabelStep-DJgORyFd.cjs';
3
4
  import '@drincs/pixi-vn/motion';
4
5
  import 'pixi.js';
5
6
 
7
+ /**
8
+ * A handler function invoked for each `[key]` token found in the text that passes the
9
+ * {@link ReplaceHandlerOptions.validation} check.
10
+ *
11
+ * @param key The content found inside the square brackets (without the brackets themselves).
12
+ * For example, for the token `[john]` the key is `"john"`.
13
+ * @returns The string to substitute in place of `[key]`, or `undefined` to leave the token unchanged.
14
+ */
15
+ type ReplaceHandler = (
16
+ /**
17
+ * The key to be replaced
18
+ */
19
+ key: string) => string | undefined;
20
+ /**
21
+ * Configuration options for a text-replacement handler registered via {@link TextReplaces.add}.
22
+ */
23
+ type ReplaceHandlerOptions = {
24
+ /**
25
+ * A unique name that identifies this handler.
26
+ * Used for documentation and debugging purposes.
27
+ */
28
+ name: string;
29
+ /**
30
+ * An optional human-readable description of what this handler does.
31
+ * Used for documentation purposes.
32
+ */
33
+ description?: string;
34
+ /**
35
+ * Determines whether this handler should be invoked for a given `[key]` token.
36
+ *
37
+ * - `"all"` – the handler is always invoked for every token found.
38
+ * - `"characterId"` – the handler is invoked only when the key matches a registered character ID
39
+ * (i.e. the character is present in `RegisteredCharacters`).
40
+ * - `RegExp` – the key string is tested against the regular expression. The handler is invoked
41
+ * only if the regex matches.
42
+ * - `ZodType<string>` – the key string is validated with `schema.safeParse(key)`. The handler
43
+ * is invoked only if validation succeeds.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * // RegExp: only replace keys that look like lowercase identifiers
48
+ * validation: /^[a-z_]+$/
49
+ *
50
+ * // Zod: only replace keys that are one of a fixed set of values
51
+ * import { z } from "zod"
52
+ * validation: z.enum(["player", "npc", "enemy"])
53
+ * ```
54
+ */
55
+ validation: RegExp | "characterId" | "all" | ZodType<string>;
56
+ /**
57
+ * When this handler should be invoked relative to the translation step.
58
+ *
59
+ * - `"before-translation"` – the handler runs **before** {@link onInkTranslate} is called.
60
+ * Useful for pre-processing tokens, e.g. converting `[key]` into `{{key}}` for i18next.
61
+ * - `"after-translation"` – the handler runs **after** {@link onInkTranslate} is called.
62
+ * Useful for substituting values that depend on the translated text.
63
+ *
64
+ * @default "after-translation"
65
+ */
66
+ type?: "after-translation" | "before-translation";
67
+ /**
68
+ * When `true`, the **first** occurrence of a matched `[key]` token is converted to the i18n
69
+ * double-brace format `{{[key]}}` (exactly once). Any subsequent occurrences of `[key]` in
70
+ * the same text are then replaced with the handler's return value as usual.
71
+ *
72
+ * The transformation sequence for a matched key is:
73
+ * - first occurrence: `[key]` → `{{[key]}}`
74
+ * - remaining occurrences: `[key]` → handler return value
75
+ *
76
+ * When `false` or omitted, the handler's return value directly replaces all occurrences of `[key]`.
77
+ *
78
+ * **Recommended i18n configuration:** when this option is enabled, configure
79
+ * `missingInterpolationHandler` in your i18n instance so that keys with no matching
80
+ * translation are left intact rather than replaced with an empty string:
81
+ *
82
+ * ```ts title="lib/i18n.ts"
83
+ * i18n.init({
84
+ * // ...
85
+ * missingInterpolationHandler(_text, value, _options) {
86
+ * return value[1];
87
+ * },
88
+ * });
89
+ * ```
90
+ *
91
+ * @default false
92
+ */
93
+ i18nInterpolation?: boolean;
94
+ };
95
+
96
+ /**
97
+ * Manages text replacement handlers that process content enclosed in square brackets (`[key]`).
98
+ *
99
+ * Handlers are called in the order they were added. For each handler, the current text is scanned
100
+ * for all `[key]` patterns. If the handler's `validation` matches a key, the handler is
101
+ * invoked with that key. If the handler returns a string, all occurrences of `[key]` are replaced
102
+ * with the returned value. After a handler finishes processing the text, the next handler starts
103
+ * on the updated text.
104
+ *
105
+ * Each handler specifies whether it runs before or after translation via the `type` field in its
106
+ * options (defaults to `"after-translation"`).
107
+ *
108
+ * @example
109
+ * ```ts title="content/text-replaces.ts"
110
+ * import { TextReplaces } from 'pixi-vn-ink'
111
+ * import { getCharacterById } from "@drincs/pixi-vn";
112
+ *
113
+ * // Replace [characterId] with the character's display name
114
+ * TextReplaces.add(
115
+ * (key) => {
116
+ * const character = getCharacterById(key)
117
+ * return character?.name
118
+ * },
119
+ * {
120
+ * name: "character-name",
121
+ * description: "Replaces character IDs with their display names",
122
+ * validation: /^[a-z_]+$/,
123
+ * type: "after-translation",
124
+ * }
125
+ * )
126
+ * // "Hello [john], meet [jane]!" -> "Hello John, meet Jane!"
127
+ * ```
128
+ */
129
+ declare namespace TextReplaces {
130
+ /**
131
+ * Configuration options for the `TextReplaces` system.
132
+ */
133
+ const options: {
134
+ /**
135
+ * The regex used to find replacement tokens in the text (e.g. `[key]`).
136
+ * @default /\[([^\]]+)\]/
137
+ */
138
+ replaceRegex: RegExp;
139
+ };
140
+ /**
141
+ * Registers a new replacement handler.
142
+ *
143
+ * Handlers are executed in the order they are added. The first handler added runs first.
144
+ *
145
+ * The {@link TranslatorManager} translation pipeline automatically calls
146
+ * {@link TextReplaces.replace} for both phases (`"before-translation"` and
147
+ * `"after-translation"`), so no additional setup is required after calling `add`.
148
+ *
149
+ * @param fn The handler function. Receives the key found inside `[...]` and should return
150
+ * the replacement string, or `undefined` to leave that token unchanged.
151
+ * @param handlerOptions Configuration for this handler, including its name, optional
152
+ * description, validation regex, and execution phase.
153
+ * @example
154
+ * ```ts title="content/text-replaces.ts"
155
+ * import { TextReplaces } from 'pixi-vn-ink'
156
+ *
157
+ * TextReplaces.add(
158
+ * (key) => key === "player" ? "Mario" : undefined,
159
+ * {
160
+ * name: "player-name",
161
+ * validation: /^player$/,
162
+ * }
163
+ * )
164
+ * ```
165
+ */
166
+ function add(fn: ReplaceHandler, handlerOptions: ReplaceHandlerOptions): void;
167
+ /**
168
+ * Removes a previously registered handler function.
169
+ *
170
+ * Only the first registration matching `fn` is removed. If the same function was added
171
+ * multiple times, subsequent registrations remain.
172
+ *
173
+ * @param fn The handler function to remove.
174
+ */
175
+ function remove(fn: ReplaceHandler): void;
176
+ /**
177
+ * Returns metadata for all registered handlers, in registration order.
178
+ *
179
+ * @returns An array of {@link ReplaceHandlerOptions} for each registered handler.
180
+ */
181
+ function info(): ReplaceHandlerOptions[];
182
+ /**
183
+ * Applica tutti gli handler registrati del tipo specificato al testo dato.
184
+ *
185
+ * Questa funzione NON esegue più la pre-elaborazione i18n automaticamente.
186
+ * Se vuoi applicare la pre-elaborazione i18n, usa prima {@link runI18nPreStep} sul testo.
187
+ *
188
+ * @param text Il testo sorgente da processare.
189
+ * @param replaceOptions Specifica quale fase di handler eseguire.
190
+ * @returns Il testo dopo che tutti gli handler sono stati applicati.
191
+ *
192
+ * @example
193
+ * // Solo handler di tipo "before-translation"
194
+ * TextReplaces.replace("Ciao [name]", { type: "before-translation" })
195
+ *
196
+ * // Con pre-elaborazione i18n:
197
+ * let t = TextReplaces.runI18nPreStep("Ciao [name]");
198
+ * t = TextReplaces.replace(t, { type: "before-translation" });
199
+ */
200
+ function replace(text: string, replaceOptions: {
201
+ /** Quale fase di handler eseguire. */
202
+ type: "after-translation" | "before-translation";
203
+ }): string;
204
+ /**
205
+ * Esegue la pre-elaborazione i18n su tutti gli handler registrati con `i18nInterpolation: true`.
206
+ *
207
+ * Per ogni handler con questa opzione, la prima occorrenza di ogni `[key]` valida viene sostituita con `{{[key]}}`.
208
+ *
209
+ * @param text Il testo da processare.
210
+ * @returns Il testo dopo la pre-elaborazione i18n.
211
+ *
212
+ * @example
213
+ * // Pre-elabora tutte le variabili i18n:
214
+ * const pre = TextReplaces.runI18nPreStep("Ciao [name]");
215
+ */
216
+ function runI18nPreStep(text: string): string;
217
+ }
218
+
6
219
  /**
7
220
  * Manages the translation pipeline for all text displayed by pixi-vn-json.
8
221
  *
@@ -13,10 +226,23 @@ import 'pixi.js';
13
226
  *
14
227
  * Use {@link TranslatorManager.t} to translate a key or array of keys.
15
228
  */
16
- declare class TranslatorManager {
17
- private static _beforeToTranslate;
18
- private static _translate;
19
- private static _afterToTranslate;
229
+ declare namespace TranslatorManager {
230
+ /**
231
+ * @deprecated
232
+ * Optional hook that runs **before** the built-in {@link TextReplaces} before-translation
233
+ * replace pass. Useful for key normalization (e.g. trimming, lowercasing).
234
+ *
235
+ * Prefer {@link TextReplaces.add} with `type: "before-translation"` instead.
236
+ */
237
+ let beforeToTranslate: ((key: string) => string) | undefined;
238
+ /**
239
+ * @deprecated
240
+ * Optional hook that runs **after** the built-in {@link TextReplaces} after-translation
241
+ * replace pass. Useful for post-processing translated strings.
242
+ *
243
+ * Prefer {@link TextReplaces.add} with `type: "after-translation"` instead.
244
+ */
245
+ let afterToTranslate: ((key: string) => string) | undefined;
20
246
  /**
21
247
  * Translates a single key or an array of keys using the registered pipeline.
22
248
  * Returns the same type (`string` or `string[]`) as the input.
@@ -24,31 +250,26 @@ declare class TranslatorManager {
24
250
  * @param key - The string key or array of string keys to translate.
25
251
  * @returns The translated string(s).
26
252
  */
27
- static t<T = string | string[]>(key: T): T;
253
+ function t<T = string | string[]>(key: T): T;
28
254
  /**
29
- * Sets a hook that runs **before** the main translation function.
30
- * Useful for key normalization (e.g. trimming, lowercasing).
255
+ * Runs the composed translation pipeline:
256
+ * 1. optional `beforeToTranslate` hook (deprecated)
257
+ * 2. {@link TextReplaces.replace} – before-translation phase
258
+ * 3. main `translate` function
259
+ * 4. optional `afterToTranslate` hook (deprecated)
260
+ * 5. {@link TextReplaces.replace} – after-translation phase
31
261
  */
32
- static set beforeToTranslate(value: (key: string) => string);
262
+ function translate(key: string): string;
33
263
  /**
34
264
  * Sets the main translation function.
35
265
  * Defaults to an identity function (returns the key unchanged).
36
266
  *
37
267
  * @example
38
268
  * ```ts
39
- * translator.translate = (key) => i18n.t(key);
269
+ * setTranslate((key) => i18n.t(key));
40
270
  * ```
41
271
  */
42
- static set translate(value: (key: string) => string);
43
- /** Returns the composed translation pipeline (before → translate → after). */
44
- static get translate(): (key: string) => string;
45
- /**
46
- * Sets a hook that runs **after** the main translation function.
47
- * Useful for post-processing translated strings (e.g. replacing placeholders).
48
- */
49
- static set afterToTranslate(value: (key: string) => string);
50
- private static addKey;
51
- private static getConditionalsThenElse;
272
+ function setTranslate(value: (key: string) => string): void;
52
273
  /**
53
274
  * Generates a JSON translation object from the provided labels.
54
275
  * @param labels The labels to translate.
@@ -56,7 +277,7 @@ declare class TranslatorManager {
56
277
  * @param options Options for translation, including default value handling.
57
278
  * @returns The populated JSON object with translations.
58
279
  */
59
- static generateJsonTranslation(labels: PixiVNJsonLabelStep[], json?: object, options?: {
280
+ function generateJsonTranslation(labels: PixiVNJsonLabelStep[], json?: object, options?: {
60
281
  /**
61
282
  * Default value to use when a key is not found.
62
283
  * - "empty_string": Use an empty string as the default value.
@@ -68,6 +289,4 @@ declare class TranslatorManager {
68
289
  }): Promise<object>;
69
290
  }
70
291
 
71
- declare const translator: typeof TranslatorManager;
72
-
73
- export { translator };
292
+ export { type ReplaceHandler, type ReplaceHandlerOptions, TextReplaces, TranslatorManager as translator };
@@ -1,8 +1,221 @@
1
+ import { ZodType } from 'zod';
1
2
  import { StepLabelPropsType } from '@drincs/pixi-vn';
2
3
  import { F as PixiVNJsonLabelStep, L as PixiVNJsonOperation } from './PixiVNJsonLabelStep-DJgORyFd.js';
3
4
  import '@drincs/pixi-vn/motion';
4
5
  import 'pixi.js';
5
6
 
7
+ /**
8
+ * A handler function invoked for each `[key]` token found in the text that passes the
9
+ * {@link ReplaceHandlerOptions.validation} check.
10
+ *
11
+ * @param key The content found inside the square brackets (without the brackets themselves).
12
+ * For example, for the token `[john]` the key is `"john"`.
13
+ * @returns The string to substitute in place of `[key]`, or `undefined` to leave the token unchanged.
14
+ */
15
+ type ReplaceHandler = (
16
+ /**
17
+ * The key to be replaced
18
+ */
19
+ key: string) => string | undefined;
20
+ /**
21
+ * Configuration options for a text-replacement handler registered via {@link TextReplaces.add}.
22
+ */
23
+ type ReplaceHandlerOptions = {
24
+ /**
25
+ * A unique name that identifies this handler.
26
+ * Used for documentation and debugging purposes.
27
+ */
28
+ name: string;
29
+ /**
30
+ * An optional human-readable description of what this handler does.
31
+ * Used for documentation purposes.
32
+ */
33
+ description?: string;
34
+ /**
35
+ * Determines whether this handler should be invoked for a given `[key]` token.
36
+ *
37
+ * - `"all"` – the handler is always invoked for every token found.
38
+ * - `"characterId"` – the handler is invoked only when the key matches a registered character ID
39
+ * (i.e. the character is present in `RegisteredCharacters`).
40
+ * - `RegExp` – the key string is tested against the regular expression. The handler is invoked
41
+ * only if the regex matches.
42
+ * - `ZodType<string>` – the key string is validated with `schema.safeParse(key)`. The handler
43
+ * is invoked only if validation succeeds.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * // RegExp: only replace keys that look like lowercase identifiers
48
+ * validation: /^[a-z_]+$/
49
+ *
50
+ * // Zod: only replace keys that are one of a fixed set of values
51
+ * import { z } from "zod"
52
+ * validation: z.enum(["player", "npc", "enemy"])
53
+ * ```
54
+ */
55
+ validation: RegExp | "characterId" | "all" | ZodType<string>;
56
+ /**
57
+ * When this handler should be invoked relative to the translation step.
58
+ *
59
+ * - `"before-translation"` – the handler runs **before** {@link onInkTranslate} is called.
60
+ * Useful for pre-processing tokens, e.g. converting `[key]` into `{{key}}` for i18next.
61
+ * - `"after-translation"` – the handler runs **after** {@link onInkTranslate} is called.
62
+ * Useful for substituting values that depend on the translated text.
63
+ *
64
+ * @default "after-translation"
65
+ */
66
+ type?: "after-translation" | "before-translation";
67
+ /**
68
+ * When `true`, the **first** occurrence of a matched `[key]` token is converted to the i18n
69
+ * double-brace format `{{[key]}}` (exactly once). Any subsequent occurrences of `[key]` in
70
+ * the same text are then replaced with the handler's return value as usual.
71
+ *
72
+ * The transformation sequence for a matched key is:
73
+ * - first occurrence: `[key]` → `{{[key]}}`
74
+ * - remaining occurrences: `[key]` → handler return value
75
+ *
76
+ * When `false` or omitted, the handler's return value directly replaces all occurrences of `[key]`.
77
+ *
78
+ * **Recommended i18n configuration:** when this option is enabled, configure
79
+ * `missingInterpolationHandler` in your i18n instance so that keys with no matching
80
+ * translation are left intact rather than replaced with an empty string:
81
+ *
82
+ * ```ts title="lib/i18n.ts"
83
+ * i18n.init({
84
+ * // ...
85
+ * missingInterpolationHandler(_text, value, _options) {
86
+ * return value[1];
87
+ * },
88
+ * });
89
+ * ```
90
+ *
91
+ * @default false
92
+ */
93
+ i18nInterpolation?: boolean;
94
+ };
95
+
96
+ /**
97
+ * Manages text replacement handlers that process content enclosed in square brackets (`[key]`).
98
+ *
99
+ * Handlers are called in the order they were added. For each handler, the current text is scanned
100
+ * for all `[key]` patterns. If the handler's `validation` matches a key, the handler is
101
+ * invoked with that key. If the handler returns a string, all occurrences of `[key]` are replaced
102
+ * with the returned value. After a handler finishes processing the text, the next handler starts
103
+ * on the updated text.
104
+ *
105
+ * Each handler specifies whether it runs before or after translation via the `type` field in its
106
+ * options (defaults to `"after-translation"`).
107
+ *
108
+ * @example
109
+ * ```ts title="content/text-replaces.ts"
110
+ * import { TextReplaces } from 'pixi-vn-ink'
111
+ * import { getCharacterById } from "@drincs/pixi-vn";
112
+ *
113
+ * // Replace [characterId] with the character's display name
114
+ * TextReplaces.add(
115
+ * (key) => {
116
+ * const character = getCharacterById(key)
117
+ * return character?.name
118
+ * },
119
+ * {
120
+ * name: "character-name",
121
+ * description: "Replaces character IDs with their display names",
122
+ * validation: /^[a-z_]+$/,
123
+ * type: "after-translation",
124
+ * }
125
+ * )
126
+ * // "Hello [john], meet [jane]!" -> "Hello John, meet Jane!"
127
+ * ```
128
+ */
129
+ declare namespace TextReplaces {
130
+ /**
131
+ * Configuration options for the `TextReplaces` system.
132
+ */
133
+ const options: {
134
+ /**
135
+ * The regex used to find replacement tokens in the text (e.g. `[key]`).
136
+ * @default /\[([^\]]+)\]/
137
+ */
138
+ replaceRegex: RegExp;
139
+ };
140
+ /**
141
+ * Registers a new replacement handler.
142
+ *
143
+ * Handlers are executed in the order they are added. The first handler added runs first.
144
+ *
145
+ * The {@link TranslatorManager} translation pipeline automatically calls
146
+ * {@link TextReplaces.replace} for both phases (`"before-translation"` and
147
+ * `"after-translation"`), so no additional setup is required after calling `add`.
148
+ *
149
+ * @param fn The handler function. Receives the key found inside `[...]` and should return
150
+ * the replacement string, or `undefined` to leave that token unchanged.
151
+ * @param handlerOptions Configuration for this handler, including its name, optional
152
+ * description, validation regex, and execution phase.
153
+ * @example
154
+ * ```ts title="content/text-replaces.ts"
155
+ * import { TextReplaces } from 'pixi-vn-ink'
156
+ *
157
+ * TextReplaces.add(
158
+ * (key) => key === "player" ? "Mario" : undefined,
159
+ * {
160
+ * name: "player-name",
161
+ * validation: /^player$/,
162
+ * }
163
+ * )
164
+ * ```
165
+ */
166
+ function add(fn: ReplaceHandler, handlerOptions: ReplaceHandlerOptions): void;
167
+ /**
168
+ * Removes a previously registered handler function.
169
+ *
170
+ * Only the first registration matching `fn` is removed. If the same function was added
171
+ * multiple times, subsequent registrations remain.
172
+ *
173
+ * @param fn The handler function to remove.
174
+ */
175
+ function remove(fn: ReplaceHandler): void;
176
+ /**
177
+ * Returns metadata for all registered handlers, in registration order.
178
+ *
179
+ * @returns An array of {@link ReplaceHandlerOptions} for each registered handler.
180
+ */
181
+ function info(): ReplaceHandlerOptions[];
182
+ /**
183
+ * Applica tutti gli handler registrati del tipo specificato al testo dato.
184
+ *
185
+ * Questa funzione NON esegue più la pre-elaborazione i18n automaticamente.
186
+ * Se vuoi applicare la pre-elaborazione i18n, usa prima {@link runI18nPreStep} sul testo.
187
+ *
188
+ * @param text Il testo sorgente da processare.
189
+ * @param replaceOptions Specifica quale fase di handler eseguire.
190
+ * @returns Il testo dopo che tutti gli handler sono stati applicati.
191
+ *
192
+ * @example
193
+ * // Solo handler di tipo "before-translation"
194
+ * TextReplaces.replace("Ciao [name]", { type: "before-translation" })
195
+ *
196
+ * // Con pre-elaborazione i18n:
197
+ * let t = TextReplaces.runI18nPreStep("Ciao [name]");
198
+ * t = TextReplaces.replace(t, { type: "before-translation" });
199
+ */
200
+ function replace(text: string, replaceOptions: {
201
+ /** Quale fase di handler eseguire. */
202
+ type: "after-translation" | "before-translation";
203
+ }): string;
204
+ /**
205
+ * Esegue la pre-elaborazione i18n su tutti gli handler registrati con `i18nInterpolation: true`.
206
+ *
207
+ * Per ogni handler con questa opzione, la prima occorrenza di ogni `[key]` valida viene sostituita con `{{[key]}}`.
208
+ *
209
+ * @param text Il testo da processare.
210
+ * @returns Il testo dopo la pre-elaborazione i18n.
211
+ *
212
+ * @example
213
+ * // Pre-elabora tutte le variabili i18n:
214
+ * const pre = TextReplaces.runI18nPreStep("Ciao [name]");
215
+ */
216
+ function runI18nPreStep(text: string): string;
217
+ }
218
+
6
219
  /**
7
220
  * Manages the translation pipeline for all text displayed by pixi-vn-json.
8
221
  *
@@ -13,10 +226,23 @@ import 'pixi.js';
13
226
  *
14
227
  * Use {@link TranslatorManager.t} to translate a key or array of keys.
15
228
  */
16
- declare class TranslatorManager {
17
- private static _beforeToTranslate;
18
- private static _translate;
19
- private static _afterToTranslate;
229
+ declare namespace TranslatorManager {
230
+ /**
231
+ * @deprecated
232
+ * Optional hook that runs **before** the built-in {@link TextReplaces} before-translation
233
+ * replace pass. Useful for key normalization (e.g. trimming, lowercasing).
234
+ *
235
+ * Prefer {@link TextReplaces.add} with `type: "before-translation"` instead.
236
+ */
237
+ let beforeToTranslate: ((key: string) => string) | undefined;
238
+ /**
239
+ * @deprecated
240
+ * Optional hook that runs **after** the built-in {@link TextReplaces} after-translation
241
+ * replace pass. Useful for post-processing translated strings.
242
+ *
243
+ * Prefer {@link TextReplaces.add} with `type: "after-translation"` instead.
244
+ */
245
+ let afterToTranslate: ((key: string) => string) | undefined;
20
246
  /**
21
247
  * Translates a single key or an array of keys using the registered pipeline.
22
248
  * Returns the same type (`string` or `string[]`) as the input.
@@ -24,31 +250,26 @@ declare class TranslatorManager {
24
250
  * @param key - The string key or array of string keys to translate.
25
251
  * @returns The translated string(s).
26
252
  */
27
- static t<T = string | string[]>(key: T): T;
253
+ function t<T = string | string[]>(key: T): T;
28
254
  /**
29
- * Sets a hook that runs **before** the main translation function.
30
- * Useful for key normalization (e.g. trimming, lowercasing).
255
+ * Runs the composed translation pipeline:
256
+ * 1. optional `beforeToTranslate` hook (deprecated)
257
+ * 2. {@link TextReplaces.replace} – before-translation phase
258
+ * 3. main `translate` function
259
+ * 4. optional `afterToTranslate` hook (deprecated)
260
+ * 5. {@link TextReplaces.replace} – after-translation phase
31
261
  */
32
- static set beforeToTranslate(value: (key: string) => string);
262
+ function translate(key: string): string;
33
263
  /**
34
264
  * Sets the main translation function.
35
265
  * Defaults to an identity function (returns the key unchanged).
36
266
  *
37
267
  * @example
38
268
  * ```ts
39
- * translator.translate = (key) => i18n.t(key);
269
+ * setTranslate((key) => i18n.t(key));
40
270
  * ```
41
271
  */
42
- static set translate(value: (key: string) => string);
43
- /** Returns the composed translation pipeline (before → translate → after). */
44
- static get translate(): (key: string) => string;
45
- /**
46
- * Sets a hook that runs **after** the main translation function.
47
- * Useful for post-processing translated strings (e.g. replacing placeholders).
48
- */
49
- static set afterToTranslate(value: (key: string) => string);
50
- private static addKey;
51
- private static getConditionalsThenElse;
272
+ function setTranslate(value: (key: string) => string): void;
52
273
  /**
53
274
  * Generates a JSON translation object from the provided labels.
54
275
  * @param labels The labels to translate.
@@ -56,7 +277,7 @@ declare class TranslatorManager {
56
277
  * @param options Options for translation, including default value handling.
57
278
  * @returns The populated JSON object with translations.
58
279
  */
59
- static generateJsonTranslation(labels: PixiVNJsonLabelStep[], json?: object, options?: {
280
+ function generateJsonTranslation(labels: PixiVNJsonLabelStep[], json?: object, options?: {
60
281
  /**
61
282
  * Default value to use when a key is not found.
62
283
  * - "empty_string": Use an empty string as the default value.
@@ -68,6 +289,4 @@ declare class TranslatorManager {
68
289
  }): Promise<object>;
69
290
  }
70
291
 
71
- declare const translator: typeof TranslatorManager;
72
-
73
- export { translator };
292
+ export { type ReplaceHandler, type ReplaceHandlerOptions, TextReplaces, TranslatorManager as translator };
@@ -1 +1 @@
1
- import {JsonUnifier}from'@drincs/pixi-vn-json/core';var P=Object.defineProperty;var V=(c,e,i)=>e in c?P(c,e,{enumerable:true,configurable:true,writable:true,value:i}):c[e]=i;var m=(c,e,i)=>V(c,typeof e!="symbol"?e+"":e,i);function E(c,e={}){let i="";return c.values.forEach(n=>{if(typeof n=="string")i+=n;else {let s=JsonUnifier.getLogichValue(n,e);i+=`${s}`;}}),i}var t=class t{static t(e){return Array.isArray(e)?e.map(i=>t.translate(`${i}`)):t.translate(`${e}`)}static set beforeToTranslate(e){t._beforeToTranslate=e;}static set translate(e){t._translate=e;}static get translate(){return e=>{let i=e;return t._beforeToTranslate&&(i=t._beforeToTranslate(i)),i=t._translate(i),t._afterToTranslate&&(i=t._afterToTranslate(i)),i}}static set afterToTranslate(e){t._afterToTranslate=e;}static addKey(e,i,n){let s=n.defaultValue||"empty_string";typeof i=="string"&&(i=[i]),Array.isArray(i)&&i.forEach(l=>{e[l]===void 0&&(s==="empty_string"?e[l]="":s==="copy_key"&&(t._beforeToTranslate?e[l]=t._beforeToTranslate(l):e[l]=l));});}static getConditionalsThenElse(e,i=[]){if(typeof e=="object"&&e&&"type"in e)if(e.type==="ifelse")e.then&&t.getConditionalsThenElse(e.then,i),e.else&&t.getConditionalsThenElse(e.else,i);else if(e.type==="stepswitch"){if(e.elements)if(Array.isArray(e.elements))e.elements.forEach(n=>{t.getConditionalsThenElse(n,i);});else if(e.elements.type==="ifelse"){let n=[];t.getConditionalsThenElse(e.elements,n),n.forEach(s=>{i.push(...s);});}else if(e.elements.type==="stepswitch"){let n=[];t.getConditionalsThenElse(e.elements,n),n.forEach(s=>{i.push(...s);});}else t.getConditionalsThenElse(e.elements,i);}else e.type==="resulttocombine"?(e.firstItem&&t.getConditionalsThenElse(e.firstItem,i),e.secondConditionalItem&&e.secondConditionalItem.forEach(n=>{t.getConditionalsThenElse(n,i);})):i.push(e);else e&&i.push(e);return i}static async generateJsonTranslation(e,i={},n={}){let{defaultValue:s="copy_key",operationStringConvert:l}=n,x=e.map(async r=>{if(r.choices){let o=[];Array.isArray(r.choices)?o=[r.choices]:o=t.getConditionalsThenElse(r.choices),o.forEach(f=>f.forEach(a=>{if("type"in a){let g=[];a.type==="ifelse"||a.type==="stepswitch"?t.getConditionalsThenElse(a,g):g=[a],g.map(p=>t.getConditionalsThenElse(p.text)).forEach(p=>{Array.isArray(p)&&p.forEach(y=>{Array.isArray(y)?y.forEach(T=>{typeof T=="string"?t.addKey(i,T,{defaultValue:s}):t.getConditionalsThenElse(T).forEach(d=>{Array.isArray(d)?d.forEach(u=>{typeof u=="string"&&t.addKey(i,u,{defaultValue:s});}):typeof d=="string"&&t.addKey(i,d,{defaultValue:s});});}):typeof y=="string"&&t.addKey(i,y,{defaultValue:s});});});}}));}if(r.dialogue){let o=[];Array.isArray(r.dialogue)?o=[r.dialogue]:o=t.getConditionalsThenElse(r.dialogue),o.forEach(f=>{if(typeof f=="string")t.addKey(i,f,{defaultValue:s});else if("text"in f){let a=t.getConditionalsThenElse(f.text);typeof a=="string"&&(a=[a]),a.forEach(g=>{typeof g=="string"?t.addKey(i,g,{defaultValue:s}):t.getConditionalsThenElse(g).forEach(p=>{typeof p=="string"?t.addKey(i,p,{defaultValue:s}):Array.isArray(p)&&p.forEach(y=>{typeof y=="string"?t.addKey(i,y,{defaultValue:s}):t.getConditionalsThenElse(y).forEach(T=>{typeof T=="string"&&t.addKey(i,T,{defaultValue:s});});});});});}});}if(r.operations)for(let o of r.operations){if(o.type==="operationtoconvert"&&l){let f=E(o),a=await l(f,r,{});if(!a)return;o=a;}o.type==="text"&&o.operationType==="show"&&t.addKey(i,o.text,{defaultValue:s});}r.conditionalStep&&t.getConditionalsThenElse(r.conditionalStep).forEach(f=>{Array.isArray(f)?t.generateJsonTranslation(f,i,n):t.generateJsonTranslation([f],i,n);});});return await Promise.all(x),i}};m(t,"_beforeToTranslate"),m(t,"_translate",e=>e),m(t,"_afterToTranslate");var h=t;var L=h;export{L as translator};
1
+ import {RegisteredCharacters}from'@drincs/pixi-vn/characters';import {ZodType}from'zod';import {JsonUnifier}from'@drincs/pixi-vn-json/core';var P;(l=>{l.options={replaceRegex:/\[([^\]]+)\]/};let p=[];function x(e,i){p.unshift({fn:e,opts:i});}l.add=x;function R(e){let i=p.findIndex(t=>t.fn===e);i!==-1&&p.splice(i,1);}l.remove=R;function S(){return p.map(e=>e.opts)}l.info=S;function w(e,i){let t=p.filter(r=>(r.opts.type??"after-translation")===i.type);for(let r of t)e=V(e,r.fn,r.opts.validation);return e}l.replace=w;function y(e){let i=p.filter(t=>t.opts.i18nInterpolation);for(let t of i)e=f(e,t.fn,t.opts);return e}l.runI18nPreStep=y;function f(e,i,t){let{validation:r}=t,u=new RegExp(l.options.replaceRegex.source,"g"),a=[...e.matchAll(u)],s=new Set,n=[];for(let o of a)s.has(o[1])||(s.add(o[1]),n.push(o[1]));for(let o of n){if(r==="characterId"){if(!RegisteredCharacters.has(o))continue}else if(r!=="all"){if(r instanceof RegExp){if(!r.test(o))continue}else if(r instanceof ZodType&&!r.safeParse(o).success)continue}i(o)!==void 0&&(e.includes(`{{[${o}]}}`)||(e=e.replaceAll(`[${o}]`,`{{[${o}]}}`)));}return e}function V(e,i,t){let r=new RegExp(l.options.replaceRegex.source,"g"),u=[...e.matchAll(r)],a=new Set,s=[];for(let n of u)a.has(n[1])||(a.add(n[1]),s.push(n[1]));for(let n of s){if(t==="characterId"){if(!RegisteredCharacters.has(n))continue}else if(t!=="all"){if(t instanceof RegExp){if(!t.test(n))continue}else if(t instanceof ZodType&&!t.safeParse(n).success)continue}let o=i(n);o!==void 0&&(e=e.replaceAll(`[${n}]`,o));}return e}})(P||(P={}));function H(d,p={}){let x="";return d.values.forEach(R=>{if(typeof R=="string")x+=R;else {let S=JsonUnifier.getLogichValue(R,p);x+=`${S}`;}}),x}var J;(l=>{let d=e=>e;function R(e){return Array.isArray(e)?e.map(i=>S(`${i}`)):S(`${e}`)}l.t=R;function S(e){let i=e;return l.beforeToTranslate&&(i=(0, l.beforeToTranslate)(i)),i=P.replace(i,{type:"before-translation"}),i=d(i),l.afterToTranslate&&(i=(0, l.afterToTranslate)(i)),i=P.replace(i,{type:"after-translation"}),i}l.translate=S;function w(e){d=e;}l.setTranslate=w;function y(e,i,t){let{defaultValue:r="empty_string"}=t;typeof i=="string"&&(i=[i]),Array.isArray(i)&&i.forEach(u=>{let a=u;if(l.beforeToTranslate&&(a=(0, l.beforeToTranslate)(a)),r==="empty_string")e[a]===void 0&&(e[a]="");else if(r==="copy_key"){let s=u;l.beforeToTranslate&&(s=(0, l.beforeToTranslate)(s));let n=P.runI18nPreStep(s);n=P.replace(n,{type:"before-translation"}),e[a]=n;}});}function f(e,i=[]){if(typeof e=="object"&&e&&"type"in e)if(e.type==="ifelse")e.then&&f(e.then,i),e.else&&f(e.else,i);else if(e.type==="stepswitch"){if(e.elements)if(Array.isArray(e.elements))e.elements.forEach(t=>{f(t,i);});else if(e.elements.type==="ifelse"){let t=[];f(e.elements,t),t.forEach(r=>{i.push(...r);});}else if(e.elements.type==="stepswitch"){let t=[];f(e.elements,t),t.forEach(r=>{i.push(...r);});}else f(e.elements,i);}else e.type==="resulttocombine"?(e.firstItem&&f(e.firstItem,i),e.secondConditionalItem&&e.secondConditionalItem.forEach(t=>{f(t,i);})):i.push(e);else e&&i.push(e);return i}async function V(e,i={},t={}){let{defaultValue:r="copy_key",operationStringConvert:u}=t,a=e.map(async s=>{if(s.choices){let n=[];Array.isArray(s.choices)?n=[s.choices]:n=f(s.choices),n.forEach(o=>{o.forEach(c=>{if("type"in c){let m=[];c.type==="ifelse"||c.type==="stepswitch"?f(c,m):m=[c],m.map(g=>f(g.text)).forEach(g=>{Array.isArray(g)&&g.forEach(h=>{Array.isArray(h)?h.forEach(E=>{typeof E=="string"?y(i,E,{defaultValue:r}):f(E).forEach(A=>{Array.isArray(A)?A.forEach(T=>{typeof T=="string"&&y(i,T,{defaultValue:r});}):typeof A=="string"&&y(i,A,{defaultValue:r});});}):typeof h=="string"&&y(i,h,{defaultValue:r});});});}});});}if(s.dialogue){let n=[];Array.isArray(s.dialogue)?n=[s.dialogue]:n=f(s.dialogue),n.forEach(o=>{if(typeof o=="string")y(i,o,{defaultValue:r});else if("text"in o){let c=f(o.text);typeof c=="string"&&(c=[c]),c.forEach(m=>{typeof m=="string"?y(i,m,{defaultValue:r}):f(m).forEach(g=>{typeof g=="string"?y(i,g,{defaultValue:r}):Array.isArray(g)&&g.forEach(h=>{typeof h=="string"?y(i,h,{defaultValue:r}):f(h).forEach(E=>{typeof E=="string"&&y(i,E,{defaultValue:r});});});});});}});}if(s.operations)for(let n of s.operations){if(n.type==="operationtoconvert"&&u){let o=H(n),c=await u(o,s,{});if(!c)return;n=c;}n.type==="text"&&n.operationType==="show"&&y(i,n.text,{defaultValue:r});}s.conditionalStep&&f(s.conditionalStep).forEach(o=>{Array.isArray(o)?V(o,i,t):V([o],i,t);});});return await Promise.all(a),i}l.generateJsonTranslation=V;})(J||(J={}));var _=J;export{P as TextReplaces,_ as translator};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drincs/pixi-vn-json",
3
- "version": "1.13.8",
3
+ "version": "1.13.9",
4
4
  "type": "module",
5
5
  "description": "Pixi'VN can be integrated with JSON files to create a visual novel.",
6
6
  "main": "./dist/index.cjs",