@gmitch215/tinyimg 1.0.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.
@@ -0,0 +1,345 @@
1
+ /**
2
+ * The option and error vocabulary the wrapper speaks.
3
+ *
4
+ * The names mirror Cloudflare Images' own transformation parameters wherever there is one to mirror,
5
+ * because the point of the library is to do that work inside the Worker instead of paying for it:
6
+ * a caller moving off the binding should be able to keep the option object they already have.
7
+ */
8
+ /** A container format, mirroring `TinyImageFormat`. */
9
+ export type ImageFormat = 'png' | 'jpeg' | 'bmp' | 'gif' | 'tiff' | 'webp' | 'avif' | 'heif';
10
+ /**
11
+ * How an aspect mismatch is absorbed, mirroring `TinyImageFit`.
12
+ *
13
+ * The eleven are two independent choices read as one: whether the mismatch is left, cropped, padded
14
+ * or distorted, and whether the scale may rise, fall, both or neither.
15
+ */
16
+ export type Fit = 'scale-down' | 'contain' | 'cover' | 'crop' | 'aspect-crop' | 'aspect-contain' | 'aspect-cover' | 'pad' | 'stretch' | 'fill' | 'scale-up';
17
+ /**
18
+ * Which part of an image a crop keeps, mirroring `TinyImageGravity`.
19
+ *
20
+ * `auto` weights the image by local detail and centers on the result. `face` runs the detector and
21
+ * centers on what it finds, falling back to `auto` when no cascade is loaded or nothing is found;
22
+ * see {@link TinyImgModule.loadBlob}.
23
+ */
24
+ export type Gravity = 'center' | 'north' | 'south' | 'west' | 'east' | 'north-west' | 'north-east' | 'south-west' | 'south-east' | 'auto' | 'face';
25
+ /** Which weights a resample reads through, mirroring `TinyResampleFilter`. */
26
+ export type ResampleFilter = 'auto' | 'nearest' | 'bilinear' | 'box' | 'catmull-rom';
27
+ /** Which axes a flip mirrors. */
28
+ export type FlipAxis = 'horizontal' | 'vertical' | 'both';
29
+ /** What to do with metadata on encode. */
30
+ export type MetadataPolicy = 'keep' | 'none';
31
+ /**
32
+ * A color.
33
+ *
34
+ * Either CSS-style hex (`'#rgb'`, `'#rrggbb'`, `'#rrggbbaa'`, with or without the hash) or channel
35
+ * values as numbers. A three number array is RGB and a four is RGBA; a single number is gray.
36
+ */
37
+ export type Color = string | readonly number[];
38
+ /**
39
+ * Everything a one-shot transformation can ask for.
40
+ *
41
+ * Every field is optional and an empty object is a valid request: it decodes and re-encodes. The
42
+ * order the operations run in is fixed and documented on {@link transform}, because an option
43
+ * object has no order of its own and two callers writing the same keys have to get the same image.
44
+ */
45
+ export interface TransformOptions {
46
+ /** Target width in pixels. With `height` unset, the aspect ratio is kept. */
47
+ width?: number;
48
+ /** Target height in pixels. With `width` unset, the aspect ratio is kept. */
49
+ height?: number;
50
+ /** How an aspect mismatch is absorbed. Only read when both `width` and `height` are set. */
51
+ fit?: Fit;
52
+ /** Which part a crop keeps, or where a pad puts the image. */
53
+ gravity?: Gravity;
54
+ /** Weights the resample reads through. `auto` is an area average down and a cubic up. */
55
+ filter?: ResampleFilter;
56
+ /** Source rectangle, taken before anything else. */
57
+ crop?: Rect;
58
+ /** Multiplies `width` and `height`, for serving a retina variant of one request. */
59
+ dpr?: number;
60
+ /** Quarter turns clockwise. Anything else is rejected; use {@link Image.rotateFree}. */
61
+ rotate?: 0 | 90 | 180 | 270;
62
+ /** Which axes to mirror. */
63
+ flip?: FlipAxis;
64
+ /** Scales every channel. 1 is unchanged. */
65
+ brightness?: number;
66
+ /** Scales every channel about mid gray. 1 is unchanged. */
67
+ contrast?: number;
68
+ /** Moves every channel toward or away from its luminance. 1 is unchanged. */
69
+ saturation?: number;
70
+ /** Rotates the hue, in degrees. */
71
+ hue?: number;
72
+ /** Raises every channel to a power. 1 is unchanged. */
73
+ gamma?: number;
74
+ /** Replaces every channel with the pixel's luminance. */
75
+ grayscale?: boolean;
76
+ /** Subtracts every channel from full scale, leaving alpha alone. */
77
+ invert?: boolean;
78
+ /** Gaussian blur radius in pixels. */
79
+ blur?: number;
80
+ /** Unsharp mask amount. */
81
+ sharpen?: number;
82
+ /** Trims a uniform border, at this tolerance. `true` means a tolerance of 8. */
83
+ trim?: boolean | number;
84
+ /** Fills whatever a pad or a rotation leaves empty. */
85
+ background?: Color;
86
+ /**
87
+ * Container to encode as. Defaults to the source's own format.
88
+ *
89
+ * `'auto'` picks one. On its own that is WebP, which is the better artifact. With
90
+ * {@link TransformOptions.budgetMs} it becomes the best format that fits the budget, which
91
+ * matters because the encoders differ by about a factor of five per sample.
92
+ */
93
+ format?: ImageFormat | 'auto';
94
+ /**
95
+ * How much computation the encoder may spend. `'fancy'` is the default.
96
+ *
97
+ * A separate axis from {@link TransformOptions.quality}: quality says what the output should
98
+ * look like, this says how hard to work to get there. See the `effort` option on
99
+ * `Image.bytes` for what each format gives up and what it was measured to cost.
100
+ */
101
+ effort?: 'fancy' | 'fast';
102
+ /**
103
+ * A CPU budget in milliseconds, which changes what `format: 'auto'` chooses.
104
+ *
105
+ * The Workers Free plan allows 10 milliseconds of CPU per request and it is not configurable,
106
+ * so a request either fits or fails; there is no paying slightly more. Give a budget below the
107
+ * limit rather than at it, since the estimate behind the choice is accurate to about 20%.
108
+ *
109
+ * An explicitly named `format` is never substituted, however far over budget it is: naming one
110
+ * is a decision, and this option does not overrule it.
111
+ */
112
+ budgetMs?: number;
113
+ /** Quality for a lossy format, 1 through 100. */
114
+ quality?: number;
115
+ /** Use a format's lossless mode where it has one. */
116
+ lossless?: boolean;
117
+ /** Write a progressive or interlaced stream. */
118
+ progressive?: boolean;
119
+ /** Whether to carry EXIF and other metadata into the output. Defaults to `keep`. */
120
+ metadata?: MetadataPolicy;
121
+ }
122
+ /** A rectangle in pixels. */
123
+ export interface Rect {
124
+ /** Left edge. */
125
+ x: number;
126
+ /** Top edge. */
127
+ y: number;
128
+ /** Width. */
129
+ width: number;
130
+ /** Height. */
131
+ height: number;
132
+ }
133
+ /** An extent in pixels. */
134
+ export interface Extent {
135
+ /** Width. */
136
+ width: number;
137
+ /** Height. */
138
+ height: number;
139
+ }
140
+ /** Kinds of data the library reads but does not ship, mirroring `TinyBlobKind`. */
141
+ export type BlobKind = 'font' | 'icc' | 'cascade';
142
+ /** What a decoded image is, without its pixels. */
143
+ export interface ImageInfo {
144
+ /** Width in pixels. */
145
+ width: number;
146
+ /** Height in pixels. */
147
+ height: number;
148
+ /** Frames the file holds; 1 for a still image. */
149
+ frames: number;
150
+ /** The format the magic bytes identified. */
151
+ format: ImageFormat | 'unknown';
152
+ /** Channels a full decode would produce. */
153
+ channels: number;
154
+ /** Bits per channel in the file, before decoding normalizes them to 8. */
155
+ bitDepth: number;
156
+ /** Whether the file carries transparency. */
157
+ hasAlpha: boolean;
158
+ /** Whether this is a progressive JPEG, which cannot stream a region. */
159
+ progressive: boolean;
160
+ }
161
+ /** Decoded samples, with the extent they describe. */
162
+ export interface RawImage {
163
+ /** Width in pixels. */
164
+ width: number;
165
+ /** Height in pixels. */
166
+ height: number;
167
+ /** Bytes per pixel, 1 through 4. */
168
+ channels: number;
169
+ /** `width * height * channels` bytes, rows tightly packed. */
170
+ pixels: Uint8Array<ArrayBuffer>;
171
+ }
172
+ /** One detection, in the coordinates of the image that was searched. */
173
+ export interface FaceBox extends Rect {
174
+ /**
175
+ * Overlapping raw detections this box was formed from.
176
+ *
177
+ * A usable ranking: a face the cascade is confident about fires at several nearby positions and
178
+ * scales, so the highest is the most likely to be a face.
179
+ */
180
+ neighbors: number;
181
+ }
182
+ /** What the planner decided, before any pixel was touched. */
183
+ export interface PlanDecision {
184
+ /** The region of the source the decoder was asked for. */
185
+ region: Rect;
186
+ /** The subsampling denominator the decoder was asked for: 1, 2, 4 or 8. */
187
+ scale: number;
188
+ /** Extent the decode produced. */
189
+ decoded: Extent;
190
+ /** Extent of the final image, and how many channels it carries. */
191
+ output: Extent & {
192
+ /** Channels per pixel, 1 through 4. */
193
+ channels: number;
194
+ };
195
+ /** Operations left after the rewrites. */
196
+ operations: number;
197
+ /** Operations an identity or annihilation rule removed. */
198
+ eliminated: number;
199
+ /** Operations a pair rule merged into another. */
200
+ collapsed: number;
201
+ /** Color stages the operations collapsed into. */
202
+ colorStages: number;
203
+ /** Fused passes the run will make. */
204
+ passes: number;
205
+ /** Special cases the planner took, by name. */
206
+ kernels: string[];
207
+ /**
208
+ * What running this plan is expected to cost in milliseconds, before any encoder.
209
+ *
210
+ * An estimate and not a promise: the rates behind it were measured on one machine, and against
211
+ * real transforms it lands within about 20%. That is the accuracy the question needs when the
212
+ * question is whether work will fit inside a CPU limit, and it is not a substitute for
213
+ * measuring, which {@link TinyImgModule.measure} does.
214
+ *
215
+ * 0 when the source header could not be read.
216
+ */
217
+ estimateMs: number;
218
+ }
219
+ /**
220
+ * A failed call.
221
+ *
222
+ * Every failure carries the module's own error code, so a caller can branch on the code rather than
223
+ * on a message, and the subclasses group the codes a caller is likely to treat the same way.
224
+ */
225
+ export declare class TinyImgError extends Error {
226
+ /** The error's class, for a caller matching on it without instanceof. */
227
+ readonly name: string;
228
+ /** The negative `TinyImageError` the module returned. */
229
+ readonly code: number;
230
+ /** The short, stable name the module carries for that code. */
231
+ readonly codeName: string;
232
+ constructor(code: number, codeName: string, context?: string);
233
+ }
234
+ /** An argument was NULL, outside its range, or a rectangle fell outside the image. */
235
+ export declare class TinyImgArgumentError extends TinyImgError {
236
+ /** The error's class, for a caller matching on it without instanceof. */
237
+ readonly name = "TinyImgArgumentError";
238
+ }
239
+ /** The bytes are not a format this build can read, or not a variant of it that it can. */
240
+ export declare class TinyImgFormatError extends TinyImgError {
241
+ /** The error's class, for a caller matching on it without instanceof. */
242
+ readonly name = "TinyImgFormatError";
243
+ }
244
+ /** The bitstream is malformed, truncated or internally inconsistent. */
245
+ export declare class TinyImgDataError extends TinyImgError {
246
+ /** The error's class, for a caller matching on it without instanceof. */
247
+ readonly name = "TinyImgDataError";
248
+ }
249
+ /**
250
+ * The allocator could not satisfy a request, or the image is past the budget.
251
+ *
252
+ * The two are separate codes because the remedy differs, so the budget one is
253
+ * {@link TinyImgTooLargeError}, a subclass. Catching this catches both.
254
+ */
255
+ export declare class TinyImgMemoryError extends TinyImgError {
256
+ /** The error's class, for a caller matching on it without instanceof. */
257
+ readonly name: string;
258
+ }
259
+ /**
260
+ * The image is past the pixel or byte budget, so no amount of memory would help.
261
+ *
262
+ * The remedy is a smaller decode rather than a bigger heap: ask for a region, a scale denominator,
263
+ * or a transformation whose output fits. A plain {@link TinyImgMemoryError} means the allocator ran
264
+ * out on a request that was within budget, which is a different problem.
265
+ */
266
+ export declare class TinyImgTooLargeError extends TinyImgMemoryError {
267
+ /** The error's class, for a caller matching on it without instanceof. */
268
+ readonly name = "TinyImgTooLargeError";
269
+ }
270
+ /** The operation needs a blob nobody has loaded; see {@link TinyImgModule.loadBlob}. */
271
+ export declare class TinyImgBlobError extends TinyImgError {
272
+ /** The error's class, for a caller matching on it without instanceof. */
273
+ readonly name = "TinyImgBlobError";
274
+ }
275
+ /** The plan is full, or holds an operation that cannot be combined with the others in it. */
276
+ export declare class TinyImgPlanError extends TinyImgError {
277
+ /** The error's class, for a caller matching on it without instanceof. */
278
+ readonly name = "TinyImgPlanError";
279
+ }
280
+ /** Error codes, mirroring `enum TinyImageError`. */
281
+ export declare const Err: {
282
+ /** The call succeeded. */
283
+ readonly ok: 0;
284
+ /** A required pointer argument was NULL. */
285
+ readonly null: -1;
286
+ /** An argument was outside its documented range. */
287
+ readonly range: -2;
288
+ /** Coordinates or a rectangle fell outside the image. */
289
+ readonly bounds: -3;
290
+ /** The allocator could not satisfy a request. */
291
+ readonly memory: -4;
292
+ /** The image exceeds the pixel budget; reach for a scaled decode. */
293
+ readonly tooLarge: -5;
294
+ /** The buffer matched no format tinyimg recognizes. */
295
+ readonly unknownFormat: -6;
296
+ /** Recognized, and this build cannot decode or encode it. */
297
+ readonly unsupportedCodec: -7;
298
+ /** The bitstream is malformed, truncated or inconsistent. */
299
+ readonly corrupt: -8;
300
+ /** Supported format, unsupported variant of it. */
301
+ readonly unsupportedVariant: -9;
302
+ /** The output buffer was too small. */
303
+ readonly bufferTooSmall: -10;
304
+ /** A font, profile or cascade nobody has loaded. */
305
+ readonly blobMissing: -11;
306
+ /** The image has no channel the operation needs. */
307
+ readonly noChannel: -12;
308
+ /** The requested key or metadata entry does not exist. */
309
+ readonly notFound: -13;
310
+ /** The plan is full, or holds an operation it cannot combine. */
311
+ readonly plan: -14;
312
+ };
313
+ /**
314
+ * Builds the error for a code.
315
+ *
316
+ * The mapping lives here rather than beside the module so the classes and the codes they cover stay
317
+ * in one place; `codeName` comes from the module, which is the only thing that knows it.
318
+ *
319
+ * @param code The negative code the module returned.
320
+ * @param codeName What the module calls it.
321
+ * @param context What was being attempted, for the message.
322
+ * @return The error to throw. Never returns for a code of zero, which is not a failure.
323
+ */
324
+ export declare function errorFor(code: number, codeName: string, context?: string): TinyImgError;
325
+ /** Anything the wrapper will take as an image or a blob. */
326
+ export type Source = Uint8Array | ArrayBuffer | ArrayBufferView | Blob | Response | ReadableStream<Uint8Array>;
327
+ /**
328
+ * Reads any accepted source into bytes.
329
+ *
330
+ * A caller should never have to reach for a `Response.arrayBuffer()` or drain a stream themselves to
331
+ * hand this library an image; every shape a Worker is likely to be holding one in is accepted.
332
+ *
333
+ * @param source The image or blob.
334
+ * @return Its bytes.
335
+ */
336
+ export declare function readSource(source: Source): Promise<Uint8Array>;
337
+ /**
338
+ * Turns a color into channel bytes.
339
+ *
340
+ * @param color The color.
341
+ * @param channels How many the image has.
342
+ * @return Exactly `channels` bytes.
343
+ */
344
+ export declare function readColor(color: Color, channels: number): Uint8Array;
345
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/ts/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,uDAAuD;AACvD,MAAM,MAAM,WAAW,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AAE7F;;;;;GAKG;AACH,MAAM,MAAM,GAAG,GACZ,YAAY,GACZ,SAAS,GACT,OAAO,GACP,MAAM,GACN,aAAa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GAAG;IACf,0BAA0B;;IAE1B,4CAA4C;;IAE5C,oDAAoD;;IAEpD,yDAAyD;;IAEzD,iDAAiD;;IAEjD,qEAAqE;;IAErE,uDAAuD;;IAEvD,6DAA6D;;IAE7D,6DAA6D;;IAE7D,mDAAmD;;IAEnD,uCAAuC;;IAEvC,oDAAoD;;IAEpD,oDAAoD;;IAEpD,0DAA0D;;IAE1D,iEAAiE;;CAExD,CAAC;AAEX;;;;;;;;;;GAUG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,YAAY,CAyBvF;AAED,4DAA4D;AAC5D,MAAM,MAAM,MAAM,GACjB,UAAU,GAAG,WAAW,GAAG,eAAe,GAAG,IAAI,GAAG,QAAQ,GAAG,cAAc,CAAC,UAAU,CAAC,CAAC;AAE3F;;;;;;;;GAQG;AACH,wBAAsB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAsBpE;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,GAAG,UAAU,CA+CpE"}
package/dist/types.js ADDED
@@ -0,0 +1,132 @@
1
+ export class TinyImgError extends Error {
2
+ name = 'TinyImgError';
3
+ code;
4
+ codeName;
5
+ constructor(code, codeName, context) {
6
+ super(context ? `${context}: ${codeName}` : codeName);
7
+ this.code = code;
8
+ this.codeName = codeName;
9
+ }
10
+ }
11
+ export class TinyImgArgumentError extends TinyImgError {
12
+ name = 'TinyImgArgumentError';
13
+ }
14
+ export class TinyImgFormatError extends TinyImgError {
15
+ name = 'TinyImgFormatError';
16
+ }
17
+ export class TinyImgDataError extends TinyImgError {
18
+ name = 'TinyImgDataError';
19
+ }
20
+ export class TinyImgMemoryError extends TinyImgError {
21
+ name = 'TinyImgMemoryError';
22
+ }
23
+ export class TinyImgTooLargeError extends TinyImgMemoryError {
24
+ name = 'TinyImgTooLargeError';
25
+ }
26
+ export class TinyImgBlobError extends TinyImgError {
27
+ name = 'TinyImgBlobError';
28
+ }
29
+ export class TinyImgPlanError extends TinyImgError {
30
+ name = 'TinyImgPlanError';
31
+ }
32
+ export const Err = {
33
+ ok: 0,
34
+ null: -1,
35
+ range: -2,
36
+ bounds: -3,
37
+ memory: -4,
38
+ tooLarge: -5,
39
+ unknownFormat: -6,
40
+ unsupportedCodec: -7,
41
+ corrupt: -8,
42
+ unsupportedVariant: -9,
43
+ bufferTooSmall: -10,
44
+ blobMissing: -11,
45
+ noChannel: -12,
46
+ notFound: -13,
47
+ plan: -14
48
+ };
49
+ export function errorFor(code, codeName, context) {
50
+ switch (code) {
51
+ case Err.null:
52
+ case Err.range:
53
+ case Err.bounds:
54
+ case Err.noChannel:
55
+ case Err.bufferTooSmall:
56
+ return new TinyImgArgumentError(code, codeName, context);
57
+ case Err.unknownFormat:
58
+ case Err.unsupportedCodec:
59
+ case Err.unsupportedVariant:
60
+ return new TinyImgFormatError(code, codeName, context);
61
+ case Err.corrupt:
62
+ return new TinyImgDataError(code, codeName, context);
63
+ case Err.memory:
64
+ return new TinyImgMemoryError(code, codeName, context);
65
+ case Err.tooLarge:
66
+ return new TinyImgTooLargeError(code, codeName, context);
67
+ case Err.blobMissing:
68
+ return new TinyImgBlobError(code, codeName, context);
69
+ case Err.plan:
70
+ return new TinyImgPlanError(code, codeName, context);
71
+ default:
72
+ return new TinyImgError(code, codeName, context);
73
+ }
74
+ }
75
+ export async function readSource(source) {
76
+ if (source instanceof Uint8Array)
77
+ return source;
78
+ if (source instanceof ArrayBuffer)
79
+ return new Uint8Array(source);
80
+ if (source instanceof Response) {
81
+ if (!source.body)
82
+ throw new TypeError('the Response has no body');
83
+ return new Uint8Array(await source.arrayBuffer());
84
+ }
85
+ if (typeof Blob !== 'undefined' && source instanceof Blob) {
86
+ return new Uint8Array(await source.arrayBuffer());
87
+ }
88
+ if (source instanceof ReadableStream) {
89
+ return new Uint8Array(await new Response(source).arrayBuffer());
90
+ }
91
+ if (ArrayBuffer.isView(source)) {
92
+ return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
93
+ }
94
+ throw new TypeError('expected bytes, an ArrayBuffer, a Blob, a Response or a ReadableStream');
95
+ }
96
+ export function readColor(color, channels) {
97
+ const out = new Uint8Array(channels);
98
+ if (typeof color !== 'string') {
99
+ const values = [...color];
100
+ if (values.length === 0)
101
+ throw new TypeError('the color has no channels');
102
+ for (let i = 0; i < channels; i++) {
103
+ const value = values[Math.min(i, values.length - 1)];
104
+ out[i] = Math.max(0, Math.min(255, Math.round(value)));
105
+ }
106
+ if ((channels === 2 || channels === 4) && values.length < channels) {
107
+ out[channels - 1] = 255;
108
+ }
109
+ return out;
110
+ }
111
+ const hex = color.startsWith('#') ? color.slice(1) : color;
112
+ const wide = hex.length <= 4 ? [...hex].map((digit) => digit + digit).join('') : hex;
113
+ if (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(wide)) {
114
+ throw new TypeError(`'${color}' is not a hex color`);
115
+ }
116
+ const rgba = [
117
+ parseInt(wide.slice(0, 2), 16),
118
+ parseInt(wide.slice(2, 4), 16),
119
+ parseInt(wide.slice(4, 6), 16),
120
+ wide.length === 8 ? parseInt(wide.slice(6, 8), 16) : 255
121
+ ];
122
+ if (channels >= 3) {
123
+ for (let i = 0; i < channels; i++)
124
+ out[i] = rgba[i === 3 ? 3 : i];
125
+ return out;
126
+ }
127
+ out[0] = Math.round(0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2]);
128
+ if (channels === 2)
129
+ out[1] = rgba[3];
130
+ return out;
131
+ }
132
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/ts/types.ts"],"names":[],"mappings":"AA4QA,MAAM,OAAO,YAAa,SAAQ,KAAK;IAEpB,IAAI,GAAW,cAAc,CAAC;IAGvC,IAAI,CAAS;IAG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