@codexo/exojs-aseprite 0.19.0 → 0.20.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.
package/README.md CHANGED
@@ -11,12 +11,12 @@ npm install --save-exact @codexo/exojs @codexo/exojs-aseprite
11
11
  Core is a peer dependency. Add `asepriteExtension` to the application; importing the package alone does not install a loader.
12
12
 
13
13
  ```ts
14
- import { Application, Asset, Scene } from '@codexo/exojs';
14
+ import { Application, Scene } from '@codexo/exojs';
15
15
  import { asepriteExtension } from '@codexo/exojs-aseprite';
16
16
 
17
17
  class CharacterScene extends Scene {
18
18
  override async load(): Promise<void> {
19
- const sheet = await this.loader.load(Asset.type('asepriteSheet', 'sprites/hero.json'));
19
+ const sheet = await this.loader.load({ type: 'asepriteSheet', source: 'sprites/hero.json' });
20
20
  const character = sheet.createAnimatedSprite();
21
21
 
22
22
  if (sheet.clips.has('walk')) {
@@ -28,7 +28,10 @@ export interface AsepriteFrameData {
28
28
  * `from` and `to` are inclusive zero-based frame indices.
29
29
  */
30
30
  export interface AsepriteFrameTag {
31
+ /** Tag colour from the editor, as `#RRGGBBAA`. */
31
32
  readonly color?: string;
33
+ /** Free-form user data attached to the tag in the editor. */
34
+ readonly data?: string;
32
35
  readonly direction: AsepriteDirection;
33
36
  /** Inclusive end frame index. */
34
37
  readonly to: number;
@@ -62,17 +65,49 @@ export interface AsepriteLayer {
62
65
  /** Layer opacity in `[0, 255]` (Aseprite's own scale, not `[0, 1]`). */
63
66
  readonly opacity?: number;
64
67
  }
65
- /** Bounds of a named slice at a specific frame. */
68
+ /** A point in sprite canvas pixels. */
69
+ export interface AsepritePoint {
70
+ readonly x: number;
71
+ readonly y: number;
72
+ }
73
+ /**
74
+ * A slice's shape from one frame on, until the next key. Every rectangle and
75
+ * point is in pixels of the untrimmed sprite canvas.
76
+ */
66
77
  export interface AsepriteSliceKey {
67
78
  readonly bounds: AsepriteRect;
79
+ /** Nine-slice centre, relative to {@link bounds}; present only on nine-slices. */
80
+ readonly center?: AsepriteRect;
68
81
  readonly frame: number;
82
+ /** Pivot point, relative to {@link bounds}; present only when one was set. */
83
+ readonly pivot?: AsepritePoint;
69
84
  }
70
85
  /** A named slice defined in the Aseprite editor. */
71
86
  export interface AsepriteSlice {
87
+ /** Slice colour from the editor, as `#RRGGBBAA`. */
72
88
  readonly color?: string;
89
+ /** Free-form user data attached to the slice in the editor. */
90
+ readonly data?: string;
91
+ /** Keys in ascending frame order. */
73
92
  readonly keys: readonly AsepriteSliceKey[];
74
93
  readonly name: string;
75
94
  }
95
+ /**
96
+ * A slice as it stands on one frame: the key in effect there, joined with the
97
+ * slice's own colour and user data. Returned by {@link AsepriteSheet.getSlice}.
98
+ */
99
+ export interface AsepriteSliceFrame {
100
+ readonly name: string;
101
+ /** The frame the key in effect was set on, at or before the requested frame. */
102
+ readonly keyFrame: number;
103
+ readonly bounds: AsepriteRect;
104
+ /** Nine-slice centre, relative to {@link bounds}. */
105
+ readonly center?: AsepriteRect;
106
+ /** Pivot point, relative to {@link bounds}. */
107
+ readonly pivot?: AsepritePoint;
108
+ readonly color?: string;
109
+ readonly data?: string;
110
+ }
76
111
  /** Metadata block of an Aseprite JSON export. */
77
112
  export interface AsepriteMeta {
78
113
  readonly app: string;
@@ -1 +1 @@
1
- {"version":3,"file":"AsepriteData.d.ts","sourceRoot":"","sources":["../../src/AsepriteData.ts"],"names":[],"mappings":"AAIA,6DAA6D;AAC7D,MAAM,MAAM,iBAAiB,GAAG,SAAS,GAAG,UAAU,GAAG,kBAAkB,GAAG,SAAS,CAAC;AAExF,uEAAuE;AACvE,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,8DAA8D;AAC9D,MAAM,WAAW,Y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QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;CAC7B;AAED;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,iBAAiB,GAAG,gBAAgB,CAAC;AAEhE,wEAAwE;AACxE,eAAO,MAAM,mBAAmB,SAAU,YAAY,KAAG,IAAI,IAAI,iBAA+C,CAAC"}
@@ -1,7 +1,6 @@
1
- //#region src/AsepriteData.ts
1
+ // src/AsepriteData.ts
2
2
  /** Returns `true` when `data` is in array mode (frames is an array). */
3
3
  const isAsepriteArrayData = (data) => Array.isArray(data.frames);
4
4
 
5
- //#endregion
6
5
  export { isAsepriteArrayData };
7
6
  //# sourceMappingURL=AsepriteData.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AsepriteData.js","names":[],"sources":["../../src/AsepriteData.ts"],"sourcesContent":["// TypeScript types for the Aseprite JSON sprite sheet export format.\n// Supports both array mode (frames is an ordered array) and hash mode\n// (frames is an object keyed by frame name / filename).\n\n/** Playback direction of an Aseprite frame tag animation. */\nexport type AsepriteDirection = 'forward' | 'pingpong' | 'pingpong_reverse' | 'reverse';\n\n/** Pixel region rectangle used throughout the Aseprite JSON format. */\nexport interface AsepriteRect {\n readonly h: number;\n readonly w: number;\n readonly x: number;\n readonly y: number;\n}\n\n/** Width/height size descriptor used in Aseprite metadata. */\nexport interface AsepriteSize {\n readonly h: number;\n readonly w: number;\n}\n\n/** A single animation frame in the Aseprite JSON export. */\nexport interface AsepriteFrameData {\n /** Display duration of this frame in milliseconds. */\n readonly duration: number;\n /** Pixel region of this frame within the packed sprite sheet texture. */\n readonly frame: AsepriteRect;\n readonly rotated: boolean;\n readonly sourceSize: AsepriteSize;\n readonly spriteSourceSize: AsepriteRect;\n readonly trimmed: boolean;\n}\n\n/**\n * A named animation range defined via Aseprite frame tags.\n * `from` and `to` are inclusive zero-based frame indices.\n */\nexport interface AsepriteFrameTag {\n readonly color?: string;\n readonly direction: AsepriteDirection;\n /** Inclusive end frame index. */\n readonly to: number;\n /** Inclusive start frame index. */\n readonly from: number;\n readonly name: string;\n /**\n * Number of times the tag plays before stopping, as a numeric string\n * (e.g. `\"1\"`, `\"2\"`). Absent means the tag loops indefinitely.\n */\n readonly repeat?: string;\n}\n\n/**\n * A single layer entry in the Aseprite JSON metadata (`meta.layers`).\n *\n * Only `name` is guaranteed. `opacity` and `blendMode` describe an image\n * layer's compositing and can both be absent (a group layer has neither), and\n * `color`/`data` carry the layer's editor user data when it was set. `group`\n * names the enclosing group layer and is absent at the top level, so the flat\n * array encodes the layer tree by parent name.\n */\nexport interface AsepriteLayer {\n readonly blendMode?: string;\n /** Layer colour tag from the editor, as `#RRGGBBAA`. */\n readonly color?: string;\n /** Free-form user data attached to the layer in the editor. */\n readonly data?: string;\n /** Name of the enclosing group layer; absent for a top-level layer. */\n readonly group?: string;\n readonly name: string;\n /** Layer opacity in `[0, 255]` (Aseprite's own scale, not `[0, 1]`). */\n readonly opacity?: number;\n}\n\n/** Bounds of a named slice at a specific frame. */\nexport interface AsepriteSliceKey {\n readonly bounds: AsepriteRect;\n readonly frame: number;\n}\n\n/** A named slice defined in the Aseprite editor. */\nexport interface AsepriteSlice {\n readonly color?: string;\n readonly keys: readonly AsepriteSliceKey[];\n readonly name: string;\n}\n\n/** Metadata block of an Aseprite JSON export. */\nexport interface AsepriteMeta {\n readonly app: string;\n readonly format: string;\n readonly frameTags?: readonly AsepriteFrameTag[];\n /** Relative path to the exported sprite sheet image. */\n readonly image: string;\n readonly layers?: readonly AsepriteLayer[];\n readonly scale: string;\n readonly size: AsepriteSize;\n readonly slices?: readonly AsepriteSlice[];\n readonly version: string;\n}\n\n/** Aseprite JSON export in array mode - frames is an ordered array. */\nexport interface AsepriteArrayData {\n readonly frames: readonly AsepriteFrameData[];\n readonly meta: AsepriteMeta;\n}\n\n/** Aseprite JSON export in hash mode - frames is an object keyed by frame name. */\nexport interface AsepriteHashData {\n readonly frames: Readonly<Record<string, AsepriteFrameData>>;\n readonly meta: AsepriteMeta;\n}\n\n/**\n * Union of both Aseprite JSON export formats.\n *\n * Use {@link isAsepriteArrayData} to discriminate between array and hash mode.\n */\nexport type AsepriteData = AsepriteArrayData | AsepriteHashData;\n\n/** Returns `true` when `data` is in array mode (frames is an array). */\nexport const isAsepriteArrayData = (data: AsepriteData): data is AsepriteArrayData => Array.isArray(data.frames);\n"],"mappings":";;AAyHA,MAAa,uBAAuB,SAAkD,MAAM,QAAQ,KAAK,MAAM"}
1
+ {"version":3,"file":"AsepriteData.js","names":[],"sources":["../../src/AsepriteData.ts"],"sourcesContent":["// TypeScript types for the Aseprite JSON sprite sheet export format.\n// Supports both array mode (frames is an ordered array) and hash mode\n// (frames is an object keyed by frame name / filename).\n\n/** Playback direction of an Aseprite frame tag animation. */\nexport type AsepriteDirection = 'forward' | 'pingpong' | 'pingpong_reverse' | 'reverse';\n\n/** Pixel region rectangle used throughout the Aseprite JSON format. */\nexport interface AsepriteRect {\n readonly h: number;\n readonly w: number;\n readonly x: number;\n readonly y: number;\n}\n\n/** Width/height size descriptor used in Aseprite metadata. */\nexport interface AsepriteSize {\n readonly h: number;\n readonly w: number;\n}\n\n/** A single animation frame in the Aseprite JSON export. */\nexport interface AsepriteFrameData {\n /** Display duration of this frame in milliseconds. */\n readonly duration: number;\n /** Pixel region of this frame within the packed sprite sheet texture. */\n readonly frame: AsepriteRect;\n readonly rotated: boolean;\n readonly sourceSize: AsepriteSize;\n readonly spriteSourceSize: AsepriteRect;\n readonly trimmed: boolean;\n}\n\n/**\n * A named animation range defined via Aseprite frame tags.\n * `from` and `to` are inclusive zero-based frame indices.\n */\nexport interface AsepriteFrameTag {\n /** Tag colour from the editor, as `#RRGGBBAA`. */\n readonly color?: string;\n /** Free-form user data attached to the tag in the editor. */\n readonly data?: string;\n readonly direction: AsepriteDirection;\n /** Inclusive end frame index. */\n readonly to: number;\n /** Inclusive start frame index. */\n readonly from: number;\n readonly name: string;\n /**\n * Number of times the tag plays before stopping, as a numeric string\n * (e.g. `\"1\"`, `\"2\"`). Absent means the tag loops indefinitely.\n */\n readonly repeat?: string;\n}\n\n/**\n * A single layer entry in the Aseprite JSON metadata (`meta.layers`).\n *\n * Only `name` is guaranteed. `opacity` and `blendMode` describe an image\n * layer's compositing and can both be absent (a group layer has neither), and\n * `color`/`data` carry the layer's editor user data when it was set. `group`\n * names the enclosing group layer and is absent at the top level, so the flat\n * array encodes the layer tree by parent name.\n */\nexport interface AsepriteLayer {\n readonly blendMode?: string;\n /** Layer colour tag from the editor, as `#RRGGBBAA`. */\n readonly color?: string;\n /** Free-form user data attached to the layer in the editor. */\n readonly data?: string;\n /** Name of the enclosing group layer; absent for a top-level layer. */\n readonly group?: string;\n readonly name: string;\n /** Layer opacity in `[0, 255]` (Aseprite's own scale, not `[0, 1]`). */\n readonly opacity?: number;\n}\n\n/** A point in sprite canvas pixels. */\nexport interface AsepritePoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * A slice's shape from one frame on, until the next key. Every rectangle and\n * point is in pixels of the untrimmed sprite canvas.\n */\nexport interface AsepriteSliceKey {\n readonly bounds: AsepriteRect;\n /** Nine-slice centre, relative to {@link bounds}; present only on nine-slices. */\n readonly center?: AsepriteRect;\n readonly frame: number;\n /** Pivot point, relative to {@link bounds}; present only when one was set. */\n readonly pivot?: AsepritePoint;\n}\n\n/** A named slice defined in the Aseprite editor. */\nexport interface AsepriteSlice {\n /** Slice colour from the editor, as `#RRGGBBAA`. */\n readonly color?: string;\n /** Free-form user data attached to the slice in the editor. */\n readonly data?: string;\n /** Keys in ascending frame order. */\n readonly keys: readonly AsepriteSliceKey[];\n readonly name: string;\n}\n\n/**\n * A slice as it stands on one frame: the key in effect there, joined with the\n * slice's own colour and user data. Returned by {@link AsepriteSheet.getSlice}.\n */\nexport interface AsepriteSliceFrame {\n readonly name: string;\n /** The frame the key in effect was set on, at or before the requested frame. */\n readonly keyFrame: number;\n readonly bounds: AsepriteRect;\n /** Nine-slice centre, relative to {@link bounds}. */\n readonly center?: AsepriteRect;\n /** Pivot point, relative to {@link bounds}. */\n readonly pivot?: AsepritePoint;\n readonly color?: string;\n readonly data?: string;\n}\n\n/** Metadata block of an Aseprite JSON export. */\nexport interface AsepriteMeta {\n readonly app: string;\n readonly format: string;\n readonly frameTags?: readonly AsepriteFrameTag[];\n /** Relative path to the exported sprite sheet image. */\n readonly image: string;\n readonly layers?: readonly AsepriteLayer[];\n readonly scale: string;\n readonly size: AsepriteSize;\n readonly slices?: readonly AsepriteSlice[];\n readonly version: string;\n}\n\n/** Aseprite JSON export in array mode - frames is an ordered array. */\nexport interface AsepriteArrayData {\n readonly frames: readonly AsepriteFrameData[];\n readonly meta: AsepriteMeta;\n}\n\n/** Aseprite JSON export in hash mode - frames is an object keyed by frame name. */\nexport interface AsepriteHashData {\n readonly frames: Readonly<Record<string, AsepriteFrameData>>;\n readonly meta: AsepriteMeta;\n}\n\n/**\n * Union of both Aseprite JSON export formats.\n *\n * Use {@link isAsepriteArrayData} to discriminate between array and hash mode.\n */\nexport type AsepriteData = AsepriteArrayData | AsepriteHashData;\n\n/** Returns `true` when `data` is in array mode (frames is an array). */\nexport const isAsepriteArrayData = (data: AsepriteData): data is AsepriteArrayData => Array.isArray(data.frames);\n"],"mappings":";;AA8JA,MAAa,uBAAuB,SAAkD,MAAM,QAAQ,KAAK,MAAM"}
@@ -1,5 +1,5 @@
1
1
  import { AnimatedSprite, type AnimatedSpriteClipDefinition, Spritesheet, type Texture } from '@codexo/exojs';
2
- import { type AsepriteData, type AsepriteLayer, type AsepriteSlice } from './AsepriteData';
2
+ import { type AsepriteData, type AsepriteFrameTag, type AsepriteLayer, type AsepriteSlice, type AsepriteSliceFrame } from './AsepriteData';
3
3
  /**
4
4
  * Parsed representation of an Aseprite JSON sprite sheet export.
5
5
  *
@@ -8,14 +8,15 @@ import { type AsepriteData, type AsepriteLayer, type AsepriteSlice } from './Ase
8
8
  * (keyed by zero-based index string: `"0"`, `"1"`, ...).
9
9
  * - A `clips` map of {@link AnimatedSpriteClipDefinition} entries built from
10
10
  * `meta.frameTags`, one per named tag.
11
- * - The `slices` and `layers` metadata maps, carried through verbatim.
11
+ * - The `slices`, `layers` and `tags` metadata maps, carried through verbatim,
12
+ * and {@link getSlice} to read a slice on a given frame.
12
13
  *
13
14
  * Call {@link createAnimatedSprite} to obtain a ready-to-use
14
15
  * {@link AnimatedSprite} with all clips pre-registered.
15
16
  *
16
17
  * @example
17
18
  * ```ts
18
- * const sheet = await loader.load(Asset.type('asepriteSheet', 'hero.aseprite.json'));
19
+ * const sheet = await loader.load({ type: 'asepriteSheet', source: 'hero.aseprite.json' });
19
20
  * const sprite = sheet.createAnimatedSprite();
20
21
  * sprite.play('run');
21
22
  * scene.addChild(sprite);
@@ -35,8 +36,8 @@ export declare class AsepriteSheet {
35
36
  * name. Slices describe editor-defined regions - hitboxes, nine-patch
36
37
  * borders, UI anchor points - that aren't part of the frame/animation
37
38
  * data itself. Each {@link AsepriteSlice} carries one {@link AsepriteSliceKey}
38
- * per frame at which its bounds change; consumers resolve the applicable
39
- * key for a given frame index themselves.
39
+ * per frame at which its bounds change; {@link getSlice} resolves the key
40
+ * in effect on a given frame.
40
41
  */
41
42
  readonly slices: ReadonlyMap<string, AsepriteSlice>;
42
43
  /**
@@ -51,6 +52,37 @@ export declare class AsepriteSheet {
51
52
  * unique within an Aseprite document, so keying by name loses nothing.
52
53
  */
53
54
  readonly layers: ReadonlyMap<string, AsepriteLayer>;
55
+ /**
56
+ * Frame tags from the Aseprite `meta.frameTags` metadata, keyed by tag
57
+ * name, with the editor colour and user data that {@link clips} do not
58
+ * carry. Empty when the export has no tags.
59
+ */
60
+ readonly tags: ReadonlyMap<string, AsepriteFrameTag>;
61
+ /**
62
+ * For every clip in {@link clips}, the sheet frame index of each of its
63
+ * frames, in play order: the index an {@link AnimatedSprite}'s
64
+ * `currentFrame` selects. Use it to look up per-frame metadata such as
65
+ * {@link getSlice} for the frame being shown.
66
+ */
67
+ readonly clipFrameIndices: ReadonlyMap<string, readonly number[]>;
68
+ /**
69
+ * The shape slice `name` has on sheet frame `frameIndex`: its most recent
70
+ * key at or before that frame, with the slice's colour and user data.
71
+ * `null` when the sheet has no such slice or the slice starts later.
72
+ *
73
+ * Rectangles and points retain the export's untrimmed source-canvas pixels.
74
+ * For clips carrying `sourceSize`, divide by the texture asset's resolution
75
+ * to compare them with logical local bounds. Metadata-free clips retain
76
+ * legacy trim-offset units; this method always returns authored source
77
+ * pixels. The pivot and nine-slice centre stay relative to the bounds.
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * const frame = sheet.clipFrameIndices.get(sprite.currentClip!)![sprite.currentFrame]!;
82
+ * const hitbox = sheet.getSlice('hitbox', frame);
83
+ * ```
84
+ */
85
+ getSlice(name: string, frameIndex: number): AsepriteSliceFrame | null;
54
86
  /**
55
87
  * Parse a raw {@link AsepriteData} document and the already-loaded
56
88
  * {@link Texture} into an {@link AsepriteSheet}.
@@ -74,9 +106,12 @@ export declare class AsepriteSheet {
74
106
  * non-positive), so uneven hold-frames survive into playback instead of
75
107
  * being flattened to a uniform fps. `frameOffsets` carries each frame's
76
108
  * `spriteSourceSize` `{x,y}` - its trimmed content's offset within the
77
- * untrimmed canvas - whenever any frame in the tag is trimmed, so frames
78
- * trimmed by different amounts stay anchored instead of jittering; it's
79
- * omitted entirely for tags with no trimmed frames.
109
+ * untrimmed canvas - whenever any frame in the tag is trimmed; it's omitted
110
+ * for tags with no trimmed frames. `sourceSize` preserves the original canvas
111
+ * for every tag, including transparent padding, so anchors and scale remain
112
+ * stable across tags. When `sourceSize` is present, both are converted to
113
+ * logical pixels using the loaded texture's asset resolution. Older input
114
+ * without it retains the legacy raw offsets and inferred-canvas fallback.
80
115
  */
81
116
  static parse(data: AsepriteData, texture: Texture): AsepriteSheet;
82
117
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"AsepriteSheet.d.ts","sourceRoot":"","sources":["../../src/AsepriteSheet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,KAAK,4BAA4B,EAAE,WAAW,EAAE,KA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CAAC;IAEzE;;;;;;;OAOG;IACH,SAAgB,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAE3D;;;;;;;;;;OAUG;IACH,SAAgB,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAE3D;;;;OAIG;IACH,SAAgB,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IAE5D;;;;;OAKG;IACH,SAAgB,gBAAgB,EAAE,WAAW,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;IAuBzE;;;;;;;;;;;;;;;;OAgBG;IACI,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,kBAAkB,GAAG,IAAI,CAuB3E;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6BG;IACH,OAAc,KAAK,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,aAAa,CAwHvE;IAED;;;;;;OAMG;IACI,oBAAoB,IAAI,cAAc,CAQ5C;IAED,kFAAkF;IAC3E,OAAO,IAAI,IAAI,CAErB;CACF"}
@@ -1,7 +1,7 @@
1
1
  import { isAsepriteArrayData } from "./AsepriteData.js";
2
2
  import { AnimatedSprite, Spritesheet, Time } from "@codexo/exojs";
3
3
 
4
- //#region src/AsepriteSheet.ts
4
+ // src/AsepriteSheet.ts
5
5
  /**
6
6
  * Normalises an {@link AsepriteData} document into an ordered array of
7
7
  * {@link AsepriteFrameData} entries regardless of whether the JSON was
@@ -79,14 +79,15 @@ const resolveTaggedFrames = (frameArray, indices) => {
79
79
  * (keyed by zero-based index string: `"0"`, `"1"`, ...).
80
80
  * - A `clips` map of {@link AnimatedSpriteClipDefinition} entries built from
81
81
  * `meta.frameTags`, one per named tag.
82
- * - The `slices` and `layers` metadata maps, carried through verbatim.
82
+ * - The `slices`, `layers` and `tags` metadata maps, carried through verbatim,
83
+ * and {@link getSlice} to read a slice on a given frame.
83
84
  *
84
85
  * Call {@link createAnimatedSprite} to obtain a ready-to-use
85
86
  * {@link AnimatedSprite} with all clips pre-registered.
86
87
  *
87
88
  * @example
88
89
  * ```ts
89
- * const sheet = await loader.load(Asset.type('asepriteSheet', 'hero.aseprite.json'));
90
+ * const sheet = await loader.load({ type: 'asepriteSheet', source: 'hero.aseprite.json' });
90
91
  * const sprite = sheet.createAnimatedSprite();
91
92
  * sprite.play('run');
92
93
  * scene.addChild(sprite);
@@ -106,8 +107,8 @@ var AsepriteSheet = class AsepriteSheet {
106
107
  * name. Slices describe editor-defined regions - hitboxes, nine-patch
107
108
  * borders, UI anchor points - that aren't part of the frame/animation
108
109
  * data itself. Each {@link AsepriteSlice} carries one {@link AsepriteSliceKey}
109
- * per frame at which its bounds change; consumers resolve the applicable
110
- * key for a given frame index themselves.
110
+ * per frame at which its bounds change; {@link getSlice} resolves the key
111
+ * in effect on a given frame.
111
112
  */
112
113
  slices;
113
114
  /**
@@ -123,15 +124,62 @@ var AsepriteSheet = class AsepriteSheet {
123
124
  */
124
125
  layers;
125
126
  /**
127
+ * Frame tags from the Aseprite `meta.frameTags` metadata, keyed by tag
128
+ * name, with the editor colour and user data that {@link clips} do not
129
+ * carry. Empty when the export has no tags.
130
+ */
131
+ tags;
132
+ /**
133
+ * For every clip in {@link clips}, the sheet frame index of each of its
134
+ * frames, in play order: the index an {@link AnimatedSprite}'s
135
+ * `currentFrame` selects. Use it to look up per-frame metadata such as
136
+ * {@link getSlice} for the frame being shown.
137
+ */
138
+ clipFrameIndices;
139
+ /**
126
140
  * @internal - use {@link AsepriteSheet.parse} to create instances.
127
141
  * The public modifier is required for the Loader's `AssetConstructor` token
128
142
  * contract; users should call `parse()` instead of constructing directly.
129
143
  */
130
- constructor(spritesheet, clips, slices, layers = /* @__PURE__ */ new Map()) {
144
+ constructor(spritesheet, clips, slices, layers = /* @__PURE__ */ new Map(), tags = /* @__PURE__ */ new Map(), clipFrameIndices = /* @__PURE__ */ new Map()) {
131
145
  this.spritesheet = spritesheet;
132
146
  this.clips = clips;
133
147
  this.slices = slices;
134
148
  this.layers = layers;
149
+ this.tags = tags;
150
+ this.clipFrameIndices = clipFrameIndices;
151
+ }
152
+ /**
153
+ * The shape slice `name` has on sheet frame `frameIndex`: its most recent
154
+ * key at or before that frame, with the slice's colour and user data.
155
+ * `null` when the sheet has no such slice or the slice starts later.
156
+ *
157
+ * Rectangles and points retain the export's untrimmed source-canvas pixels.
158
+ * For clips carrying `sourceSize`, divide by the texture asset's resolution
159
+ * to compare them with logical local bounds. Metadata-free clips retain
160
+ * legacy trim-offset units; this method always returns authored source
161
+ * pixels. The pivot and nine-slice centre stay relative to the bounds.
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * const frame = sheet.clipFrameIndices.get(sprite.currentClip!)![sprite.currentFrame]!;
166
+ * const hitbox = sheet.getSlice('hitbox', frame);
167
+ * ```
168
+ */
169
+ getSlice(name, frameIndex) {
170
+ const slice = this.slices.get(name);
171
+ let current;
172
+ for (const key of slice?.keys ?? []) if (key.frame <= frameIndex && (current === void 0 || key.frame >= current.frame)) current = key;
173
+ if (slice === void 0 || current === void 0) return null;
174
+ return {
175
+ name,
176
+ keyFrame: current.frame,
177
+ bounds: current.bounds,
178
+ ...current.center !== void 0 && { center: current.center },
179
+ ...current.pivot !== void 0 && { pivot: current.pivot },
180
+ ...slice.color !== void 0 && { color: slice.color },
181
+ ...slice.data !== void 0 && { data: slice.data }
182
+ };
135
183
  }
136
184
  /**
137
185
  * Parse a raw {@link AsepriteData} document and the already-loaded
@@ -156,29 +204,54 @@ var AsepriteSheet = class AsepriteSheet {
156
204
  * non-positive), so uneven hold-frames survive into playback instead of
157
205
  * being flattened to a uniform fps. `frameOffsets` carries each frame's
158
206
  * `spriteSourceSize` `{x,y}` - its trimmed content's offset within the
159
- * untrimmed canvas - whenever any frame in the tag is trimmed, so frames
160
- * trimmed by different amounts stay anchored instead of jittering; it's
161
- * omitted entirely for tags with no trimmed frames.
207
+ * untrimmed canvas - whenever any frame in the tag is trimmed; it's omitted
208
+ * for tags with no trimmed frames. `sourceSize` preserves the original canvas
209
+ * for every tag, including transparent padding, so anchors and scale remain
210
+ * stable across tags. When `sourceSize` is present, both are converted to
211
+ * logical pixels using the loaded texture's asset resolution. Older input
212
+ * without it retains the legacy raw offsets and inferred-canvas fallback.
162
213
  */
163
214
  static parse(data, texture) {
164
215
  const frameArray = normaliseFrames(data);
216
+ let resolution = 1;
217
+ if (texture.width > 0) resolution = texture.width / texture.logicalWidth;
218
+ else if (texture.height > 0) resolution = texture.height / texture.logicalHeight;
165
219
  const spritesheetFrames = {};
166
220
  for (const [i, frameData] of frameArray.entries()) spritesheetFrames[String(i)] = { frame: frameData.frame };
167
221
  const spritesheet = new Spritesheet(texture, { frames: spritesheetFrames });
168
222
  const clips = /* @__PURE__ */ new Map();
223
+ const clipFrameIndices = /* @__PURE__ */ new Map();
224
+ const tags = /* @__PURE__ */ new Map();
169
225
  const frameTags = data.meta.frameTags ?? [];
170
226
  for (const tag of frameTags) {
171
227
  const taggedFrames = resolveTaggedFrames(frameArray, expandFrameIndices(tag));
172
228
  const frames = taggedFrames.map(({ index }) => spritesheet.getFrame(String(index)));
229
+ tags.set(tag.name, tag);
173
230
  if (frames.length === 0) continue;
174
- const repeat = tag.repeat !== void 0 ? Number(tag.repeat) : -1;
231
+ const parsedRepeat = tag.repeat !== void 0 ? Number(tag.repeat) : -1;
232
+ const repeat = parsedRepeat === 0 ? -1 : parsedRepeat;
175
233
  const fps = avgFps(taggedFrames);
176
234
  const frameDurations = taggedFrames.map(({ frameData }) => Time.seconds(frameData.duration > 0 ? frameData.duration / 1e3 : 1 / fps));
177
- const frameOffsets = taggedFrames.some(({ frameData }) => frameData.trimmed) ? taggedFrames.map(({ frameData }) => {
235
+ let sourceSize = {
236
+ width: 0,
237
+ height: 0
238
+ };
239
+ for (const { frameData } of taggedFrames) {
240
+ const size = frameData.sourceSize;
241
+ if (size === void 0) {
242
+ sourceSize = void 0;
243
+ break;
244
+ }
245
+ sourceSize.width = Math.max(sourceSize.width, size.w / resolution);
246
+ sourceSize.height = Math.max(sourceSize.height, size.h / resolution);
247
+ }
248
+ const anyTrimmed = taggedFrames.some(({ frameData }) => frameData.trimmed);
249
+ const offsetResolution = sourceSize === void 0 ? 1 : resolution;
250
+ const frameOffsets = anyTrimmed ? taggedFrames.map(({ frameData }) => {
178
251
  const { x, y } = frameData.spriteSourceSize;
179
252
  return {
180
- x,
181
- y
253
+ x: x / offsetResolution,
254
+ y: y / offsetResolution
182
255
  };
183
256
  }) : void 0;
184
257
  clips.set(tag.name, {
@@ -186,14 +259,16 @@ var AsepriteSheet = class AsepriteSheet {
186
259
  frames,
187
260
  repeat,
188
261
  frameDurations,
189
- ...frameOffsets ? { frameOffsets } : {}
262
+ ...frameOffsets ? { frameOffsets } : {},
263
+ ...sourceSize ? { sourceSize } : {}
190
264
  });
265
+ clipFrameIndices.set(tag.name, taggedFrames.map(({ index }) => index));
191
266
  }
192
267
  const slices = /* @__PURE__ */ new Map();
193
268
  for (const slice of data.meta.slices ?? []) slices.set(slice.name, slice);
194
269
  const layers = /* @__PURE__ */ new Map();
195
270
  for (const layer of data.meta.layers ?? []) layers.set(layer.name, layer);
196
- return new AsepriteSheet(spritesheet, clips, slices, layers);
271
+ return new AsepriteSheet(spritesheet, clips, slices, layers, tags, clipFrameIndices);
197
272
  }
198
273
  /**
199
274
  * Create an {@link AnimatedSprite} with all frame-tag clips pre-defined.
@@ -213,6 +288,5 @@ var AsepriteSheet = class AsepriteSheet {
213
288
  }
214
289
  };
215
290
 
216
- //#endregion
217
291
  export { AsepriteSheet };
218
292
  //# sourceMappingURL=AsepriteSheet.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AsepriteSheet.js","names":[],"sources":["../../src/AsepriteSheet.ts"],"sourcesContent":["import { AnimatedSprite, type AnimatedSpriteClipDefinition, Spritesheet, type Texture, Time } from '@codexo/exojs';\n\nimport { type AsepriteData, type AsepriteFrameData, type AsepriteFrameTag, type AsepriteLayer, type AsepriteSlice, isAsepriteArrayData } from './AsepriteData';\n\n/**\n * Normalises an {@link AsepriteData} document into an ordered array of\n * {@link AsepriteFrameData} entries regardless of whether the JSON was\n * produced in array or hash mode.\n */\nconst normaliseFrames = (data: AsepriteData): AsepriteFrameData[] => {\n if (isAsepriteArrayData(data)) {\n return [...data.frames];\n }\n\n return Object.values(data.frames);\n};\n\n/**\n * Expands a frame tag's inclusive `[from, to]` range into the ordered\n * sequence of frame indices it actually plays, according to its\n * {@link AsepriteDirection}. Indices are not bounds-checked against the\n * frame array here; callers filter out-of-range entries separately.\n *\n * - `forward`: `[from, from+1, ..., to]`.\n * - `reverse`: `[to, to-1, ..., from]`.\n * - `pingpong`: a forward pass followed by a backward pass that excludes\n * both endpoints, e.g. `[0,1,2]` becomes `[0,1,2,1]`.\n * - `pingpong_reverse`: the mirrored shape, starting from `to`.\n * - A single-frame tag (`from === to`) always yields just that one frame.\n */\nconst expandFrameIndices = (tag: AsepriteFrameTag): number[] => {\n const { from, to } = tag;\n\n if (from === to) {\n return [from];\n }\n\n const indices: number[] = [];\n\n switch (tag.direction) {\n case 'reverse':\n for (let i = to; i >= from; i--) indices.push(i);\n break;\n\n case 'pingpong':\n for (let i = from; i <= to; i++) indices.push(i);\n for (let i = to - 1; i > from; i--) indices.push(i);\n break;\n\n case 'pingpong_reverse':\n for (let i = to; i >= from; i--) indices.push(i);\n for (let i = from + 1; i < to; i++) indices.push(i);\n break;\n\n case 'forward':\n default:\n for (let i = from; i <= to; i++) indices.push(i);\n break;\n }\n\n return indices;\n};\n\n/**\n * Calculates the average frames-per-second for a sequence of frame indices,\n * based on the per-frame `duration` field (milliseconds per frame) exported\n * by Aseprite. Every occurrence of an index counts toward the average - for\n * ping-pong sequences that means repeated (bounced) frames are weighted twice.\n * Falls back to `12` fps when all durations are zero or the sequence is empty.\n */\nconst avgFps = (frames: TaggedFrame[]): number => {\n if (frames.length === 0) {\n return 12;\n }\n\n const totalMs = frames.reduce((sum, { frameData }) => sum + frameData.duration, 0);\n const avgMs = totalMs / frames.length;\n\n return avgMs > 0 ? 1000 / avgMs : 12;\n};\n\n/**\n * A frame a tag actually resolved to, paired with the index it came from.\n * Resolving index and data together is what keeps every per-frame array below\n * (durations, offsets, spritesheet lookups) aligned without re-indexing.\n */\ninterface TaggedFrame {\n index: number;\n frameData: AsepriteFrameData;\n}\n\n/**\n * Resolves a tag's frame indices against the frame array, dropping any that\n * fall outside it - Aseprite exports can reference frames a later edit removed.\n */\nconst resolveTaggedFrames = (frameArray: AsepriteFrameData[], indices: number[]): TaggedFrame[] => {\n const resolved: TaggedFrame[] = [];\n\n for (const index of indices) {\n const frameData = frameArray[index];\n\n if (frameData !== undefined) {\n resolved.push({ index, frameData });\n }\n }\n\n return resolved;\n};\n\n/**\n * Parsed representation of an Aseprite JSON sprite sheet export.\n *\n * `AsepriteSheet.parse(data, texture)` converts the raw JSON document into:\n * - A {@link Spritesheet} whose frames correspond to the Aseprite frame array\n * (keyed by zero-based index string: `\"0\"`, `\"1\"`, ...).\n * - A `clips` map of {@link AnimatedSpriteClipDefinition} entries built from\n * `meta.frameTags`, one per named tag.\n * - The `slices` and `layers` metadata maps, carried through verbatim.\n *\n * Call {@link createAnimatedSprite} to obtain a ready-to-use\n * {@link AnimatedSprite} with all clips pre-registered.\n *\n * @example\n * ```ts\n * const sheet = await loader.load(Asset.type('asepriteSheet', 'hero.aseprite.json'));\n * const sprite = sheet.createAnimatedSprite();\n * sprite.play('run');\n * scene.addChild(sprite);\n * ```\n */\nexport class AsepriteSheet {\n /** The underlying {@link Spritesheet} whose frames are keyed by index string. */\n public readonly spritesheet: Spritesheet;\n\n /**\n * Animation clips derived from the Aseprite `frameTags` metadata.\n * Each clip's frames are live references into {@link spritesheet.frames};\n * they are cloned automatically when passed to {@link AnimatedSprite.addClip}.\n */\n public readonly clips: ReadonlyMap<string, AnimatedSpriteClipDefinition>;\n\n /**\n * Named slices from the Aseprite `meta.slices` metadata, keyed by slice\n * name. Slices describe editor-defined regions - hitboxes, nine-patch\n * borders, UI anchor points - that aren't part of the frame/animation\n * data itself. Each {@link AsepriteSlice} carries one {@link AsepriteSliceKey}\n * per frame at which its bounds change; consumers resolve the applicable\n * key for a given frame index themselves.\n */\n public readonly slices: ReadonlyMap<string, AsepriteSlice>;\n\n /**\n * Layers from the Aseprite `meta.layers` metadata, keyed by layer name and\n * in export order (bottom-most first). Aseprite packs the sheet already\n * composited, so these are descriptive rather than renderable: they tell a\n * consumer which layers went into a frame and how - opacity, blend mode,\n * editor user data - and {@link AsepriteLayer.group} names the enclosing\n * group layer, so the flat map still encodes the layer tree.\n *\n * Empty when the export carries no `meta.layers` block. Layer names are\n * unique within an Aseprite document, so keying by name loses nothing.\n */\n public readonly layers: ReadonlyMap<string, AsepriteLayer>;\n\n /**\n * @internal - use {@link AsepriteSheet.parse} to create instances.\n * The public modifier is required for the Loader's `AssetConstructor` token\n * contract; users should call `parse()` instead of constructing directly.\n */\n public constructor(\n spritesheet: Spritesheet,\n clips: ReadonlyMap<string, AnimatedSpriteClipDefinition>,\n slices: ReadonlyMap<string, AsepriteSlice>,\n layers: ReadonlyMap<string, AsepriteLayer> = new Map(),\n ) {\n this.spritesheet = spritesheet;\n this.clips = clips;\n this.slices = slices;\n this.layers = layers;\n }\n\n /**\n * Parse a raw {@link AsepriteData} document and the already-loaded\n * {@link Texture} into an {@link AsepriteSheet}.\n *\n * Supports both Aseprite array mode and hash mode. Frame indices from\n * `frameTags` are resolved against the ordered frame array; out-of-range\n * indices are silently skipped.\n *\n * A tag's `direction` determines the expanded frame sequence fed into the\n * clip - `forward` and `reverse` play the `[from, to]` range in order or\n * in reverse, while `pingpong`/`pingpong_reverse` append a backward pass\n * (excluding both endpoints) so the bounce plays back correctly on the\n * engine's forward-only {@link AnimatedSprite} playback. The tag's\n * `repeat` field maps directly onto {@link AnimatedSpriteClipDefinition.repeat}:\n * absent means the clip loops indefinitely (`repeat: -1`); a numeric\n * string (`\"1\"`, `\"2\"`, ...) means it plays exactly that many full cycles\n * before stopping.\n *\n * Each clip's `frameDurations` carries the real per-frame `duration` from\n * the export (falling back to the tag's average when a frame's duration is\n * non-positive), so uneven hold-frames survive into playback instead of\n * being flattened to a uniform fps. `frameOffsets` carries each frame's\n * `spriteSourceSize` `{x,y}` - its trimmed content's offset within the\n * untrimmed canvas - whenever any frame in the tag is trimmed, so frames\n * trimmed by different amounts stay anchored instead of jittering; it's\n * omitted entirely for tags with no trimmed frames.\n */\n public static parse(data: AsepriteData, texture: Texture): AsepriteSheet {\n const frameArray = normaliseFrames(data);\n\n // Build SpritesheetData: frame names are zero-based index strings.\n const spritesheetFrames: Record<string, { frame: { x: number; y: number; w: number; h: number } }> = {};\n\n for (const [i, frameData] of frameArray.entries()) {\n spritesheetFrames[String(i)] = { frame: frameData.frame };\n }\n\n const spritesheet = new Spritesheet(texture, { frames: spritesheetFrames });\n\n // Build clips from frameTags, resolving frame indices into Rectangles.\n const clips = new Map<string, AnimatedSpriteClipDefinition>();\n const frameTags = data.meta.frameTags ?? [];\n\n for (const tag of frameTags) {\n // Out-of-range indices are silently skipped; `taggedFrames` parallels\n // `frames` exactly, so it's the basis for every other per-frame array\n // (durations, offsets) built below.\n const taggedFrames = resolveTaggedFrames(frameArray, expandFrameIndices(tag));\n const frames = taggedFrames.map(({ index }) => spritesheet.getFrame(String(index)));\n\n if (frames.length === 0) {\n continue;\n }\n\n // Aseprite's `tag.repeat` (a numeric string, `'1'` through any N) maps\n // directly onto the engine's `repeat` count. Absent means the tag\n // loops indefinitely, the engine's `-1` sentinel.\n const repeat = tag.repeat !== undefined ? Number(tag.repeat) : -1;\n const fps = avgFps(taggedFrames);\n\n // Per-frame hold duration (Aseprite \"duration\"), so uneven hold-frames\n // (e.g. a lingering idle frame) survive into playback instead of being\n // flattened to the tag's average fps. A non-positive duration (same\n // degenerate case `avgFps` guards against) falls back to the average -\n // computed as `1 / fps` directly, not `(1000 / fps) / 1000`, so it is\n // bit-for-bit the reciprocal of the fps this clip actually carries.\n const frameDurations = taggedFrames.map(({ frameData }) => Time.seconds(frameData.duration > 0 ? frameData.duration / 1000 : 1 / fps));\n\n // Per-frame trim offset (Aseprite \"spriteSourceSize\"), so frames trimmed\n // by different amounts stay anchored to the same point in the untrimmed\n // canvas instead of jittering frame to frame. Omitted entirely when no\n // frame in the tag is trimmed, to avoid noise on untrimmed sheets.\n const anyTrimmed = taggedFrames.some(({ frameData }) => frameData.trimmed);\n const frameOffsets = anyTrimmed\n ? taggedFrames.map(({ frameData }) => {\n const { x, y } = frameData.spriteSourceSize;\n\n return { x, y };\n })\n : undefined;\n\n clips.set(tag.name, {\n fps,\n frames,\n repeat,\n frameDurations,\n ...(frameOffsets ? { frameOffsets } : {}),\n });\n }\n\n // Build the slices map from meta.slices, keyed by slice name.\n const slices = new Map<string, AsepriteSlice>();\n\n for (const slice of data.meta.slices ?? []) {\n slices.set(slice.name, slice);\n }\n\n // Same for meta.layers - insertion order is the export order, so the map\n // doubles as the ordered layer list.\n const layers = new Map<string, AsepriteLayer>();\n\n for (const layer of data.meta.layers ?? []) {\n layers.set(layer.name, layer);\n }\n\n return new AsepriteSheet(spritesheet, clips, slices, layers);\n }\n\n /**\n * Create an {@link AnimatedSprite} with all frame-tag clips pre-defined.\n *\n * Each clip is registered via {@link AnimatedSprite.addClip}, which\n * clones the frame {@link Rectangle}s so the sprite owns its own copies.\n * Call {@link AnimatedSprite.play} with a tag name to start playback.\n */\n public createAnimatedSprite(): AnimatedSprite {\n const sprite = new AnimatedSprite(this.spritesheet.texture);\n\n for (const [name, clip] of this.clips) {\n sprite.addClip(name, clip);\n }\n\n return sprite;\n }\n\n /** Destroy the underlying {@link Spritesheet} and release its frame resources. */\n public destroy(): void {\n this.spritesheet.destroy();\n }\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,mBAAmB,SAA4C;CACnE,IAAI,oBAAoB,IAAI,GAC1B,OAAO,CAAC,GAAG,KAAK,MAAM;CAGxB,OAAO,OAAO,O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AAS,IAAI,IAA2B;EAE9C,KAAK,MAAM,SAAS,KAAK,KAAK,UAAU,CAAC,GACvC,OAAO,IAAI,MAAM,MAAM,KAAK;EAK9B,MAAM,yBAAS,IAAI,IAA2B;EAE9C,KAAK,MAAM,SAAS,KAAK,KAAK,UAAU,CAAC,GACvC,OAAO,IAAI,MAAM,MAAM,KAAK;EAG9B,OAAO,IAAI,cAAc,aAAa,OAAO,QAAQ,MAAM;CAC7D;;;;;;;;CASA,AAAO,uBAAuC;EAC5C,MAAM,SAAS,IAAI,eAAe,KAAK,YAAY,OAAO;EAE1D,KAAK,MAAM,CAAC,MAAM,SAAS,KAAK,OAC9B,OAAO,QAAQ,MAAM,IAAI;EAG3B,OAAO;CACT;;CAGA,AAAO,UAAgB;EACrB,KAAK,YAAY,QAAQ;CAC3B;AACF"}
1
+ {"version":3,"file":"AsepriteSheet.js","names":[],"sources":["../../src/AsepriteSheet.ts"],"sourcesContent":["import { AnimatedSprite, type AnimatedSpriteClipDefinition, Spritesheet, type Texture, Time } from '@codexo/exojs';\n\nimport {\n type AsepriteData,\n type AsepriteFrameData,\n type AsepriteFrameTag,\n type AsepriteLayer,\n type AsepriteSlice,\n type AsepriteSliceFrame,\n type AsepriteSliceKey,\n isAsepriteArrayData,\n} from './AsepriteData';\n\n/**\n * Normalises an {@link AsepriteData} document into an ordered array of\n * {@link AsepriteFrameData} entries regardless of whether the JSON was\n * produced in array or hash mode.\n */\nconst normaliseFrames = (data: AsepriteData): AsepriteFrameData[] => {\n if (isAsepriteArrayData(data)) {\n return [...data.frames];\n }\n\n return Object.values(data.frames);\n};\n\n/**\n * Expands a frame tag's inclusive `[from, to]` range into the ordered\n * sequence of frame indices it actually plays, according to its\n * {@link AsepriteDirection}. Indices are not bounds-checked against the\n * frame array here; callers filter out-of-range entries separately.\n *\n * - `forward`: `[from, from+1, ..., to]`.\n * - `reverse`: `[to, to-1, ..., from]`.\n * - `pingpong`: a forward pass followed by a backward pass that excludes\n * both endpoints, e.g. `[0,1,2]` becomes `[0,1,2,1]`.\n * - `pingpong_reverse`: the mirrored shape, starting from `to`.\n * - A single-frame tag (`from === to`) always yields just that one frame.\n */\nconst expandFrameIndices = (tag: AsepriteFrameTag): number[] => {\n const { from, to } = tag;\n\n if (from === to) {\n return [from];\n }\n\n const indices: number[] = [];\n\n switch (tag.direction) {\n case 'reverse':\n for (let i = to; i >= from; i--) {\n indices.push(i);\n }\n\n break;\n\n case 'pingpong':\n for (let i = from; i <= to; i++) {\n indices.push(i);\n }\n\n for (let i = to - 1; i > from; i--) {\n indices.push(i);\n }\n\n break;\n\n case 'pingpong_reverse':\n for (let i = to; i >= from; i--) {\n indices.push(i);\n }\n\n for (let i = from + 1; i < to; i++) {\n indices.push(i);\n }\n\n break;\n\n case 'forward':\n default:\n for (let i = from; i <= to; i++) {\n indices.push(i);\n }\n\n break;\n }\n\n return indices;\n};\n\n/**\n * Calculates the average frames-per-second for a sequence of frame indices,\n * based on the per-frame `duration` field (milliseconds per frame) exported\n * by Aseprite. Every occurrence of an index counts toward the average - for\n * ping-pong sequences that means repeated (bounced) frames are weighted twice.\n * Falls back to `12` fps when all durations are zero or the sequence is empty.\n */\nconst avgFps = (frames: TaggedFrame[]): number => {\n if (frames.length === 0) {\n return 12;\n }\n\n const totalMs = frames.reduce((sum, { frameData }) => sum + frameData.duration, 0);\n const avgMs = totalMs / frames.length;\n\n return avgMs > 0 ? 1000 / avgMs : 12;\n};\n\n/**\n * A frame a tag actually resolved to, paired with the index it came from.\n * Resolving index and data together is what keeps every per-frame array below\n * (durations, offsets, spritesheet lookups) aligned without re-indexing.\n */\ninterface TaggedFrame {\n index: number;\n frameData: AsepriteFrameData;\n}\n\n/**\n * Resolves a tag's frame indices against the frame array, dropping any that\n * fall outside it - Aseprite exports can reference frames a later edit removed.\n */\nconst resolveTaggedFrames = (frameArray: AsepriteFrameData[], indices: number[]): TaggedFrame[] => {\n const resolved: TaggedFrame[] = [];\n\n for (const index of indices) {\n const frameData = frameArray[index];\n\n if (frameData !== undefined) {\n resolved.push({ index, frameData });\n }\n }\n\n return resolved;\n};\n\n/**\n * Parsed representation of an Aseprite JSON sprite sheet export.\n *\n * `AsepriteSheet.parse(data, texture)` converts the raw JSON document into:\n * - A {@link Spritesheet} whose frames correspond to the Aseprite frame array\n * (keyed by zero-based index string: `\"0\"`, `\"1\"`, ...).\n * - A `clips` map of {@link AnimatedSpriteClipDefinition} entries built from\n * `meta.frameTags`, one per named tag.\n * - The `slices`, `layers` and `tags` metadata maps, carried through verbatim,\n * and {@link getSlice} to read a slice on a given frame.\n *\n * Call {@link createAnimatedSprite} to obtain a ready-to-use\n * {@link AnimatedSprite} with all clips pre-registered.\n *\n * @example\n * ```ts\n * const sheet = await loader.load({ type: 'asepriteSheet', source: 'hero.aseprite.json' });\n * const sprite = sheet.createAnimatedSprite();\n * sprite.play('run');\n * scene.addChild(sprite);\n * ```\n */\nexport class AsepriteSheet {\n /** The underlying {@link Spritesheet} whose frames are keyed by index string. */\n public readonly spritesheet: Spritesheet;\n\n /**\n * Animation clips derived from the Aseprite `frameTags` metadata.\n * Each clip's frames are live references into {@link spritesheet.frames};\n * they are cloned automatically when passed to {@link AnimatedSprite.addClip}.\n */\n public readonly clips: ReadonlyMap<string, AnimatedSpriteClipDefinition>;\n\n /**\n * Named slices from the Aseprite `meta.slices` metadata, keyed by slice\n * name. Slices describe editor-defined regions - hitboxes, nine-patch\n * borders, UI anchor points - that aren't part of the frame/animation\n * data itself. Each {@link AsepriteSlice} carries one {@link AsepriteSliceKey}\n * per frame at which its bounds change; {@link getSlice} resolves the key\n * in effect on a given frame.\n */\n public readonly slices: ReadonlyMap<string, AsepriteSlice>;\n\n /**\n * Layers from the Aseprite `meta.layers` metadata, keyed by layer name and\n * in export order (bottom-most first). Aseprite packs the sheet already\n * composited, so these are descriptive rather than renderable: they tell a\n * consumer which layers went into a frame and how - opacity, blend mode,\n * editor user data - and {@link AsepriteLayer.group} names the enclosing\n * group layer, so the flat map still encodes the layer tree.\n *\n * Empty when the export carries no `meta.layers` block. Layer names are\n * unique within an Aseprite document, so keying by name loses nothing.\n */\n public readonly layers: ReadonlyMap<string, AsepriteLayer>;\n\n /**\n * Frame tags from the Aseprite `meta.frameTags` metadata, keyed by tag\n * name, with the editor colour and user data that {@link clips} do not\n * carry. Empty when the export has no tags.\n */\n public readonly tags: ReadonlyMap<string, AsepriteFrameTag>;\n\n /**\n * For every clip in {@link clips}, the sheet frame index of each of its\n * frames, in play order: the index an {@link AnimatedSprite}'s\n * `currentFrame` selects. Use it to look up per-frame metadata such as\n * {@link getSlice} for the frame being shown.\n */\n public readonly clipFrameIndices: ReadonlyMap<string, readonly number[]>;\n\n /**\n * @internal - use {@link AsepriteSheet.parse} to create instances.\n * The public modifier is required for the Loader's `AssetConstructor` token\n * contract; users should call `parse()` instead of constructing directly.\n */\n public constructor(\n spritesheet: Spritesheet,\n clips: ReadonlyMap<string, AnimatedSpriteClipDefinition>,\n slices: ReadonlyMap<string, AsepriteSlice>,\n layers: ReadonlyMap<string, AsepriteLayer> = new Map(),\n tags: ReadonlyMap<string, AsepriteFrameTag> = new Map(),\n clipFrameIndices: ReadonlyMap<string, readonly number[]> = new Map(),\n ) {\n this.spritesheet = spritesheet;\n this.clips = clips;\n this.slices = slices;\n this.layers = layers;\n this.tags = tags;\n this.clipFrameIndices = clipFrameIndices;\n }\n\n /**\n * The shape slice `name` has on sheet frame `frameIndex`: its most recent\n * key at or before that frame, with the slice's colour and user data.\n * `null` when the sheet has no such slice or the slice starts later.\n *\n * Rectangles and points retain the export's untrimmed source-canvas pixels.\n * For clips carrying `sourceSize`, divide by the texture asset's resolution\n * to compare them with logical local bounds. Metadata-free clips retain\n * legacy trim-offset units; this method always returns authored source\n * pixels. The pivot and nine-slice centre stay relative to the bounds.\n *\n * @example\n * ```ts\n * const frame = sheet.clipFrameIndices.get(sprite.currentClip!)![sprite.currentFrame]!;\n * const hitbox = sheet.getSlice('hitbox', frame);\n * ```\n */\n public getSlice(name: string, frameIndex: number): AsepriteSliceFrame | null {\n const slice = this.slices.get(name);\n let current: AsepriteSliceKey | undefined;\n\n for (const key of slice?.keys ?? []) {\n if (key.frame <= frameIndex && (current === undefined || key.frame >= current.frame)) {\n current = key;\n }\n }\n\n if (slice === undefined || current === undefined) {\n return null;\n }\n\n return {\n name,\n keyFrame: current.frame,\n bounds: current.bounds,\n ...(current.center !== undefined && { center: current.center }),\n ...(current.pivot !== undefined && { pivot: current.pivot }),\n ...(slice.color !== undefined && { color: slice.color }),\n ...(slice.data !== undefined && { data: slice.data }),\n };\n }\n\n /**\n * Parse a raw {@link AsepriteData} document and the already-loaded\n * {@link Texture} into an {@link AsepriteSheet}.\n *\n * Supports both Aseprite array mode and hash mode. Frame indices from\n * `frameTags` are resolved against the ordered frame array; out-of-range\n * indices are silently skipped.\n *\n * A tag's `direction` determines the expanded frame sequence fed into the\n * clip - `forward` and `reverse` play the `[from, to]` range in order or\n * in reverse, while `pingpong`/`pingpong_reverse` append a backward pass\n * (excluding both endpoints) so the bounce plays back correctly on the\n * engine's forward-only {@link AnimatedSprite} playback. The tag's\n * `repeat` field maps directly onto {@link AnimatedSpriteClipDefinition.repeat}:\n * absent means the clip loops indefinitely (`repeat: -1`); a numeric\n * string (`\"1\"`, `\"2\"`, ...) means it plays exactly that many full cycles\n * before stopping.\n *\n * Each clip's `frameDurations` carries the real per-frame `duration` from\n * the export (falling back to the tag's average when a frame's duration is\n * non-positive), so uneven hold-frames survive into playback instead of\n * being flattened to a uniform fps. `frameOffsets` carries each frame's\n * `spriteSourceSize` `{x,y}` - its trimmed content's offset within the\n * untrimmed canvas - whenever any frame in the tag is trimmed; it's omitted\n * for tags with no trimmed frames. `sourceSize` preserves the original canvas\n * for every tag, including transparent padding, so anchors and scale remain\n * stable across tags. When `sourceSize` is present, both are converted to\n * logical pixels using the loaded texture's asset resolution. Older input\n * without it retains the legacy raw offsets and inferred-canvas fallback.\n */\n public static parse(data: AsepriteData, texture: Texture): AsepriteSheet {\n const frameArray = normaliseFrames(data);\n // Use public dimensions: package declarations intentionally strip internal\n // texture fields. The asset factory awaits the image before parsing; an\n // empty texture supplied directly retains the legacy unit-density fallback.\n let resolution = 1;\n\n if (texture.width > 0) {\n resolution = texture.width / texture.logicalWidth;\n } else if (texture.height > 0) {\n resolution = texture.height / texture.logicalHeight;\n }\n\n // Build SpritesheetData: frame names are zero-based index strings.\n const spritesheetFrames: Record<string, { frame: { x: number; y: number; w: number; h: number } }> = {};\n\n for (const [i, frameData] of frameArray.entries()) {\n spritesheetFrames[String(i)] = { frame: frameData.frame };\n }\n\n const spritesheet = new Spritesheet(texture, { frames: spritesheetFrames });\n\n // Build clips from frameTags, resolving frame indices into Rectangles.\n const clips = new Map<string, AnimatedSpriteClipDefinition>();\n const clipFrameIndices = new Map<string, readonly number[]>();\n const tags = new Map<string, AsepriteFrameTag>();\n const frameTags = data.meta.frameTags ?? [];\n\n for (const tag of frameTags) {\n // Out-of-range indices are silently skipped; `taggedFrames` parallels\n // `frames` exactly, so it's the basis for every other per-frame array\n // (durations, offsets) built below.\n const taggedFrames = resolveTaggedFrames(frameArray, expandFrameIndices(tag));\n const frames = taggedFrames.map(({ index }) => spritesheet.getFrame(String(index)));\n\n tags.set(tag.name, tag);\n\n if (frames.length === 0) {\n continue;\n }\n\n // Aseprite's `tag.repeat` (a numeric string, `'1'` through any N) maps\n // directly onto the engine's `repeat` count. Absent or `'0'` means the\n // tag loops indefinitely, the engine's `-1` sentinel.\n const parsedRepeat = tag.repeat !== undefined ? Number(tag.repeat) : -1;\n const repeat = parsedRepeat === 0 ? -1 : parsedRepeat;\n const fps = avgFps(taggedFrames);\n\n // Per-frame hold duration (Aseprite \"duration\"), so uneven hold-frames\n // (e.g. a lingering idle frame) survive into playback instead of being\n // flattened to the tag's average fps. A non-positive duration (same\n // degenerate case `avgFps` guards against) falls back to the average -\n // computed as `1 / fps` directly, not `(1000 / fps) / 1000`, so it is\n // bit-for-bit the reciprocal of the fps this clip actually carries.\n const frameDurations = taggedFrames.map(({ frameData }) =>\n Time.seconds(frameData.duration > 0 ? frameData.duration / 1000 : 1 / fps),\n );\n\n let sourceSize: { width: number; height: number } | undefined = { width: 0, height: 0 };\n\n for (const { frameData } of taggedFrames) {\n // Earlier accepted exports can omit this field. Keep their inferred\n // canvas rather than manufacturing authoritative dimensions.\n const size = (frameData as Partial<AsepriteFrameData>).sourceSize;\n\n if (size === undefined) {\n sourceSize = undefined;\n break;\n }\n\n sourceSize.width = Math.max(sourceSize.width, size.w / resolution);\n sourceSize.height = Math.max(sourceSize.height, size.h / resolution);\n }\n\n // Per-frame trim offset (Aseprite \"spriteSourceSize\"), so frames trimmed\n // by different amounts stay anchored to the same point in the untrimmed\n // canvas instead of jittering frame to frame. Omitted entirely when no\n // frame in the tag is trimmed, to avoid noise on untrimmed sheets.\n const anyTrimmed = taggedFrames.some(({ frameData }) => frameData.trimmed);\n // The metadata-free legacy path historically kept raw trim offsets.\n // Preserve those units with its existing inferred-canvas behavior.\n const offsetResolution = sourceSize === undefined ? 1 : resolution;\n const frameOffsets = anyTrimmed\n ? taggedFrames.map(({ frameData }) => {\n const { x, y } = frameData.spriteSourceSize;\n\n return { x: x / offsetResolution, y: y / offsetResolution };\n })\n : undefined;\n\n clips.set(tag.name, {\n fps,\n frames,\n repeat,\n frameDurations,\n ...(frameOffsets ? { frameOffsets } : {}),\n ...(sourceSize ? { sourceSize } : {}),\n });\n clipFrameIndices.set(\n tag.name,\n taggedFrames.map(({ index }) => index),\n );\n }\n\n // Build the slices map from meta.slices, keyed by slice name.\n const slices = new Map<string, AsepriteSlice>();\n\n for (const slice of data.meta.slices ?? []) {\n slices.set(slice.name, slice);\n }\n\n // Same for meta.layers - insertion order is the export order, so the map\n // doubles as the ordered layer list.\n const layers = new Map<string, AsepriteLayer>();\n\n for (const layer of data.meta.layers ?? []) {\n layers.set(layer.name, layer);\n }\n\n return new AsepriteSheet(spritesheet, clips, slices, layers, tags, clipFrameIndices);\n }\n\n /**\n * Create an {@link AnimatedSprite} with all frame-tag clips pre-defined.\n *\n * Each clip is registered via {@link AnimatedSprite.addClip}, which\n * clones the frame {@link Rectangle}s so the sprite owns its own copies.\n * Call {@link AnimatedSprite.play} with a tag name to start playback.\n */\n public createAnimatedSprite(): AnimatedSprite {\n const sprite = new AnimatedSprite(this.spritesheet.texture);\n\n for (const [name, clip] of this.clips) {\n sprite.addClip(name, clip);\n }\n\n return sprite;\n }\n\n /** Destroy the underlying {@link Spritesheet} and release its frame resources. */\n public destroy(): void {\n this.spritesheet.destroy();\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,MAAM,mBAAmB,SAA4C;CACnE,IAAI,oBAAoB,IAAI,GAC1B,OAAO,CAAC,GAAG,KAAK,MAAM;CAGxB,OAAO,OAAO,OAAO,KAAK,MAAM;AAClC;;;;;;;;;;;;;;AAeA,MAAM,sBAAsB,QAAoC;CAC9D,MAAM,EAAE,MAAM,OAAO;CAErB,IAAI,SAAS,IACX,OAAO,CAAC,IAAI;CAGd,MAAM,UAAoB,CAAC;CAE3B,QAAQ,IAAI,WAAZ;EACE,KAAK;GACH,KAAK,IAAI,IAAI,IAAI,KAAK,MAAM,KAC1B,QAAQ,KAAK,CAAC;GAGhB;EAEF,KAAK;GACH,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,KAC1B,QAAQ,KAAK,CAAC;GAGhB,KAAK,IAAI,IAAI,KAAK,GAAG,IAAI,MAAM,KAC7B,QAAQ,KAAK,CAAC;GAGhB;EAEF,KAAK;GACH,KAAK,IAAI,IAAI,IAAI,KAAK,MAAM,KAC1B,QAAQ,KAAK,CAAC;GAGhB,KAAK,IAAI,IAAI,OAAO,GAAG,IAAI,IAAI,KAC7B,QAAQ,KAAK,CAAC;GAGhB;EAGF,SACE,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,KAC1B,QAAQ,KAAK,CAAC;CAIpB;CAEA,OAAO;AACT;;;;;;;;AASA,MAAM,UAAU,WAAkC;CAChD,IAAI,OAAO,WAAW,GACpB,OAAO;CA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@ -3,7 +3,7 @@ import type { Extension } from '@codexo/exojs/extensions';
3
3
  * Default immutable Aseprite extension descriptor.
4
4
  *
5
5
  * Installs one asset type:
6
- * - {@link asepriteType} - `loader.load(asepriteType.asset('hero.aseprite.json'))`
6
+ * - {@link asepriteType} - `loader.load({ type: asepriteType, source: 'hero.aseprite.json' })`
7
7
  * fetches the Aseprite JSON, resolves and loads the packed texture, and
8
8
  * returns a fully-parsed {@link AsepriteSheet} with all frame-tag clips.
9
9
  *
@@ -1 +1 @@
1
- {"version":3,"file":"asepriteExtension.d.ts","sourceRoot":"","sources":["../../src/asepriteExtension.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAI1D;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,EAAE,SAG9B,CAAC"}
1
+ {"version":3,"file":"asepriteExtension.d.ts","sources":["../../src/asepriteExtension.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAI1D;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,EAAE,SAG9B,CAAC"}
@@ -1,11 +1,11 @@
1
1
  import { asepriteType } from "./asepriteType.js";
2
2
 
3
- //#region src/asepriteExtension.ts
3
+ // src/asepriteExtension.ts
4
4
  /**
5
5
  * Default immutable Aseprite extension descriptor.
6
6
  *
7
7
  * Installs one asset type:
8
- * - {@link asepriteType} - `loader.load(asepriteType.asset('hero.aseprite.json'))`
8
+ * - {@link asepriteType} - `loader.load({ type: asepriteType, source: 'hero.aseprite.json' })`
9
9
  * fetches the Aseprite JSON, resolves and loads the packed texture, and
10
10
  * returns a fully-parsed {@link AsepriteSheet} with all frame-tag clips.
11
11
  *
@@ -17,6 +17,5 @@ const asepriteExtension = Object.freeze({
17
17
  assets: [asepriteType]
18
18
  });
19
19
 
20
- //#endregion
21
20
  export { asepriteExtension };
22
21
  //# sourceMappingURL=asepriteExtension.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"asepriteExtension.js","names":[],"sources":["../../src/asepriteExtension.ts"],"sourcesContent":["import type { Extension } from '@codexo/exojs/extensions';\n\nimport { asepriteType } from './asepriteType';\n\n/**\n * Default immutable Aseprite extension descriptor.\n *\n * Installs one asset type:\n * - {@link asepriteType} - `loader.load(asepriteType.asset('hero.aseprite.json'))`\n * fetches the Aseprite JSON, resolves and loads the packed texture, and\n * returns a fully-parsed {@link AsepriteSheet} with all frame-tag clips.\n *\n * Pass it to the application that should have it via\n * `ApplicationOptions.extensions`.\n */\nexport const asepriteExtension: Extension = Object.freeze({\n id: '@codexo/exojs-aseprite',\n assets: [asepriteType],\n});\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,oBAA+B,OAAO,OAAO;CACxD,IAAI;CACJ,QAAQ,CAAC,YAAY;AACvB,CAAC"}
1
+ {"version":3,"file":"asepriteExtension.js","names":[],"sources":["../../src/asepriteExtension.ts"],"sourcesContent":["import type { Extension } from '@codexo/exojs/extensions';\n\nimport { asepriteType } from './asepriteType';\n\n/**\n * Default immutable Aseprite extension descriptor.\n *\n * Installs one asset type:\n * - {@link asepriteType} - `loader.load({ type: asepriteType, source: 'hero.aseprite.json' })`\n * fetches the Aseprite JSON, resolves and loads the packed texture, and\n * returns a fully-parsed {@link AsepriteSheet} with all frame-tag clips.\n *\n * Pass it to the application that should have it via\n * `ApplicationOptions.extensions`.\n */\nexport const asepriteExtension: Extension = Object.freeze({\n id: '@codexo/exojs-aseprite',\n assets: [asepriteType],\n});\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,oBAA+B,OAAO,OAAO;CACxD,IAAI;CACJ,QAAQ,CAAC,YAAY;AACvB,CAAC"}
@@ -5,6 +5,10 @@ import { AsepriteSheet } from './AsepriteSheet';
5
5
  /**
6
6
  * Thrown when an Aseprite JSON document does not match the expected shape.
7
7
  * `source` is the URL of the file being parsed.
8
+ *
9
+ * Loading through the Loader reports it as the load failure's `cause`, not as
10
+ * the rejection itself; when the stored document is not valid JSON, the cause
11
+ * is a `SyntaxError` instead.
8
12
  */
9
13
  export declare class AsepriteFormatError extends Error {
10
14
  readonly source: string;
@@ -1 +1 @@
1
- {"version":3,"file":"asepriteType.d.ts","sourceRoot":"","sources":["../../src/asepriteType.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAW,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAS,SAAS,EAAmB,MAAM,eAAe,CAAC;AAKlE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AA0ChD;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,SAAgB,MAAM,EAAE,MAAM,CAAC;IAE/B,YAAmB,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAIjD;CACF;AAqCD;;;;;;GAMG;AACH,qBAAa,iBAAkB,SAAQ,SAAS,CAAC,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,CAAC;IAC9F,SAAgB,EAAE,mBAAmB;IACrC,SAAyB,MAAM,uBAAiB;IAGhD,SAAyB,KAAK,EAAE,gBAAgB,CAAC,YAAY,EAAE,MAAM,CAAC,CAIpE;IAEK,aAAa,IAAI,YAAY,CAAC,YAAY,EAAE,aAAa,CAAC,CAQhE;CACF;AAED,mFAAmF;AACnF,eAAO,MAAM,YAAY,mBAA0B,CAAC"}
1
+ {"version":3,"file":"asepriteType.d.ts","sources":["../../src/asepriteType.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAW,MAAM,eAAe,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAmB,MAAM,eAAe,CAAC;AAK3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAgDhD;;;;;;;GAOG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,SAAgB,MAAM,EAAE,MAAM,CAAC;IAE/B,YAAmB,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAIjD;CACF;AAwKD;;;;;;GAMG;AACH,qBAAa,iBAAkB,SAAQ,SAAS,CAAC,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,CAAC;IAC9F,SAAgB,EAAE,mBAAmB;IACrC,SAAyB,MAAM,uBAAiB;IAGhD,SAAyB,KAAK,EAAE,gBAAgB,CAAC,YAAY,EAAE,MAAM,CAAC,CAIpE;IAEK,aAAa,IAAI,YAAY,CAAC,YAAY,EAAE,aAAa,CAAC,CAWhE;CACF;AAED,mFAAmF;AACnF,eAAO,MAAM,YAAY,mBAA0B,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { AsepriteSheet } from "./AsepriteSheet.js";
2
- import { Asset, AssetType, jsonSourceCodec } from "@codexo/exojs";
2
+ import { AssetType, jsonSourceCodec } from "@codexo/exojs";
3
3
 
4
- //#region src/asepriteType.ts
4
+ // src/asepriteType.ts
5
5
  /** The JSON codec, narrowed to the two acquisition halves this type reuses verbatim. */
6
6
  const jsonStringCodec = jsonSourceCodec;
7
7
  /** Matches references that are already absolute: scheme, `//`, `/`, data/blob. */
@@ -23,11 +23,16 @@ const resolveAsepriteUrl = (ref, base) => {
23
23
  if (absoluteRefPattern.test(ref)) return ref;
24
24
  if (absoluteBasePattern.test(base)) return new URL(ref, base).href;
25
25
  const relative = new URL(ref, syntheticOrigin + base.replace(/^\/+/, "")).href.slice(22);
26
+ if (base.startsWith("//")) return `//${relative}`;
26
27
  return base.startsWith("/") ? `/${relative}` : relative;
27
28
  };
28
29
  /**
29
30
  * Thrown when an Aseprite JSON document does not match the expected shape.
30
31
  * `source` is the URL of the file being parsed.
32
+ *
33
+ * Loading through the Loader reports it as the load failure's `cause`, not as
34
+ * the rejection itself; when the stored document is not valid JSON, the cause
35
+ * is a `SyntaxError` instead.
31
36
  */
32
37
  var AsepriteFormatError = class extends Error {
33
38
  source;
@@ -51,8 +56,60 @@ const validateAsepriteData = (raw, source) => {
51
56
  if (typeof meta.image !== "string" || meta.image.length === 0) throw new AsepriteFormatError(source, "\"meta.image\" must be a non-empty string");
52
57
  const frames = doc.frames;
53
58
  if (!Array.isArray(frames) && (typeof frames !== "object" || frames === null)) throw new AsepriteFormatError(source, "\"frames\" must be an array or an object");
59
+ validateFrames(frames, source);
60
+ validateFrameTags(meta.frameTags, source);
61
+ validateSlices(meta.slices, source);
54
62
  return doc;
55
63
  };
64
+ const DIRECTIONS = [
65
+ "forward",
66
+ "reverse",
67
+ "pingpong",
68
+ "pingpong_reverse"
69
+ ];
70
+ const isRecord = (value) => typeof value === "object" && value !== null;
71
+ const isRect = (value) => isRecord(value) && [
72
+ value.x,
73
+ value.y,
74
+ value.w,
75
+ value.h
76
+ ].every((component) => typeof component === "number" && Number.isFinite(component));
77
+ const isFrameIndex = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
78
+ const validateFrames = (frames, source) => {
79
+ const frameEntries = Array.isArray(frames) ? frames.map((frame, index) => [String(index), frame]) : Object.entries(frames);
80
+ for (const [key, frame] of frameEntries) {
81
+ if (isRecord(frame) && frame.rotated === true) throw new AsepriteFormatError(source, `"frames.${key}" is rotated; packed rotated frames are not supported - export the sheet with rotation disabled`);
82
+ if (!isRecord(frame) || !isRect(frame.frame) || typeof frame.duration !== "number" || !Number.isFinite(frame.duration) || typeof frame.trimmed !== "boolean" || !isRect(frame.spriteSourceSize)) throw new AsepriteFormatError(source, `"frames.${key}" must have frame and spriteSourceSize rectangles, a finite duration and a boolean trimmed flag`);
83
+ const size = frame.sourceSize;
84
+ if (size !== void 0 && (!isRecord(size) || typeof size.w !== "number" || !Number.isFinite(size.w) || size.w <= 0 || typeof size.h !== "number" || !Number.isFinite(size.h) || size.h <= 0)) throw new AsepriteFormatError(source, `"frames.${key}.sourceSize" must have positive finite w and h`);
85
+ }
86
+ };
87
+ /** A malformed tag would otherwise become a clip with no frames or a `NaN` repeat count. */
88
+ const validateFrameTags = (tags, source) => {
89
+ if (tags === void 0) return;
90
+ if (!Array.isArray(tags)) throw new AsepriteFormatError(source, "\"meta.frameTags\" must be an array");
91
+ for (const [index, tag] of tags.entries()) {
92
+ const where = `"meta.frameTags[${index}]"`;
93
+ if (!isRecord(tag) || typeof tag.name !== "string") throw new AsepriteFormatError(source, `${where} must be an object with a string "name"`);
94
+ if (!isFrameIndex(tag.from) || !isFrameIndex(tag.to) || tag.from > tag.to) throw new AsepriteFormatError(source, `${where} ("${tag.name}") needs frame indices with from <= to`);
95
+ if (typeof tag.direction !== "string" || !DIRECTIONS.includes(tag.direction)) throw new AsepriteFormatError(source, `${where} ("${tag.name}") has an unknown direction ${JSON.stringify(tag.direction)}`);
96
+ const repeat = tag.repeat;
97
+ const wholeRepeat = typeof repeat === "string" ? /^\d+$/.test(repeat) : isFrameIndex(repeat);
98
+ if (repeat !== void 0 && !wholeRepeat) throw new AsepriteFormatError(source, `${where} ("${tag.name}") has a repeat count that is not a whole number: ${JSON.stringify(tag.repeat)}`);
99
+ }
100
+ };
101
+ const validateSlices = (slices, source) => {
102
+ if (slices === void 0) return;
103
+ if (!Array.isArray(slices)) throw new AsepriteFormatError(source, "\"meta.slices\" must be an array");
104
+ for (const [index, slice] of slices.entries()) {
105
+ const where = `"meta.slices[${index}]"`;
106
+ if (!isRecord(slice) || typeof slice.name !== "string" || !Array.isArray(slice.keys)) throw new AsepriteFormatError(source, `${where} must be an object with a string "name" and a "keys" array`);
107
+ for (const key of slice.keys) {
108
+ const pivot = isRecord(key) ? key.pivot : void 0;
109
+ if (!(isRecord(key) && isFrameIndex(key.frame) && isRect(key.bounds) && (key.center === void 0 || isRect(key.center)) && (pivot === void 0 || isRecord(pivot) && typeof pivot.x === "number" && typeof pivot.y === "number"))) throw new AsepriteFormatError(source, `${where} ("${slice.name}") has a key without a frame index and bounds, or with a malformed centre or pivot`);
110
+ }
111
+ }
112
+ };
56
113
  /**
57
114
  * Aseprite JSON exports, together with the packed sheet they reference.
58
115
  *
@@ -70,7 +127,10 @@ var AsepriteAssetType = class extends AssetType {
70
127
  };
71
128
  createFactory() {
72
129
  return { async create(source, context) {
73
- const texture = await context.dependencies.load(Asset.type("texture", resolveAsepriteUrl(source.meta.image, context.source)));
130
+ const texture = await context.dependencies.load({
131
+ type: "texture",
132
+ source: resolveAsepriteUrl(source.meta.image, context.source)
133
+ });
74
134
  return AsepriteSheet.parse(source, texture);
75
135
  } };
76
136
  }
@@ -78,6 +138,5 @@ var AsepriteAssetType = class extends AssetType {
78
138
  /** The Aseprite sheet asset type. Install it through {@link asepriteExtension}. */
79
139
  const asepriteType = new AsepriteAssetType();
80
140
 
81
- //#endregion
82
141
  export { AsepriteAssetType, AsepriteFormatError, asepriteType };
83
142
  //# sourceMappingURL=asepriteType.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"asepriteType.js","names":[],"sources":["../../src/asepriteType.ts"],"sourcesContent":["import type { AssetFactory, AssetSourceCodec, Texture } from '@codexo/exojs';\nimport { Asset, AssetType, jsonSourceCodec } from '@codexo/exojs';\n\n/** The JSON codec, narrowed to the two acquisition halves this type reuses verbatim. */\nconst jsonStringCodec = jsonSourceCodec as Required<AssetSourceCodec<unknown, string>>;\n\nimport type { AsepriteData } from './AsepriteData';\nimport { AsepriteSheet } from './AsepriteSheet';\n\n// ── URL resolution ───────────────────────────────────────────────────────────\n\n/** Matches references that are already absolute: scheme, `//`, `/`, data/blob. */\nconst absoluteRefPattern = /^(?:[a-z][a-z\\d+.-]*:|\\/\\/|\\/)/i;\n\n/** Matches a base that has an explicit scheme (absolute URL). */\nconst absoluteBasePattern = /^[a-z][a-z\\d+.-]*:/i;\n\n/** Synthetic origin used to borrow `URL`'s `../`/`./` collapsing. */\nconst syntheticOrigin = 'https://exojs.invalid/';\n\n/**\n * Resolves `ref` (the image path read from an Aseprite JSON file) relative to\n * `base` (the resolved location of the JSON file itself).\n *\n * - Absolute refs (scheme, `//`, `/`, `data:`, `blob:`) are returned as-is.\n * - Absolute bases delegate to `new URL(ref, base).href`.\n * - Relative bases use a synthetic origin to collapse `./` and `../` segments,\n * then strips the origin from the result.\n */\nconst resolveAsepriteUrl = (ref: string, base: string): string => {\n if (absoluteRefPattern.test(ref)) {\n return ref;\n }\n\n if (absoluteBasePattern.test(base)) {\n return new URL(ref, base).href;\n }\n\n const resolved = new URL(ref, syntheticOrigin + base.replace(/^\\/+/, ''));\n const relative = resolved.href.slice(syntheticOrigin.length);\n\n // A root-relative base must produce a root-relative result again - dropping\n // the leading slash would make the browser re-resolve the reference against\n // the document base URL (e.g. `/site/assets/x.png` → `/site/site/assets/...`).\n return base.startsWith('/') ? `/${relative}` : relative;\n};\n\n// ── Validation ───────────────────────────────────────────────────────────────\n\n/**\n * Thrown when an Aseprite JSON document does not match the expected shape.\n * `source` is the URL of the file being parsed.\n */\nexport class AsepriteFormatError extends Error {\n public readonly source: string;\n\n public constructor(source: string, message: string) {\n super(`[AsepriteFormatError] ${source}: ${message}`);\n this.name = 'AsepriteFormatError';\n this.source = source;\n }\n}\n\n/**\n * Validates an `unknown` value against the minimum required Aseprite JSON\n * shape and narrows it to {@link AsepriteData}. Throws {@link AsepriteFormatError}\n * on any mismatch.\n */\nconst validateAsepriteData = (raw: unknown, source: string): AsepriteData => {\n if (typeof raw !== 'object' || raw === null) {\n throw new AsepriteFormatError(source, 'root must be an object');\n }\n\n const doc = raw as Record<string, unknown>;\n\n if (!('frames' in doc)) {\n throw new AsepriteFormatError(source, 'missing required field \"frames\"');\n }\n\n if (!('meta' in doc) || typeof doc.meta !== 'object' || doc.meta === null) {\n throw new AsepriteFormatError(source, 'missing required field \"meta\"');\n }\n\n const meta = doc.meta as Record<string, unknown>;\n\n if (typeof meta.image !== 'string' || meta.image.length === 0) {\n throw new AsepriteFormatError(source, '\"meta.image\" must be a non-empty string');\n }\n\n const frames = doc.frames;\n\n if (!Array.isArray(frames) && (typeof frames !== 'object' || frames === null)) {\n throw new AsepriteFormatError(source, '\"frames\" must be an array or an object');\n }\n\n return doc as unknown as AsepriteData;\n};\n\n/**\n * Aseprite JSON exports, together with the packed sheet they reference.\n *\n * The image URL is read from `meta.image` and resolved against the JSON file's\n * own location; the texture is claimed by this sheet's dependency scope, so it\n * lives exactly as long as the sheet does.\n */\nexport class AsepriteAssetType extends AssetType<AsepriteData, AsepriteSheet, undefined, string> {\n public readonly id = 'asepriteSheet';\n public override readonly _token = AsepriteSheet;\n // Stored as the text that arrived, like any JSON: a parsed value round-trips\n // through key order and number formatting the response never had.\n public override readonly codec: AssetSourceCodec<AsepriteData, string> = {\n fromResponse: (response, context) => jsonStringCodec.fromResponse(response, context),\n fromBytes: (bytes, context) => jsonStringCodec.fromBytes(bytes, context),\n decode: (stored, context) => Promise.resolve(validateAsepriteData(JSON.parse(stored), context.locator)),\n };\n\n public createFactory(): AssetFactory<AsepriteData, AsepriteSheet> {\n return {\n async create(source, context) {\n const texture: Texture = await context.dependencies.load(Asset.type('texture', resolveAsepriteUrl(source.meta.image, context.source)));\n\n return AsepriteSheet.parse(source, texture);\n },\n };\n }\n}\n\n/** The Aseprite sheet asset type. Install it through {@link asepriteExtension}. */\nexport const asepriteType = new AsepriteAssetType();\n"],"mappings":";;;;;AAIA,MAAM,kBAAkB;;AAQxB,MAAM,qBAAqB;;AAG3B,MAAM,sBAAsB;;AAG5B,MAAM,kBAAkB;;;;;;;;;;AAWxB,MAAM,sBAAsB,KAAa,SAAyB;CAChE,IAAI,mBAAmB,KAAK,GAAG,GAC7B,OAAO;CAGT,IAAI,oBAAoB,KAAK,IAAI,GAC/B,OAAO,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC;CAI5B,MAAM,WAAW,IADI,IAAI,KAAK,kBAAkB,KAAK,QAAQ,QAAQ,EAAE,CAC/C,CAAC,CAAC,KAAK,MAAM,EAAsB;CAK3D,OAAO,KAAK,WAAW,GAAG,IAAI,IAAI,aAAa;AACjD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AM,CAAC,CAAC;GAErI,OAAO,cAAc,MAAM,QAAQ,OAAO;EAC5C,EACF;CACF;AACF;;AAGA,MAAa,eAAe,IAAI,kBAAkB"}
1
+ {"version":3,"file":"asepriteType.js","names":[],"sources":["../../src/asepriteType.ts"],"sourcesContent":["import type { AssetFactory, AssetSourceCodec, Texture } from '@codexo/exojs';\nimport { AssetType, jsonSourceCodec } from '@codexo/exojs';\n\n/** The JSON codec, narrowed to the two acquisition halves this type reuses verbatim. */\nconst jsonStringCodec = jsonSourceCodec as Required<AssetSourceCodec<unknown, string>>;\n\nimport type { AsepriteData } from './AsepriteData';\nimport { AsepriteSheet } from './AsepriteSheet';\n\n// ── URL resolution ───────────────────────────────────────────────────────────\n\n/** Matches references that are already absolute: scheme, `//`, `/`, data/blob. */\nconst absoluteRefPattern = /^(?:[a-z][a-z\\d+.-]*:|\\/\\/|\\/)/i;\n\n/** Matches a base that has an explicit scheme (absolute URL). */\nconst absoluteBasePattern = /^[a-z][a-z\\d+.-]*:/i;\n\n/** Synthetic origin used to borrow `URL`'s `../`/`./` collapsing. */\nconst syntheticOrigin = 'https://exojs.invalid/';\n\n/**\n * Resolves `ref` (the image path read from an Aseprite JSON file) relative to\n * `base` (the resolved location of the JSON file itself).\n *\n * - Absolute refs (scheme, `//`, `/`, `data:`, `blob:`) are returned as-is.\n * - Absolute bases delegate to `new URL(ref, base).href`.\n * - Relative bases use a synthetic origin to collapse `./` and `../` segments,\n * then strips the origin from the result.\n */\nconst resolveAsepriteUrl = (ref: string, base: string): string => {\n if (absoluteRefPattern.test(ref)) {\n return ref;\n }\n\n if (absoluteBasePattern.test(base)) {\n return new URL(ref, base).href;\n }\n\n const resolved = new URL(ref, syntheticOrigin + base.replace(/^\\/+/, ''));\n const relative = resolved.href.slice(syntheticOrigin.length);\n\n // A root-relative base must produce a root-relative result again - dropping\n // the leading slash would make the browser re-resolve the reference against\n // the document base URL (e.g. `/site/assets/x.png` → `/site/site/assets/...`).\n // A protocol-relative base keeps both slashes for the same reason; the\n // synthetic resolution already dropped the authority prefix.\n if (base.startsWith('//')) {\n return `//${relative}`;\n }\n\n return base.startsWith('/') ? `/${relative}` : relative;\n};\n\n// ── Validation ───────────────────────────────────────────────────────────────\n\n/**\n * Thrown when an Aseprite JSON document does not match the expected shape.\n * `source` is the URL of the file being parsed.\n *\n * Loading through the Loader reports it as the load failure's `cause`, not as\n * the rejection itself; when the stored document is not valid JSON, the cause\n * is a `SyntaxError` instead.\n */\nexport class AsepriteFormatError extends Error {\n public readonly source: string;\n\n public constructor(source: string, message: string) {\n super(`[AsepriteFormatError] ${source}: ${message}`);\n this.name = 'AsepriteFormatError';\n this.source = source;\n }\n}\n\n/**\n * Validates an `unknown` value against the minimum required Aseprite JSON\n * shape and narrows it to {@link AsepriteData}. Throws {@link AsepriteFormatError}\n * on any mismatch.\n */\nconst validateAsepriteData = (raw: unknown, source: string): AsepriteData => {\n if (typeof raw !== 'object' || raw === null) {\n throw new AsepriteFormatError(source, 'root must be an object');\n }\n\n const doc = raw as Record<string, unknown>;\n\n if (!('frames' in doc)) {\n throw new AsepriteFormatError(source, 'missing required field \"frames\"');\n }\n\n if (!('meta' in doc) || typeof doc.meta !== 'object' || doc.meta === null) {\n throw new AsepriteFormatError(source, 'missing required field \"meta\"');\n }\n\n const meta = doc.meta as Record<string, unknown>;\n\n if (typeof meta.image !== 'string' || meta.image.length === 0) {\n throw new AsepriteFormatError(source, '\"meta.image\" must be a non-empty string');\n }\n\n const frames = doc.frames;\n\n if (!Array.isArray(frames) && (typeof frames !== 'object' || frames === null)) {\n throw new AsepriteFormatError(source, '\"frames\" must be an array or an object');\n }\n\n validateFrames(frames, source);\n validateFrameTags(meta.frameTags, source);\n validateSlices(meta.slices, source);\n\n return doc as unknown as AsepriteData;\n};\n\nconst DIRECTIONS: readonly string[] = ['forward', 'reverse', 'pingpong', 'pingpong_reverse'];\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;\n\nconst isRect = (value: unknown): boolean =>\n isRecord(value) && [value.x, value.y, value.w, value.h].every(component => typeof component === 'number' && Number.isFinite(component));\n\nconst isFrameIndex = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value >= 0;\n\nconst validateFrames = (frames: object, source: string): void => {\n // A rotated packed frame stores its pixels transposed; the runtime samples\n // the rectangle verbatim, so accepting it would render wrong pixels.\n const frameEntries: Array<[string, unknown]> = Array.isArray(frames)\n ? frames.map((frame, index) => [String(index), frame])\n : Object.entries(frames);\n\n for (const [key, frame] of frameEntries) {\n if (isRecord(frame) && frame.rotated === true) {\n throw new AsepriteFormatError(\n source,\n `\"frames.${key}\" is rotated; packed rotated frames are not supported - export the sheet with rotation disabled`,\n );\n }\n\n if (\n !isRecord(frame) ||\n !isRect(frame.frame) ||\n typeof frame.duration !== 'number' ||\n !Number.isFinite(frame.duration) ||\n typeof frame.trimmed !== 'boolean' ||\n !isRect(frame.spriteSourceSize)\n ) {\n throw new AsepriteFormatError(\n source,\n `\"frames.${key}\" must have frame and spriteSourceSize rectangles, a finite duration and a boolean trimmed flag`,\n );\n }\n\n const size = frame.sourceSize;\n\n if (\n size !== undefined &&\n (!isRecord(size) ||\n typeof size.w !== 'number' ||\n !Number.isFinite(size.w) ||\n size.w <= 0 ||\n typeof size.h !== 'number' ||\n !Number.isFinite(size.h) ||\n size.h <= 0)\n ) {\n throw new AsepriteFormatError(source, `\"frames.${key}.sourceSize\" must have positive finite w and h`);\n }\n }\n};\n\n/** A malformed tag would otherwise become a clip with no frames or a `NaN` repeat count. */\nconst validateFrameTags = (tags: unknown, source: string): void => {\n if (tags === undefined) {\n return;\n }\n\n if (!Array.isArray(tags)) {\n throw new AsepriteFormatError(source, '\"meta.frameTags\" must be an array');\n }\n\n for (const [index, tag] of tags.entries()) {\n const where = `\"meta.frameTags[${index}]\"`;\n\n if (!isRecord(tag) || typeof tag.name !== 'string') {\n throw new AsepriteFormatError(source, `${where} must be an object with a string \"name\"`);\n }\n\n if (!isFrameIndex(tag.from) || !isFrameIndex(tag.to) || tag.from > tag.to) {\n throw new AsepriteFormatError(source, `${where} (\"${tag.name}\") needs frame indices with from <= to`);\n }\n\n if (typeof tag.direction !== 'string' || !DIRECTIONS.includes(tag.direction)) {\n throw new AsepriteFormatError(source, `${where} (\"${tag.name}\") has an unknown direction ${JSON.stringify(tag.direction)}`);\n }\n\n const repeat = tag.repeat;\n const wholeRepeat = typeof repeat === 'string' ? /^\\d+$/.test(repeat) : isFrameIndex(repeat);\n\n if (repeat !== undefined && !wholeRepeat) {\n throw new AsepriteFormatError(\n source,\n `${where} (\"${tag.name}\") has a repeat count that is not a whole number: ${JSON.stringify(tag.repeat)}`,\n );\n }\n }\n};\n\nconst validateSlices = (slices: unknown, source: string): void => {\n if (slices === undefined) {\n return;\n }\n\n if (!Array.isArray(slices)) {\n throw new AsepriteFormatError(source, '\"meta.slices\" must be an array');\n }\n\n for (const [index, slice] of slices.entries()) {\n const where = `\"meta.slices[${index}]\"`;\n\n if (!isRecord(slice) || typeof slice.name !== 'string' || !Array.isArray(slice.keys)) {\n throw new AsepriteFormatError(source, `${where} must be an object with a string \"name\" and a \"keys\" array`);\n }\n\n for (const key of slice.keys as unknown[]) {\n const pivot = isRecord(key) ? key.pivot : undefined;\n const valid =\n isRecord(key) &&\n isFrameIndex(key.frame) &&\n isRect(key.bounds) &&\n (key.center === undefined || isRect(key.center)) &&\n (pivot === undefined || (isRecord(pivot) && typeof pivot.x === 'number' && typeof pivot.y === 'number'));\n\n if (!valid) {\n throw new AsepriteFormatError(\n source,\n `${where} (\"${slice.name}\") has a key without a frame index and bounds, or with a malformed centre or pivot`,\n );\n }\n }\n }\n};\n\n/**\n * Aseprite JSON exports, together with the packed sheet they reference.\n *\n * The image URL is read from `meta.image` and resolved against the JSON file's\n * own location; the texture is claimed by this sheet's dependency scope, so it\n * lives exactly as long as the sheet does.\n */\nexport class AsepriteAssetType extends AssetType<AsepriteData, AsepriteSheet, undefined, string> {\n public readonly id = 'asepriteSheet';\n public override readonly _token = AsepriteSheet;\n // Stored as the text that arrived, like any JSON: a parsed value round-trips\n // through key order and number formatting the response never had.\n public override readonly codec: AssetSourceCodec<AsepriteData, string> = {\n fromResponse: (response, context) => jsonStringCodec.fromResponse(response, context),\n fromBytes: (bytes, context) => jsonStringCodec.fromBytes(bytes, context),\n decode: (stored, context) => Promise.resolve(validateAsepriteData(JSON.parse(stored), context.locator)),\n };\n\n public createFactory(): AssetFactory<AsepriteData, AsepriteSheet> {\n return {\n async create(source, context) {\n const texture: Texture = await context.dependencies.load({\n type: 'texture',\n source: resolveAsepriteUrl(source.meta.image, context.source),\n });\n\n return AsepriteSheet.parse(source, texture);\n },\n };\n }\n}\n\n/** The Aseprite sheet asset type. Install it through {@link asepriteExtension}. */\nexport const asepriteType = new AsepriteAssetType();\n"],"mappings":";;;;;AAIA,MAAM,kBAAkB;;AAQxB,MAAM,qBAAqB;;AAG3B,MAAM,sBAAsB;;AAG5B,MAAM,kBAAkB;;;;;;;;;;AAWxB,MAAM,sBAAsB,KAAa,SAAyB;CAChE,IAAI,mBAAmB,KAAK,GAAG,GAC7B,OAAO;CAGT,IAAI,oBAAoB,KAAK,IAAI,GAC/B,OAAO,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC;CAI5B,MAAM,WAAW,IADI,IAAI,KAAK,kBAAkB,KAAK,QAAQ,QAAQ,EAAE,CAC/C,CAAC,CAAC,KAAK,MAAM,EAAsB;CAO3D,IAAI,KAAK,WAAW,IAAI,GACtB,OAAO,KAAK;CAGd,OAAO,KAAK,WAAW,GAAG,IAAI,IAAI,aAAa;AACjD;;;;;;;;;AAYA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,AAAgB;CAEhB,AAAO,YAAY,QAAgB,SAAiB;EAClD,MAAM,yBAAyB,OAAO,IAAI,SAAS;EACnD,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;;;;;;AAOA,MAAM,wBAAwB,KAAc,WAAiC;CAC3E,IAAI,OAAO,QAAQ,YAAY,Q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AM,GAAG,QAAQ,OAAO,CAAC;CACxG;CAEA,AAAO,gBAA2D;EAChE,OAAO,EACL,MAAM,OAAO,QAAQ,SAAS;GAC5B,MAAM,UAAmB,MAAM,QAAQ,aAAa,KAAK;IACvD,MAAM;IACN,QAAQ,mBAAmB,OAAO,KAAK,OAAO,QAAQ,MAAM;GAC9D,CAAC;GAED,OAAO,cAAc,MAAM,QAAQ,OAAO;EAC5C,EACF;CACF;AACF;;AAGA,MAAa,eAAe,IAAI,kBAAkB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,cAAc,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,cAAc,UAAU,CAAC"}
@@ -1,4 +1,4 @@
1
- export type { AsepriteArrayData, AsepriteData, AsepriteDirection, AsepriteFrameData, AsepriteFrameTag, AsepriteHashData, AsepriteLayer, AsepriteMeta, AsepriteRect, AsepriteSize, AsepriteSlice, AsepriteSliceKey, } from './AsepriteData';
1
+ export type { AsepriteArrayData, AsepriteData, AsepriteDirection, AsepriteFrameData, AsepriteFrameTag, AsepriteHashData, AsepriteLayer, AsepriteMeta, AsepritePoint, AsepriteRect, AsepriteSize, AsepriteSlice, AsepriteSliceFrame, AsepriteSliceKey, } from './AsepriteData';
2
2
  export { isAsepriteArrayData } from './AsepriteData';
3
3
  export { asepriteExtension } from './asepriteExtension';
4
4
  export { AsepriteSheet } from './AsepriteSheet';
@@ -1 +1 @@
1
- {"version":3,"file":"public.d.ts","sourceRoot":"","sources":["../../src/public.ts"],"names":[],"mappings":"AAGA,YAAY,EACV,iBAAiB,EACjB,YAAY,EACZ,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,gBAAgB,GACjB,MAAM,gBAAgB,CAAC;AACxB,OA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YAG3B,OAAO,EAAE,IAAI,CAAC;SACf,CAAC;KACH;CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codexo/exojs-aseprite",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Aseprite sprite sheet asset extension for ExoJS.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,18 +26,18 @@
26
26
  "LICENSE"
27
27
  ],
28
28
  "peerDependencies": {
29
- "@codexo/exojs": "0.19.x"
29
+ "@codexo/exojs": "0.20.x"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@codexo/exojs-config": "0.0.0",
33
- "@codexo/exojs": "0.19.0"
33
+ "@codexo/exojs": "0.20.0"
34
34
  },
35
35
  "license": "MIT",
36
36
  "publishConfig": {
37
37
  "access": "public"
38
38
  },
39
39
  "scripts": {
40
- "build": "tsx ../../scripts/build-extension.ts",
40
+ "build": "node --import tsx ../../scripts/build-extension.ts",
41
41
  "build:dev": "tsx ../../scripts/build-extension.ts --dev",
42
42
  "typecheck": "exo-tsc --noEmit && exo-tsc --noEmit -p tsconfig.test.json",
43
43
  "lint": "eslint \"src/**/*.ts\"",