├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitattributes ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── ci-cd.yml │ ├── commitlint.yml │ └── signature-assistant.yml ├── .gitignore ├── .husky ├── .gitattributes └── commit-msg ├── .jsdoc.json ├── .npmignore ├── .nvmrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── TRADEMARK ├── commitlint.config.js ├── index.js ├── package-lock.json ├── package.json ├── release.config.js ├── renovate.json5 ├── src ├── .eslintrc.js ├── coders │ ├── adler32.js │ ├── byte-packets.js │ ├── byte-primitives.js │ ├── byte-stream.js │ ├── crc32.js │ ├── deflate-packets.js │ ├── deflate-stream.js │ ├── png-chunk-stream.js │ ├── png-file.js │ ├── png-packets.js │ ├── proxy-stream.js │ ├── squeak-image.js │ ├── squeak-sound.js │ ├── wav-file.js │ └── wav-packets.js ├── playground │ ├── array.js │ ├── field-object.js │ ├── field.js │ ├── index.html │ ├── index.js │ ├── js-primitive.js │ ├── object.js │ ├── view.js │ └── viewable.js ├── sb1-file-packets.js ├── sb1-file.js ├── squeak │ ├── byte-primitives.js │ ├── byte-take-iterator.js │ ├── field-iterator.js │ ├── field-object.js │ ├── fields.js │ ├── ids.js │ ├── reference-fixer.js │ ├── type-iterator.js │ └── types.js ├── to-sb2 │ ├── fake-zip.js │ └── json-generator.js └── util │ ├── assert.js │ └── log.js ├── test ├── .eslintrc.js ├── fixtures │ └── valid │ │ ├── bouncing-music-balls.sb │ │ ├── default.sb │ │ └── ewe-and-me.sb ├── integration │ ├── default.js │ └── valid.js └── unit │ ├── adler32.js │ ├── byte-packets.js │ ├── byte-primitives.js │ ├── byte-stream.js │ ├── crc32.js │ └── spec.js └── webpack.config.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env"] 3 | } 4 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | 10 | [*.{js,html}] 11 | indent_style = space 12 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | coverage/* 2 | dist/* 3 | node_modules/* 4 | playground/* 5 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['scratch', 'scratch/node', 'scratch/es6'] 3 | }; 4 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Explicitly specify line endings for as many files as possible. 5 | # People who (for example) rsync between Windows and Linux need this. 6 | 7 | # File types which we know are binary 8 | *.sb binary 9 | *.sb2 binary 10 | 11 | # Prefer LF for most file types 12 | *.css text eol=lf 13 | *.htm text eol=lf 14 | *.html text eol=lf 15 | *.iml text eol=lf 16 | *.js text eol=lf 17 | *.js.map text eol=lf 18 | *.json text eol=lf 19 | *.md text eol=lf 20 | *.xml text eol=lf 21 | *.yml text eol=lf 22 | 23 | # Prefer LF for these files 24 | .editorconfig text eol=lf 25 | .eslintignore text eol=lf 26 | .eslintrc text eol=lf 27 | .gitattributes text eol=lf 28 | .gitignore text eol=lf 29 | .gitmodules text eol=lf 30 | .npmignore text eol=lf 31 | LICENSE text eol=lf 32 | Makefile text eol=lf 33 | README text eol=lf 34 | TRADEMARK text eol=lf 35 | 36 | # Use CRLF for Windows-specific file types 37 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | The development of Scratch is an ongoing process, and we love to have people in the Scratch and open source communities help us along the way. 3 | 4 | If you're interested in contributing, please take a look at the [issues](https://github.com/LLK/scratch-sb1-converter/issues) on this repository. 5 | Two great ways of helping are by identifying bugs and documenting them as issues, or fixing issues and creating pull requests. When looking for bugs to fix, please look for the ["Help Wanted" label](https://github.com/LLK/scratch-sb1-converter/issues?q=label%3A%22help+wanted%22). Bugs with this label have been specifically set aside for Open Source contributors. Issues without the label can also be worked on but we ask that you comment on the issue prior to starting work. When submitting pull requests please be patient -- it can take a while to find time to review them. The organization and class structures can't be radically changed without significant coordination and collaboration from the Scratch Team, so these types of changes should be avoided. 6 | 7 | It's been said that the Scratch Team spends about one hour of design discussion for every pixel in Scratch, but some think that estimate is a little low. While we welcome suggestions for new features in our [suggestions forum](https://scratch.mit.edu/discuss/1/) (especially ones that come with mockups), we are unlikely to accept PRs with new features that haven't been thought through and discussed as a group. Why? Because we have a strong belief in the value of keeping things simple for new users. To learn more about our design philosophy, see [the Scratch Developers page](https://scratch.mit.edu/developers), or [this paper](http://web.media.mit.edu/~mres/papers/Scratch-CACM-final.pdf). 8 | 9 | Beyond this repo, there are also some other resources that you might want to take a look at: 10 | * [Community Guidelines](https://github.com/LLK/scratch-www/wiki/Community-Guidelines) (we find it important to maintain a constructive and welcoming community, just like on Scratch) 11 | * [Open Source forum](https://scratch.mit.edu/discuss/49/) on Scratch 12 | * [Suggestions forum](https://scratch.mit.edu/discuss/1/) on Scratch 13 | * [Bugs & Glitches forum](https://scratch.mit.edu/discuss/3/) on Scratch 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Expected Behavior 2 | 3 | _Please describe what should happen_ 4 | 5 | ### Actual Behavior 6 | 7 | _Describe what actually happens_ 8 | 9 | ### Steps to Reproduce 10 | 11 | _Explain what someone needs to do in order to see what's described in *Actual behavior* above_ 12 | 13 | ### Operating System and Browser 14 | 15 | _e.g. Mac OS 10.11.6 Safari 10.0_ 16 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Resolves 2 | 3 | _What Github issue does this resolve (please include link)?_ 4 | 5 | ### Proposed Changes 6 | 7 | _Describe what this Pull Request does_ 8 | 9 | ### Reason for Changes 10 | 11 | _Explain why these changes should be made_ 12 | 13 | ### Test Coverage 14 | 15 | _Please show how you have added tests to cover your changes_ 16 | -------------------------------------------------------------------------------- /.github/workflows/ci-cd.yml: -------------------------------------------------------------------------------- 1 | name: CI/CD 2 | 3 | on: 4 | push: # Runs whenever a commit is pushed to the repository 5 | workflow_call: # Allows another workflow to call this one 6 | workflow_dispatch: # Allows you to run this workflow manually from the Actions tab 7 | 8 | concurrency: 9 | group: "${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}" 10 | cancel-in-progress: true 11 | 12 | permissions: 13 | contents: write # publish a GitHub release 14 | pages: write # deploy to GitHub Pages 15 | issues: write # comment on released issues 16 | pull-requests: write # comment on released pull requests 17 | 18 | jobs: 19 | build-and-deploy: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 23 | 24 | - uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3 25 | with: 26 | cache: "npm" 27 | node-version-file: ".nvmrc" 28 | 29 | - name: Info 30 | run: | 31 | cat < 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scratch-sb1-converter 2 | 3 | Scratch 1 (.sb) to Scratch 2 (.sb2) conversion library for Scratch 3.0 4 | 5 | ## Committing 6 | 7 | This project uses [semantic release](https://github.com/semantic-release/semantic-release) to ensure version bumps 8 | follow semver so that projects depending on it don't break unexpectedly. 9 | 10 | In order to automatically determine version updates, semantic release expects commit messages to follow the 11 | [conventional-changelog](https://github.com/bcoe/conventional-changelog-standard/blob/master/convention.md) 12 | specification. 13 | 14 | You can use the [commitizen CLI](https://github.com/commitizen/cz-cli) to make commits formatted in this way: 15 | 16 | ```bash 17 | npm install -g commitizen@latest cz-conventional-changelog@latest 18 | ``` 19 | 20 | Now you're ready to make commits using `git cz`. 21 | -------------------------------------------------------------------------------- /TRADEMARK: -------------------------------------------------------------------------------- 1 | The Scratch trademarks, including the Scratch name, logo, the Scratch Cat, Gobo, Pico, Nano, Tera and Giga graphics (the "Marks"), are property of the Massachusetts Institute of Technology (MIT). Marks may not be used to endorse or promote products derived from this software without specific prior written permission. 2 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['@commitlint/config-conventional'], 3 | ignores: [message => message.startsWith('chore(release):')] 4 | }; 5 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | export {SB1File} from './src/sb1-file'; 2 | export {AssertionError, ValidationError} from './src/util/assert'; 3 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scratch-sb1-converter", 3 | "version": "2.0.152", 4 | "description": "Scratch 1 (.sb) to Scratch 2 (.sb2) conversion library for Scratch 3.0", 5 | "author": "Scratch Foundation", 6 | "license": "AGPL-3.0-only", 7 | "homepage": "https://github.com/scratchfoundation/scratch-sb1-converter#readme", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/scratchfoundation/scratch-sb1-converter.git" 11 | }, 12 | "main": "playground/main.js", 13 | "browser": "index.js", 14 | "scripts": { 15 | "build": "npm run docs && webpack --progress --colors --bail", 16 | "commitmsg": "commitlint -e $GIT_PARAMS", 17 | "deploy": "touch playground/.nojekyll && gh-pages -t -d playground -m \"Build for $(git log --pretty=format:%H -n1)\"", 18 | "docs": "jsdoc -c .jsdoc.json", 19 | "lint": "eslint .", 20 | "prepare": "husky install", 21 | "semantic-release": "semantic-release", 22 | "start": "webpack-dev-server --output-library-target=umd2", 23 | "test:ci:build": "babel --presets @babel/preset-env . --out-dir dist/test-tmp --only src,test,index.js --source-maps", 24 | "test:ci:unit": "npm run test:ci:build && tap ./dist/test-tmp/test/unit", 25 | "test:ci:integration": "npm run test:ci:build && tap ./dist/test-tmp/test/integration", 26 | "test:ci": "npm run test:ci:build && tap ./dist/test-tmp/test", 27 | "test:unit": "tap --node-arg=--require --node-arg=@babel/register ./test/unit", 28 | "test:integration": "tap --node-arg=--require --node-arg=@babel/register ./test/integration", 29 | "test:coverage": "tap --node-arg=--require --node-arg=@babel/register ./test/{unit,integration}/*.js --coverage --coverage-report=lcov", 30 | "test": "npm run lint && npm run docs && npm run test:unit && npm run test:integration", 31 | "watch": "webpack --progress --colors --watch" 32 | }, 33 | "dependencies": { 34 | "js-md5": "^0.7.3", 35 | "minilog": "^3.1.0", 36 | "text-encoding": "^0.7.0" 37 | }, 38 | "devDependencies": { 39 | "@babel/cli": "7.27.2", 40 | "@babel/core": "7.27.3", 41 | "@babel/eslint-parser": "7.27.1", 42 | "@babel/preset-env": "7.27.2", 43 | "@babel/register": "7.27.1", 44 | "@commitlint/cli": "18.6.1", 45 | "@commitlint/config-conventional": "18.6.3", 46 | "babel-eslint": "10.1.0", 47 | "babel-loader": "8.4.1", 48 | "docdash": "1.2.0", 49 | "eslint": "8.57.1", 50 | "eslint-config-scratch": "9.0.9", 51 | "gh-pages": "1.2.0", 52 | "html-webpack-plugin": "3.2.0", 53 | "husky": "8.0.3", 54 | "jsdoc": "3.6.11", 55 | "json": "^9.0.4", 56 | "scratch-semantic-release-config": "3.0.0", 57 | "semantic-release": "19.0.5", 58 | "tap": "12.7.0", 59 | "webpack": "4.47.0", 60 | "webpack-cli": "3.3.12", 61 | "webpack-dev-server": "3.11.3" 62 | }, 63 | "config": { 64 | "commitizen": { 65 | "path": "cz-conventional-changelog" 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /release.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: 'scratch-semantic-release-config', 3 | branches: [ 4 | { 5 | name: 'develop' 6 | // default channel 7 | }, 8 | { 9 | name: 'hotfix/*', 10 | channel: 'hotfix', 11 | prerelease: 'hotfix' 12 | } 13 | ] 14 | }; 15 | -------------------------------------------------------------------------------- /renovate.json5: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "github>scratchfoundation/scratch-renovate-config:js-lib-bundled" 5 | ], 6 | "baseBranches": ["develop"] 7 | } 8 | -------------------------------------------------------------------------------- /src/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: ['scratch', 'scratch/es6'], 4 | env: { 5 | browser: true 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /src/coders/adler32.js: -------------------------------------------------------------------------------- 1 | class Adler32 { 2 | constructor () { 3 | this.adler = 1; 4 | } 5 | 6 | update (uint8a, position, length) { 7 | let a = this.adler & 0xffff; 8 | let b = this.adler >>> 16; 9 | for (let i = 0; i < length; i++) { 10 | a = (a + uint8a[position + i]) % 65521; 11 | b = (b + a) % 65521; 12 | } 13 | this.adler = (b << 16) | a; 14 | return this; 15 | } 16 | 17 | get digest () { 18 | return this.adler; 19 | } 20 | } 21 | 22 | export {Adler32}; 23 | -------------------------------------------------------------------------------- /src/coders/byte-packets.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @typedef {function} PacketConstructor 3 | */ 4 | 5 | /** 6 | * A packet of bytes represented with getter/setter properties for decoding and 7 | * encoding values mapped to names, located at known offsets. 8 | * 9 | * ```js 10 | * // Defining a subclass: 11 | * import {Packet} from '../coders/byte-packets'; 12 | * import {Uint8, Uint16LE} from '../coders/byte-primitives'; 13 | * 14 | * class MyIdentifiedUint16 extends Packet.extend({ 15 | * binaryType: Uint8, 16 | * value: Uint16LE 17 | * }) {} 18 | * 19 | * Packet.initConstructor(MyIdentifiedUint16); 20 | * 21 | * // One way to use it: 22 | * const indentifiedUint16 = new MyIdentifiedUint16(uint8a, position); 23 | * indentifiedUint16.binaryType = IDENTIFIED_UINT_16; 24 | * indentifiedUint16.value = value; 25 | * ``` 26 | */ 27 | class Packet { 28 | /** 29 | * @param {Uint8Array=} [uint8a=new Uint8Array(this.size)] - byte array to 30 | * encode to and decode from 31 | * @param {number=} offset - offset in addition to the member offsets to 32 | * encode to and decode from 33 | */ 34 | constructor (uint8a = new Uint8Array(this.size), offset = 0) { 35 | /** 36 | * Byte array to encode to and decode from. 37 | * @type {Uint8Array} 38 | */ 39 | this.uint8a = uint8a; 40 | 41 | /** 42 | * Offset in addition to the member offsets to encode to and decode 43 | * from. 44 | * @type {number} 45 | */ 46 | this.offset = offset; 47 | } 48 | 49 | /** 50 | * Check that the decoded values of this Packet match the values in other. 51 | * @param {object} other - object to match against 52 | * @returns {boolean} true if all keys in other match values in this packet 53 | */ 54 | equals (other) { 55 | for (const key in other) { 56 | if (this[key] !== other[key]) { 57 | return false; 58 | } 59 | } 60 | return true; 61 | } 62 | 63 | view () { 64 | const className = this.constructor.name; 65 | const obj = { 66 | toString () { 67 | return className; 68 | } 69 | }; 70 | for (const key in this.shape) { 71 | obj[key] = this[key]; 72 | } 73 | return obj; 74 | } 75 | 76 | /** 77 | * Initialize the Packet subclass constructor for easy access to static 78 | * members like size. 79 | * @param {function} PacketConstructor - constuctor function for the Packet 80 | * subclass 81 | * @returns {function} initialized constructor 82 | */ 83 | static initConstructor (PacketConstructor) { 84 | PacketConstructor.size = PacketConstructor.prototype.size; 85 | return PacketConstructor; 86 | } 87 | 88 | /** 89 | * Extend a subclass of Packet with given BytePrimitive members. 90 | * @param {object} shape - shape of the packet defined with BytePrimitives 91 | * @returns {function} Packet subclass constructor 92 | */ 93 | static extend (shape) { 94 | const DefinedPacket = class extends Packet { 95 | get shape () { 96 | return shape; 97 | } 98 | }; 99 | 100 | let position = 0; 101 | Object.keys(shape).forEach(key => { 102 | Object.defineProperty(DefinedPacket.prototype, key, shape[key].asPropertyObject(position)); 103 | if (shape[key].size === 0) { 104 | throw new Error('Packet cannot be defined with variable sized members.'); 105 | } 106 | position += shape[key].size; 107 | }); 108 | 109 | DefinedPacket.prototype.size = position; 110 | DefinedPacket.size = position; 111 | 112 | return DefinedPacket; 113 | } 114 | } 115 | 116 | export {Packet}; 117 | -------------------------------------------------------------------------------- /src/coders/byte-primitives.js: -------------------------------------------------------------------------------- 1 | import {assert} from '../util/assert'; 2 | 3 | const notImplemented = () => { 4 | throw new Error('Not implemented'); 5 | }; 6 | 7 | /** 8 | * Is the host computer little or big endian. 9 | * @const IS_HOST_LITTLE_ENDIAN 10 | * @type {boolean} 11 | */ 12 | const IS_HOST_LITTLE_ENDIAN = (() => { 13 | const ab16 = new Uint16Array(1); 14 | const ab8 = new Uint8Array(ab16.buffer); 15 | ab16[0] = 0xaabb; 16 | return ab8[0] === 0xbb; 17 | })(); 18 | 19 | /** 20 | * @callback BytePrimitive~sizeOfCallback 21 | * @param {Uint8Array} uint8a 22 | * @param {number} position 23 | * @returns {number} 24 | */ 25 | 26 | /** 27 | * @callback BytePrimitive~writeSizeOfCallback 28 | * @param {Uint8Array} uint8a 29 | * @param {number} position 30 | * @param {*} value 31 | * @returns {number} 32 | */ 33 | 34 | /** 35 | * @callback BytePrimitive~writeCallback 36 | * @param {Uint8Array} uint8a 37 | * @param {number} position 38 | * @param {*} value 39 | */ 40 | 41 | /** 42 | * An interface for reading and writing binary values to typed arrays. 43 | * 44 | * Combined with {@link Packet Packet} this makes reading and writing packets 45 | * of binary values easy. 46 | */ 47 | class BytePrimitive { 48 | /** 49 | * @constructor 50 | * @param {object} options - Options to initialize BytePrimitive instance 51 | * with. 52 | * @param {number} [options.size=0] - Fixed size of the BytePrimitive. 53 | * Should be 0 if the primitive has a variable size. 54 | * @param {BytePrimitive~sizeOfCallback} [options.sizeOf=() => size] - 55 | * Variable size of the primitive depending on its value stored in the 56 | * array. 57 | * @param {BytePrimitive~writeSizeOfCallback} [options.writeSizeOf] - 58 | * Variable size of the primitive depending on the value being written. 59 | * @param {TypedArray} [options.toBytes=new Uint8Array(1)] - Temporary 60 | * space to copy bytes to/from to translate between a value and its 61 | * representative byte set. 62 | * @param {BytePrimitive#read} options.read - How is a value read 63 | * at the given position of the array. 64 | * @param {BytePrimitive~writeCallback} [options.write] - How to write a 65 | * value to the array at the given position. 66 | */ 67 | constructor ({ 68 | size = 0, 69 | sizeOf = () => size, 70 | writeSizeOf = notImplemented, 71 | toBytes = new Uint8Array(1), 72 | read, 73 | write = notImplemented 74 | }) { 75 | this.size = size; 76 | this.sizeOf = sizeOf; 77 | this.writeSizeOf = writeSizeOf; 78 | 79 | this.toBytes = toBytes; 80 | this.bytes = new Uint8Array(toBytes.buffer); 81 | 82 | this.read = read; 83 | this.write = write; 84 | } 85 | 86 | /** 87 | * Create an object that can be used with `Object.defineProperty` to read 88 | * and write values offset by `position` and the object's `this.offset` 89 | * from `this.uint8a` by getting or setting the property. 90 | * @param {number} position - Additional offset with `this.offset` to read 91 | * from or write to. 92 | * @returns {object} - A object that can be passed as the third argument to 93 | * `Object.defineProperty`. 94 | */ 95 | asPropertyObject (position) { 96 | const _this = this; 97 | 98 | return { 99 | get () { 100 | return _this.read(this.uint8a, position + this.offset); 101 | }, 102 | 103 | set (value) { 104 | return _this.write(this.uint8a, position + this.offset, value); 105 | }, 106 | 107 | enumerable: true 108 | }; 109 | } 110 | 111 | /** 112 | * Read a value from `position` in `uint8a`. 113 | * @param {Uint8Array} uint8a - Array to read from. 114 | * @param {number} position - Position in `uint8a` to read from. 115 | * @returns {*} - Value read from `uint8a` at `position`. 116 | */ 117 | read () { 118 | return null; 119 | } 120 | } 121 | 122 | /** 123 | * @const Uint8 124 | * @type {BytePrimitive} 125 | */ 126 | const Uint8 = new BytePrimitive({ 127 | size: 1, 128 | read (uint8a, position) { 129 | return uint8a[position]; 130 | }, 131 | write (uint8a, position, value) { 132 | uint8a[position] = value; 133 | return value; 134 | } 135 | }); 136 | 137 | const HOSTLE_BE16 = { 138 | size: 2, 139 | // toBytes: Defined by instance. 140 | read (uint8a, position) { 141 | this.bytes[1] = uint8a[position + 0]; 142 | this.bytes[0] = uint8a[position + 1]; 143 | return this.toBytes[0]; 144 | }, 145 | write (uint8a, position, value) { 146 | this.toBytes[0] = value; 147 | uint8a[position + 0] = this.bytes[1]; 148 | uint8a[position + 1] = this.bytes[0]; 149 | return value; 150 | } 151 | }; 152 | const HOSTBE_BE16 = { 153 | size: 2, 154 | // toBytes: Defined by instance. 155 | read (uint8a, position) { 156 | this.bytes[0] = uint8a[position + 0]; 157 | this.bytes[1] = uint8a[position + 1]; 158 | return this.toBytes[0]; 159 | }, 160 | write (uint8a, position, value) { 161 | this.toBytes[0] = value; 162 | uint8a[position + 0] = this.bytes[0]; 163 | uint8a[position + 1] = this.bytes[1]; 164 | return value; 165 | } 166 | }; 167 | 168 | let BE16; 169 | if (IS_HOST_LITTLE_ENDIAN) { 170 | BE16 = HOSTLE_BE16; 171 | } else { 172 | BE16 = HOSTBE_BE16; 173 | } 174 | 175 | /** 176 | * @const Uint16BE 177 | * @type {BytePrimitive} 178 | */ 179 | const Uint16BE = new BytePrimitive(Object.assign({}, BE16, { 180 | toBytes: new Uint16Array(1) 181 | })); 182 | 183 | /** 184 | * @const Int16BE 185 | * @type {BytePrimitive} 186 | */ 187 | const Int16BE = new BytePrimitive(Object.assign({}, BE16, { 188 | toBytes: new Int16Array(1) 189 | })); 190 | 191 | const HOSTLE_BE32 = { 192 | size: 4, 193 | // toBytes: Defined by instance. 194 | read (uint8a, position) { 195 | this.bytes[3] = uint8a[position + 0]; 196 | this.bytes[2] = uint8a[position + 1]; 197 | this.bytes[1] = uint8a[position + 2]; 198 | this.bytes[0] = uint8a[position + 3]; 199 | return this.toBytes[0]; 200 | }, 201 | write (uint8a, position, value) { 202 | this.toBytes[0] = value; 203 | uint8a[position + 0] = this.bytes[3]; 204 | uint8a[position + 1] = this.bytes[2]; 205 | uint8a[position + 2] = this.bytes[1]; 206 | uint8a[position + 3] = this.bytes[0]; 207 | return value; 208 | } 209 | }; 210 | 211 | const HOSTBE_BE32 = { 212 | size: 4, 213 | // toBytes: Defined by instance. 214 | read (uint8a, position) { 215 | this.bytes[0] = uint8a[position + 0]; 216 | this.bytes[1] = uint8a[position + 1]; 217 | this.bytes[2] = uint8a[position + 2]; 218 | this.bytes[3] = uint8a[position + 3]; 219 | return this.toBytes[0]; 220 | }, 221 | write (uint8a, position, value) { 222 | this.toBytes[0] = value; 223 | uint8a[position + 0] = this.bytes[0]; 224 | uint8a[position + 1] = this.bytes[1]; 225 | uint8a[position + 2] = this.bytes[2]; 226 | uint8a[position + 3] = this.bytes[3]; 227 | return value; 228 | } 229 | }; 230 | 231 | let BE32; 232 | if (IS_HOST_LITTLE_ENDIAN) { 233 | BE32 = HOSTLE_BE32; 234 | } else { 235 | BE32 = HOSTBE_BE32; 236 | } 237 | 238 | /** 239 | * @const Int32BE 240 | * @type {BytePrimitive} 241 | */ 242 | const Int32BE = new BytePrimitive(Object.assign({}, BE32, { 243 | toBytes: new Int32Array(1) 244 | })); 245 | 246 | /** 247 | * @const Uint32BE 248 | * @type {BytePrimitive} 249 | */ 250 | const Uint32BE = new BytePrimitive(Object.assign({}, BE32, { 251 | toBytes: new Uint32Array(1) 252 | })); 253 | 254 | let LE16; 255 | if (IS_HOST_LITTLE_ENDIAN) { 256 | LE16 = HOSTBE_BE16; 257 | } else { 258 | LE16 = HOSTLE_BE16; 259 | } 260 | 261 | /** 262 | * @const Uint16LE 263 | * @type {BytePrimitive} 264 | */ 265 | const Uint16LE = new BytePrimitive(Object.assign({}, LE16, { 266 | toBytes: new Uint16Array(1) 267 | })); 268 | 269 | let LE32; 270 | if (IS_HOST_LITTLE_ENDIAN) { 271 | LE32 = HOSTBE_BE32; 272 | } else { 273 | LE32 = HOSTLE_BE32; 274 | } 275 | 276 | /** 277 | * @const Uint32LE 278 | * @type {BytePrimitive} 279 | */ 280 | const Uint32LE = new BytePrimitive(Object.assign({}, LE32, { 281 | toBytes: new Uint32Array(1) 282 | })); 283 | 284 | const HOSTLE_BEDOUBLE = { 285 | size: 8, 286 | read (uint8a, position) { 287 | this.bytes[7] = uint8a[position + 0]; 288 | this.bytes[6] = uint8a[position + 1]; 289 | this.bytes[5] = uint8a[position + 2]; 290 | this.bytes[4] = uint8a[position + 3]; 291 | this.bytes[3] = uint8a[position + 4]; 292 | this.bytes[2] = uint8a[position + 5]; 293 | this.bytes[1] = uint8a[position + 6]; 294 | this.bytes[0] = uint8a[position + 7]; 295 | return this.toBytes[0]; 296 | } 297 | }; 298 | 299 | const HOSTBE_BEDOUBLE = { 300 | size: 8, 301 | read (uint8a, position) { 302 | this.bytes[7] = uint8a[position + 0]; 303 | this.bytes[6] = uint8a[position + 1]; 304 | this.bytes[5] = uint8a[position + 2]; 305 | this.bytes[4] = uint8a[position + 3]; 306 | this.bytes[3] = uint8a[position + 4]; 307 | this.bytes[2] = uint8a[position + 5]; 308 | this.bytes[1] = uint8a[position + 6]; 309 | this.bytes[0] = uint8a[position + 7]; 310 | return this.toBytes[0]; 311 | } 312 | }; 313 | 314 | let BEDOUBLE; 315 | if (IS_HOST_LITTLE_ENDIAN) { 316 | BEDOUBLE = HOSTLE_BEDOUBLE; 317 | } else { 318 | BEDOUBLE = HOSTBE_BEDOUBLE; 319 | } 320 | 321 | /** 322 | * @const DoubleBE 323 | * @type {BytePrimitive} 324 | */ 325 | const DoubleBE = new BytePrimitive(Object.assign({}, BEDOUBLE, { 326 | toBytes: new Float64Array(1) 327 | })); 328 | 329 | /** 330 | * @extends BytePrimitive 331 | */ 332 | class FixedAsciiString extends BytePrimitive { 333 | /** 334 | * @param {number} size - Number of bytes the FixedAsciiString uses. 335 | */ 336 | constructor (size) { 337 | super({ 338 | size, 339 | read (uint8a, position) { 340 | let str = ''; 341 | for (let i = 0; i < size; i++) { 342 | const code = uint8a[position + i]; 343 | assert(code <= 127, 'Non-ascii character in FixedAsciiString'); 344 | str += String.fromCharCode(code); 345 | } 346 | return str; 347 | }, 348 | write (uint8a, position, value) { 349 | for (let i = 0; i < size; i++) { 350 | const code = value.charCodeAt(i); 351 | assert(code <= 127, 'Non-ascii character in FixedAsciiString'); 352 | uint8a[position + i] = code; 353 | } 354 | return value; 355 | } 356 | }); 357 | } 358 | } 359 | 360 | export { 361 | IS_HOST_LITTLE_ENDIAN, 362 | BytePrimitive, 363 | Uint8, 364 | Uint16BE, 365 | Int16BE, 366 | Int32BE, 367 | Uint32BE, 368 | Uint16LE, 369 | Uint32LE, 370 | DoubleBE, 371 | FixedAsciiString 372 | }; 373 | -------------------------------------------------------------------------------- /src/coders/byte-stream.js: -------------------------------------------------------------------------------- 1 | import {assert} from '../util/assert'; 2 | 3 | /** 4 | * Read and write a stream of {@link BytePrimitive}s, {@link Packet}s, or byte 5 | * arrays to an ArrayBuffer. 6 | */ 7 | class ByteStream { 8 | /** 9 | * @param {ArrayBuffer} buffer - The ArrayBuffer to read from or write to. 10 | * @param {number=} [position=0] - The position to start reading or writing 11 | * from in the ArrayBuffer. 12 | */ 13 | constructor (buffer, position = 0) { 14 | /** 15 | * The ArrayBuffer to read from or write to. 16 | * @type {ArrayBuffer} 17 | */ 18 | this.buffer = buffer; 19 | 20 | /** 21 | * The position to start reading or writing from in the ArrayBuffer. 22 | * @type {number} 23 | */ 24 | this.position = position; 25 | 26 | /** 27 | * The typed array view of the buffer to read and write with. 28 | * @type {Uint8Array} 29 | */ 30 | this.uint8a = new Uint8Array(this.buffer); 31 | } 32 | 33 | /** 34 | * Read one instance of a given BytePrimitive and increment position based 35 | * on the size of that value. 36 | * @param {BytePrimitive} member - BytePrimitive to read and increment size 37 | * with. 38 | * @returns {*} Return the value produced by the BytePrimitive. 39 | */ 40 | read (member) { 41 | const value = member.read(this.uint8a, this.position); 42 | if (member.size === 0) { 43 | this.position += member.sizeOf(this.uint8a, this.position); 44 | } else { 45 | this.position += member.size; 46 | } 47 | return value; 48 | } 49 | 50 | /** 51 | * Read one instance of a given Packet subclass and increment position 52 | * based on the size of that value. 53 | * @param {PacketConstructor} StructType - Packet subclass constructor that 54 | * can read from the current stream position. 55 | * @returns {Packet} Instance of a Packet pointed at the position of the 56 | * stream before calling readStruct. 57 | */ 58 | readStruct (StructType) { 59 | const obj = new StructType(this.uint8a, this.position); 60 | this.position += StructType.size; 61 | return obj; 62 | } 63 | 64 | /** 65 | * Resize the internal buffer to allow for the needed amount of space. 66 | * @param {number} needed - How many bytes need to fit in the buffer. 67 | * @private 68 | */ 69 | resize (needed) { 70 | if (this.buffer.byteLength < needed) { 71 | const uint8a = this.uint8a; 72 | const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log(needed) / Math.log(2))); 73 | this.buffer = new ArrayBuffer(nextPowerOf2); 74 | 75 | this.uint8a = new Uint8Array(this.buffer); 76 | this.uint8a.set(uint8a); 77 | } 78 | } 79 | 80 | /** 81 | * Write a value to the stream (with a BytePrimitive defining how to do so) 82 | * and increment the position. 83 | * @param {BytePrimitive} member - BytePrimitive to define how to write the 84 | * value. 85 | * @param {*} value - Value to write. 86 | * @returns {*} Value passed to the method. 87 | */ 88 | write (member, value) { 89 | if (member.size === 0) { 90 | this.resize(this.position + member.writeSizeOf(value)); 91 | } else { 92 | this.resize(this.position + member.size); 93 | } 94 | 95 | member.write(this.uint8a, this.position, value); 96 | if (member.size === 0) { 97 | this.position += member.writeSizeOf(this.uint8a, this.position); 98 | } else { 99 | this.position += member.size; 100 | } 101 | return value; 102 | } 103 | 104 | /** 105 | * Write data to the stream structured by a given Packet subclass 106 | * constructor and increment the position. 107 | * @param {PacketConstructor} StructType - The Packet subclass constructor 108 | * defining how to write the data. 109 | * @param {object} data - Data to write. 110 | * @returns {Packet} - Constructed packet after writing data. 111 | */ 112 | writeStruct (StructType, data) { 113 | this.resize(this.position + StructType.size); 114 | 115 | const st = Object.assign(new StructType(this.uint8a, this.position), data); 116 | this.position += StructType.size; 117 | return st; 118 | } 119 | 120 | /** 121 | * Write bytes from the given Uint8Array array to the stream and increment 122 | * the position. 123 | * @param {Uint8Array} bytes - Bytes to write to the stream. 124 | * @param {number=} [start=0] - Where in bytes to start writing from. 125 | * @param {number=} [end=bytes.length] - Where in bytes to stop writing, excluding position at bytes[end]. 126 | * @returns {Uint8Array} Passed bytes Uint8Array. 127 | */ 128 | writeBytes (bytes, start = 0, end = bytes.length) { 129 | assert(bytes instanceof Uint8Array, 'writeBytes must be passed an Uint8Array'); 130 | 131 | this.resize(this.position + (end - start)); 132 | 133 | for (let i = start; i < end; i++) { 134 | this.uint8a[this.position + i - start] = bytes[i]; 135 | } 136 | this.position += end - start; 137 | return bytes; 138 | } 139 | } 140 | 141 | export {ByteStream}; 142 | -------------------------------------------------------------------------------- /src/coders/crc32.js: -------------------------------------------------------------------------------- 1 | class CRC32 { 2 | constructor () { 3 | this.bit = new Uint32Array(1); 4 | this.crc = 0; 5 | this.c = 0; 6 | 7 | this.table = []; 8 | let c; 9 | for (let i = 0; i < 256; i++) { 10 | c = i; 11 | for (let j = 0; j < 8; j++) { 12 | c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); 13 | } 14 | this.table[i] = c >>> 0; 15 | } 16 | } 17 | 18 | update (uint8a, position = 0, length = uint8a.length) { 19 | let crc = (~this.crc) >>> 0; 20 | for (let i = 0; i < length; i++) { 21 | crc = (crc >>> 8) ^ this.table[(crc ^ uint8a[position + i]) & 0xff]; 22 | } 23 | this.crc = (~crc) >>> 0; 24 | return this; 25 | } 26 | 27 | get digest () { 28 | return this.crc; 29 | } 30 | } 31 | 32 | export {CRC32}; 33 | -------------------------------------------------------------------------------- /src/coders/deflate-packets.js: -------------------------------------------------------------------------------- 1 | import {Packet} from './byte-packets'; 2 | import {Uint8, Uint16LE, Uint32LE} from './byte-primitives'; 3 | 4 | const DEFLATE_BLOCK_SIZE_MAX = 0xffff; 5 | 6 | export {DEFLATE_BLOCK_SIZE_MAX}; 7 | 8 | class DeflateHeader extends Packet.extend({ 9 | cmf: Uint8, 10 | flag: Uint8 11 | }) {} 12 | 13 | Packet.initConstructor(DeflateHeader); 14 | 15 | export {DeflateHeader}; 16 | 17 | class DeflateChunkStart extends Packet.extend({ 18 | lastPacket: Uint8, 19 | length: Uint16LE, 20 | lengthCheck: Uint16LE 21 | }) {} 22 | 23 | Packet.initConstructor(DeflateChunkStart); 24 | 25 | export {DeflateChunkStart}; 26 | 27 | class DeflateEnd extends Packet.extend({ 28 | checksum: Uint32LE 29 | }) {} 30 | 31 | Packet.initConstructor(DeflateEnd); 32 | 33 | export {DeflateEnd}; 34 | -------------------------------------------------------------------------------- /src/coders/deflate-stream.js: -------------------------------------------------------------------------------- 1 | import {Adler32} from './adler32'; 2 | import {DEFLATE_BLOCK_SIZE_MAX, DeflateHeader, DeflateChunkStart, DeflateEnd} from './deflate-packets'; 3 | import {ProxyStream} from './proxy-stream'; 4 | 5 | class DeflateStream extends ProxyStream { 6 | constructor (stream) { 7 | super(stream); 8 | 9 | this.stream.writeStruct(DeflateHeader, { 10 | cmf: 0b00001000, 11 | flag: 0b00011101 12 | }); 13 | 14 | this.adler = new Adler32(); 15 | 16 | this.chunk = this.stream.writeStruct(DeflateChunkStart, { 17 | lastPacket: 0, 18 | length: 0, 19 | lengthCheck: 0 ^ 0xffff 20 | }); 21 | } 22 | 23 | get _deflateIndex () { 24 | return this.chunk.length; 25 | } 26 | 27 | set _deflateIndex (value) { 28 | this.chunk.length = value; 29 | this.chunk.lengthCheck = value ^ 0xffff; 30 | } 31 | 32 | writeStruct (StructType, data) { 33 | this.writeBytes(Object.assign(new StructType(), data).uint8a); 34 | } 35 | 36 | writeBytes (bytes, start = 0, end = bytes.length) { 37 | let chunkStart = start; 38 | while (end - chunkStart > 0) { 39 | if (this._deflateIndex === DEFLATE_BLOCK_SIZE_MAX) { 40 | this.chunk = this.stream.writeStruct(DeflateChunkStart, { 41 | lastPacket: 0, 42 | length: 0, 43 | lengthCheck: 0 ^ 0xffff 44 | }); 45 | } 46 | 47 | const chunkLength = Math.min( 48 | end - chunkStart, 49 | DEFLATE_BLOCK_SIZE_MAX - this._deflateIndex 50 | ); 51 | this.stream.writeBytes(bytes, chunkStart, chunkStart + chunkLength); 52 | this._deflateIndex += chunkLength; 53 | chunkStart += chunkLength; 54 | } 55 | 56 | this.adler.update(bytes, start, end - start); 57 | } 58 | 59 | finish () { 60 | this.chunk.lastPacket = 1; 61 | 62 | this.stream.writeStruct(DeflateEnd, { 63 | checksum: this.adler.digest 64 | }); 65 | } 66 | 67 | static estimateSize (bodySize) { 68 | const packets = Math.ceil(bodySize / DEFLATE_BLOCK_SIZE_MAX); 69 | return ( 70 | DeflateHeader.size + 71 | (packets * DeflateChunkStart.size) + 72 | DeflateEnd.size + 73 | bodySize 74 | ); 75 | } 76 | } 77 | 78 | export {DeflateStream}; 79 | -------------------------------------------------------------------------------- /src/coders/png-chunk-stream.js: -------------------------------------------------------------------------------- 1 | import {Uint32BE} from './byte-primitives'; 2 | import {CRC32} from './crc32'; 3 | import {PNGChunkStart, PNGChunkEnd} from './png-packets'; 4 | import {ProxyStream} from './proxy-stream'; 5 | 6 | class PNGChunkStream extends ProxyStream { 7 | constructor (stream, chunkType = 'IHDR') { 8 | super(stream); 9 | 10 | this.start = this.stream.writeStruct(PNGChunkStart, { 11 | length: 0, 12 | chunkType 13 | }); 14 | 15 | this.crc = new CRC32(); 16 | } 17 | 18 | finish () { 19 | const crcStart = this.start.offset + this.start.size; 20 | const length = this.position - crcStart; 21 | this.start.length = length; 22 | 23 | this.crc.update(this.stream.uint8a, crcStart - Uint32BE.size, length + Uint32BE.size); 24 | this.stream.writeStruct(PNGChunkEnd, { 25 | checksum: this.crc.digest 26 | }); 27 | } 28 | 29 | static size (bodySize) { 30 | return PNGChunkStart.size + bodySize + PNGChunkEnd.size; 31 | } 32 | } 33 | 34 | export {PNGChunkStream}; 35 | -------------------------------------------------------------------------------- /src/coders/png-file.js: -------------------------------------------------------------------------------- 1 | import {ByteStream} from './byte-stream'; 2 | import {PNGSignature, PNGIHDRChunkBody, PNGFilterMethodByte} from './png-packets'; 3 | import {DeflateStream} from './deflate-stream'; 4 | import {PNGChunkStream} from './png-chunk-stream'; 5 | 6 | class PNGFile { 7 | encode (width, height, pixelsUint8) { 8 | const rowSize = (width * 4) + PNGFilterMethodByte.size; 9 | const bodySize = rowSize * height; 10 | const size = ( 11 | PNGSignature.size + 12 | // IHDR 13 | PNGChunkStream.size(PNGIHDRChunkBody.size) + 14 | // IDAT 15 | PNGChunkStream.size(DeflateStream.estimateSize(bodySize)) + 16 | // IEND 17 | PNGChunkStream.size(0) 18 | ); 19 | 20 | const stream = new ByteStream(new ArrayBuffer(size)); 21 | 22 | stream.writeStruct(PNGSignature, { 23 | support8Bit: 0x89, 24 | png: 'PNG', 25 | dosLineEnding: '\r\n', 26 | dosEndOfFile: '\x1a', 27 | unixLineEnding: '\n' 28 | }); 29 | 30 | const pngIhdr = new PNGChunkStream(stream, 'IHDR'); 31 | 32 | pngIhdr.writeStruct(PNGIHDRChunkBody, { 33 | width, 34 | height, 35 | bitDepth: 8, 36 | colorType: 6, 37 | compressionMethod: 0, 38 | filterMethod: 0, 39 | interlaceMethod: 0 40 | }); 41 | 42 | pngIhdr.finish(); 43 | 44 | const pngIdat = new PNGChunkStream(stream, 'IDAT'); 45 | 46 | const deflate = new DeflateStream(pngIdat); 47 | 48 | let pixelsIndex = 0; 49 | while (pixelsIndex < pixelsUint8.length) { 50 | deflate.writeStruct(PNGFilterMethodByte, { 51 | method: 0 52 | }); 53 | 54 | const partialLength = Math.min( 55 | pixelsUint8.length - pixelsIndex, 56 | rowSize - PNGFilterMethodByte.size 57 | ); 58 | deflate.writeBytes( 59 | pixelsUint8, pixelsIndex, pixelsIndex + partialLength 60 | ); 61 | 62 | pixelsIndex += partialLength; 63 | } 64 | 65 | deflate.finish(); 66 | 67 | pngIdat.finish(); 68 | 69 | const pngIend = new PNGChunkStream(stream, 'IEND'); 70 | 71 | pngIend.finish(); 72 | 73 | return stream.buffer; 74 | } 75 | 76 | static encode (width, height, pixels) { 77 | return new PNGFile().encode(width, height, pixels); 78 | } 79 | } 80 | 81 | export {PNGFile}; 82 | -------------------------------------------------------------------------------- /src/coders/png-packets.js: -------------------------------------------------------------------------------- 1 | import {assert} from '../util/assert'; 2 | 3 | import {Packet} from './byte-packets'; 4 | import {Uint8, Uint32BE, FixedAsciiString} from './byte-primitives'; 5 | 6 | class PNGSignature extends Packet.extend({ 7 | support8Bit: Uint8, 8 | png: new FixedAsciiString(3), 9 | dosLineEnding: new FixedAsciiString(2), 10 | dosEndOfFile: new FixedAsciiString(1), 11 | unixLineEnding: new FixedAsciiString(1) 12 | }) { 13 | static validate () { 14 | assert(this.equals({ 15 | support8Bit: 0x89, 16 | png: 'PNG', 17 | dosLineEnding: '\r\n', 18 | dosEndOfFile: '\x1a', 19 | unixLineEnding: '\n' 20 | }), 'PNGSignature does not match the expected values'); 21 | } 22 | } 23 | 24 | Packet.initConstructor(PNGSignature); 25 | 26 | export {PNGSignature}; 27 | 28 | class PNGChunkStart extends Packet.extend({ 29 | length: Uint32BE, 30 | chunkType: new FixedAsciiString(4) 31 | }) {} 32 | 33 | Packet.initConstructor(PNGChunkStart); 34 | 35 | export {PNGChunkStart}; 36 | 37 | class PNGChunkEnd extends Packet.extend({ 38 | checksum: Uint32BE 39 | }) {} 40 | 41 | Packet.initConstructor(PNGChunkEnd); 42 | 43 | export {PNGChunkEnd}; 44 | 45 | class PNGIHDRChunkBody extends Packet.extend({ 46 | width: Uint32BE, 47 | height: Uint32BE, 48 | bitDepth: Uint8, 49 | colorType: Uint8, 50 | compressionMethod: Uint8, 51 | filterMethod: Uint8, 52 | interlaceMethod: Uint8 53 | }) {} 54 | 55 | Packet.initConstructor(PNGIHDRChunkBody); 56 | 57 | export {PNGIHDRChunkBody}; 58 | 59 | class PNGFilterMethodByte extends Packet.extend({ 60 | method: Uint8 61 | }) {} 62 | 63 | Packet.initConstructor(PNGFilterMethodByte); 64 | 65 | export {PNGFilterMethodByte}; 66 | -------------------------------------------------------------------------------- /src/coders/proxy-stream.js: -------------------------------------------------------------------------------- 1 | class ProxyStream { 2 | constructor (stream) { 3 | this.stream = stream; 4 | } 5 | 6 | get uint8a () { 7 | return this.stream.uint8a; 8 | } 9 | 10 | set uint8a (value) { 11 | this.stream.uint8a = value; 12 | } 13 | 14 | get position () { 15 | return this.stream.position; 16 | } 17 | 18 | set position (value) { 19 | this.stream.position = value; 20 | } 21 | 22 | writeStruct (StructType, data) { 23 | return this.stream.writeStruct(StructType, data); 24 | } 25 | 26 | writeBytes (bytes, start = 0, end = bytes.length) { 27 | return this.stream.writeBytes(bytes, start, end); 28 | } 29 | } 30 | 31 | export {ProxyStream}; 32 | -------------------------------------------------------------------------------- /src/coders/squeak-image.js: -------------------------------------------------------------------------------- 1 | import {BytePrimitive, Uint8, Uint32BE} from './byte-primitives'; 2 | import {ByteStream} from './byte-stream'; 3 | 4 | const defaultColorMap = [ 5 | 0x00000000, 0xFF000000, 0xFFFFFFFF, 0xFF808080, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFF00FFFF, 6 | 0xFFFFFF00, 0xFFFF00FF, 0xFF202020, 0xFF404040, 0xFF606060, 0xFF9F9F9F, 0xFFBFBFBF, 0xFFDFDFDF, 7 | 0xFF080808, 0xFF101010, 0xFF181818, 0xFF282828, 0xFF303030, 0xFF383838, 0xFF484848, 0xFF505050, 8 | 0xFF585858, 0xFF686868, 0xFF707070, 0xFF787878, 0xFF878787, 0xFF8F8F8F, 0xFF979797, 0xFFA7A7A7, 9 | 0xFFAFAFAF, 0xFFB7B7B7, 0xFFC7C7C7, 0xFFCFCFCF, 0xFFD7D7D7, 0xFFE7E7E7, 0xFFEFEFEF, 0xFFF7F7F7, 10 | 0xFF000000, 0xFF003300, 0xFF006600, 0xFF009900, 0xFF00CC00, 0xFF00FF00, 0xFF000033, 0xFF003333, 11 | 0xFF006633, 0xFF009933, 0xFF00CC33, 0xFF00FF33, 0xFF000066, 0xFF003366, 0xFF006666, 0xFF009966, 12 | 0xFF00CC66, 0xFF00FF66, 0xFF000099, 0xFF003399, 0xFF006699, 0xFF009999, 0xFF00CC99, 0xFF00FF99, 13 | 0xFF0000CC, 0xFF0033CC, 0xFF0066CC, 0xFF0099CC, 0xFF00CCCC, 0xFF00FFCC, 0xFF0000FF, 0xFF0033FF, 14 | 0xFF0066FF, 0xFF0099FF, 0xFF00CCFF, 0xFF00FFFF, 0xFF330000, 0xFF333300, 0xFF336600, 0xFF339900, 15 | 0xFF33CC00, 0xFF33FF00, 0xFF330033, 0xFF333333, 0xFF336633, 0xFF339933, 0xFF33CC33, 0xFF33FF33, 16 | 0xFF330066, 0xFF333366, 0xFF336666, 0xFF339966, 0xFF33CC66, 0xFF33FF66, 0xFF330099, 0xFF333399, 17 | 0xFF336699, 0xFF339999, 0xFF33CC99, 0xFF33FF99, 0xFF3300CC, 0xFF3333CC, 0xFF3366CC, 0xFF3399CC, 18 | 0xFF33CCCC, 0xFF33FFCC, 0xFF3300FF, 0xFF3333FF, 0xFF3366FF, 0xFF3399FF, 0xFF33CCFF, 0xFF33FFFF, 19 | 0xFF660000, 0xFF663300, 0xFF666600, 0xFF669900, 0xFF66CC00, 0xFF66FF00, 0xFF660033, 0xFF663333, 20 | 0xFF666633, 0xFF669933, 0xFF66CC33, 0xFF66FF33, 0xFF660066, 0xFF663366, 0xFF666666, 0xFF669966, 21 | 0xFF66CC66, 0xFF66FF66, 0xFF660099, 0xFF663399, 0xFF666699, 0xFF669999, 0xFF66CC99, 0xFF66FF99, 22 | 0xFF6600CC, 0xFF6633CC, 0xFF6666CC, 0xFF6699CC, 0xFF66CCCC, 0xFF66FFCC, 0xFF6600FF, 0xFF6633FF, 23 | 0xFF6666FF, 0xFF6699FF, 0xFF66CCFF, 0xFF66FFFF, 0xFF990000, 0xFF993300, 0xFF996600, 0xFF999900, 24 | 0xFF99CC00, 0xFF99FF00, 0xFF990033, 0xFF993333, 0xFF996633, 0xFF999933, 0xFF99CC33, 0xFF99FF33, 25 | 0xFF990066, 0xFF993366, 0xFF996666, 0xFF999966, 0xFF99CC66, 0xFF99FF66, 0xFF990099, 0xFF993399, 26 | 0xFF996699, 0xFF999999, 0xFF99CC99, 0xFF99FF99, 0xFF9900CC, 0xFF9933CC, 0xFF9966CC, 0xFF9999CC, 27 | 0xFF99CCCC, 0xFF99FFCC, 0xFF9900FF, 0xFF9933FF, 0xFF9966FF, 0xFF9999FF, 0xFF99CCFF, 0xFF99FFFF, 28 | 0xFFCC0000, 0xFFCC3300, 0xFFCC6600, 0xFFCC9900, 0xFFCCCC00, 0xFFCCFF00, 0xFFCC0033, 0xFFCC3333, 29 | 0xFFCC6633, 0xFFCC9933, 0xFFCCCC33, 0xFFCCFF33, 0xFFCC0066, 0xFFCC3366, 0xFFCC6666, 0xFFCC9966, 30 | 0xFFCCCC66, 0xFFCCFF66, 0xFFCC0099, 0xFFCC3399, 0xFFCC6699, 0xFFCC9999, 0xFFCCCC99, 0xFFCCFF99, 31 | 0xFFCC00CC, 0xFFCC33CC, 0xFFCC66CC, 0xFFCC99CC, 0xFFCCCCCC, 0xFFCCFFCC, 0xFFCC00FF, 0xFFCC33FF, 32 | 0xFFCC66FF, 0xFFCC99FF, 0xFFCCCCFF, 0xFFCCFFFF, 0xFFFF0000, 0xFFFF3300, 0xFFFF6600, 0xFFFF9900, 33 | 0xFFFFCC00, 0xFFFFFF00, 0xFFFF0033, 0xFFFF3333, 0xFFFF6633, 0xFFFF9933, 0xFFFFCC33, 0xFFFFFF33, 34 | 0xFFFF0066, 0xFFFF3366, 0xFFFF6666, 0xFFFF9966, 0xFFFFCC66, 0xFFFFFF66, 0xFFFF0099, 0xFFFF3399, 35 | 0xFFFF6699, 0xFFFF9999, 0xFFFFCC99, 0xFFFFFF99, 0xFFFF00CC, 0xFFFF33CC, 0xFFFF66CC, 0xFFFF99CC, 36 | 0xFFFFCCCC, 0xFFFFFFCC, 0xFFFF00FF, 0xFFFF33FF, 0xFFFF66FF, 0xFFFF99FF, 0xFFFFCCFF, 0xFFFFFFFF]; 37 | 38 | const defaultOneBitColorMap = [0xFFFFFFFF, 0xFF000000]; 39 | 40 | const VariableIntBE = new BytePrimitive({ 41 | sizeOf (uint8a, position) { 42 | const count = uint8a[position]; 43 | if (count <= 223) return 1; 44 | if (count <= 254) return 2; 45 | return 5; 46 | }, 47 | read (uint8a, position) { 48 | const count = uint8a[position]; 49 | if (count <= 223) return count; 50 | if (count <= 254) return ((count - 224) * 256) + uint8a[position + 1]; 51 | return Uint32BE.read(uint8a, position + 1); 52 | } 53 | }); 54 | 55 | class SqueakImage { 56 | decode (width, height, depth, bytes, colormap) { 57 | const pixels = this.decodePixels(bytes, depth === 32); 58 | 59 | if (depth <= 8) { 60 | if (!colormap) { 61 | colormap = depth === 1 ? defaultOneBitColorMap : defaultColorMap; 62 | } 63 | return this.unpackPixels(pixels, width, height, depth, colormap); 64 | } else if (depth === 16) { 65 | return this.raster16To32(pixels, width, height); 66 | } else if (depth === 32) { 67 | return pixels; 68 | } 69 | throw new Error('Unhandled Squeak Image depth.'); 70 | } 71 | 72 | decodePixels (bytes, withAlpha) { 73 | let result; 74 | 75 | // Already decompressed 76 | if (Array.isArray(bytes) || bytes instanceof Uint32Array) { 77 | result = new Uint32Array(bytes); 78 | if (withAlpha) { 79 | for (let i = 0; i < result.length; i++) { 80 | if (result[i] !== 0) { 81 | result[i] = 0xff000000 | result[i]; 82 | } 83 | } 84 | } 85 | return result; 86 | } 87 | 88 | const stream = new ByteStream(bytes.buffer, bytes.byteOffset); 89 | 90 | const pixelsOut = stream.read(VariableIntBE); 91 | result = new Uint32Array(pixelsOut); 92 | 93 | let i = 0; 94 | while (i < pixelsOut) { 95 | const runLengthAndCode = stream.read(VariableIntBE); 96 | const runLength = runLengthAndCode >> 2; 97 | const code = runLengthAndCode & 0b11; 98 | 99 | let w; 100 | 101 | switch (code) { 102 | case 0: 103 | i += runLength; 104 | break; 105 | 106 | case 1: 107 | w = stream.read(Uint8); 108 | w = (w << 24) | (w << 16) | (w << 8) | w; 109 | if (withAlpha && w !== 0) { 110 | w |= 0xff000000; 111 | } 112 | for (let j = 0; j < runLength; j++) { 113 | result[i++] = w; 114 | } 115 | break; 116 | 117 | case 2: 118 | w = stream.read(Uint32BE); 119 | if (withAlpha && w !== 0) { 120 | w |= 0xff000000; 121 | } 122 | for (let j = 0; j < runLength; j++) { 123 | result[i++] = w; 124 | } 125 | break; 126 | 127 | case 3: 128 | for (let j = 0; j < runLength; j++) { 129 | w = stream.read(Uint32BE); 130 | if (withAlpha && w !== 0) { 131 | w |= 0xff000000; 132 | } 133 | result[i++] = w; 134 | } 135 | } 136 | } 137 | 138 | return result; 139 | } 140 | 141 | unpackPixels (words, width, height, depth, colormap) { 142 | const result = new Uint32Array(width * height); 143 | const mask = (1 << depth) - 1; 144 | const pixelsPerWord = 32 / depth; 145 | let dst = 0; 146 | 147 | let src = 0; 148 | for (let y = 0; y < height; y++) { 149 | let word; 150 | let shift = -1; 151 | for (let x = 0; x < width; x++) { 152 | if (shift < 0) { 153 | shift = depth * (pixelsPerWord - 1); 154 | word = words[src++]; 155 | } 156 | result[dst++] = colormap[(word >> shift) & mask]; 157 | shift -= depth; 158 | } 159 | } 160 | return result; 161 | } 162 | 163 | raster16To32 (words, width, height) { 164 | const result = new Uint32Array(2 * words.length); 165 | let shift; 166 | let word; 167 | let pix; 168 | let src = 0; 169 | let dst = 0; 170 | for (let y = 0; y < height; y++) { 171 | shift = -1; 172 | for (let x = 0; x < width; x++) { 173 | if (shift < 0) { 174 | shift = 16; 175 | word = words[src++]; 176 | } 177 | pix = (word >> shift) & 0xffff; 178 | if (pix !== 0) { 179 | const red = (pix >> 7) & 0b11111000; 180 | const green = (pix >> 2) & 0b11111000; 181 | const blue = (pix << 3) & 0b11111000; 182 | pix = 0xff000000 | (red << 16) | (green << 8) | blue; 183 | } 184 | result[dst++] = pix; 185 | shift -= 16; 186 | } 187 | } 188 | return result; 189 | } 190 | 191 | buildCustomColormap (depth, colors, table) { 192 | const result = new Uint32Array(1 << depth); 193 | for (let i = 0; i < colors.length; i++) { 194 | result[i] = table[colors[i].index - 1]; 195 | } 196 | return result; 197 | } 198 | } 199 | 200 | export {SqueakImage}; 201 | -------------------------------------------------------------------------------- /src/coders/squeak-sound.js: -------------------------------------------------------------------------------- 1 | import {assert} from '../util/assert'; 2 | 3 | import {Uint8} from './byte-primitives'; 4 | import {ByteStream} from './byte-stream'; 5 | 6 | const SQUEAK_SOUND_STEP_SIZE_TABLE = [ 7 | 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 8 | 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 9 | 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 10 | 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 11 | 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 12 | 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 13 | 27086, 29794, 32767 14 | ]; 15 | 16 | const SQUEAK_SOUND_INDEX_TABLES = { 17 | 2: [-1, 2, -1, 2], 18 | 3: [-1, -1, 2, 4, -1, -1, 2, 4], 19 | 4: [-1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8], 20 | 5: [ 21 | -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16, 22 | -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 23 | ] 24 | }; 25 | 26 | class SqueakSound { 27 | constructor (bitsPerSample) { 28 | this.bitsPerSample = bitsPerSample; 29 | 30 | this.indexTable = SQUEAK_SOUND_INDEX_TABLES[bitsPerSample]; 31 | 32 | this.signMask = 1 << (bitsPerSample - 1); 33 | this.valueMask = this.signMask - 1; 34 | this.valueHighBit = this.signMask >> 1; 35 | 36 | this.bitPosition = 0; 37 | this.currentByte = 0; 38 | 39 | this.stream = null; 40 | this.end = 0; 41 | } 42 | 43 | decode (data) { 44 | // Reset position information. 45 | this.bitPosition = 0; 46 | this.currentByte = 0; 47 | 48 | this.stream = new ByteStream(data.buffer, data.byteOffset); 49 | this.end = data.byteOffset + data.length; 50 | 51 | const size = Math.floor(data.length * 8 / this.bitsPerSample); 52 | const result = new Int16Array(size); 53 | 54 | let sample = 0; 55 | let index = 0; 56 | 57 | for (let i = 0; i < size; i++) { 58 | const code = this.nextCode(); 59 | 60 | assert(code >= 0, 'Ran out of bits in Squeak Sound'); 61 | 62 | let step = SQUEAK_SOUND_STEP_SIZE_TABLE[index]; 63 | let delta = 0; 64 | for (let bit = this.valueHighBit; bit > 0; bit = bit >> 1) { 65 | if ((code & bit) !== 0) { 66 | delta += step; 67 | } 68 | step = step >> 1; 69 | } 70 | delta += step; 71 | 72 | sample += ((code & this.signMask) === 0) ? delta : -delta; 73 | 74 | index += this.indexTable[code]; 75 | if (index < 0) index = 0; 76 | if (index > 88) index = 88; 77 | 78 | if (sample > 32767) sample = 32767; 79 | if (sample < -32768) sample = -32768; 80 | 81 | result[i] = sample; 82 | } 83 | 84 | return result; 85 | } 86 | 87 | nextCode () { 88 | let remaining = this.bitsPerSample; 89 | let shift = remaining - this.bitPosition; 90 | let result = (shift < 0) ? (this.currentByte >> -shift) : (this.currentByte << shift); 91 | while (shift > 0) { 92 | remaining -= this.bitPosition; 93 | if (this.end - this.stream.position > 0) { 94 | this.currentByte = this.stream.read(Uint8); 95 | this.bitPosition = 8; 96 | } else { 97 | this.currentByte = 0; 98 | this.bitPosition = 0; 99 | return -1; 100 | } 101 | shift = remaining - this.bitPosition; 102 | result += (shift < 0) ? (this.currentByte >> -shift) : (this.currentByte << shift); 103 | } 104 | this.bitPosition -= remaining; 105 | this.currentByte = this.currentByte & (0xff >> (8 - this.bitPosition)); 106 | return result; 107 | } 108 | 109 | static samples (bitsPerSample, data) { 110 | return data.length * 8 / bitsPerSample; 111 | } 112 | } 113 | 114 | export {SqueakSound}; 115 | -------------------------------------------------------------------------------- /src/coders/wav-file.js: -------------------------------------------------------------------------------- 1 | import {ByteStream} from './byte-stream'; 2 | import {WAVESignature, WAVEChunkStart, WAVEFMTChunkBody} from './wav-packets'; 3 | 4 | class WAVFile { 5 | encode (intSamples, {channels = 1, sampleRate = 22050} = {}) { 6 | const samplesUint8 = new Uint8Array(intSamples.buffer, intSamples.byteOffset, intSamples.byteLength); 7 | const size = ( 8 | WAVESignature.size + 9 | WAVEChunkStart.size + 10 | WAVEFMTChunkBody.size + 11 | WAVEChunkStart.size + 12 | samplesUint8.length 13 | ); 14 | 15 | const stream = new ByteStream(new ArrayBuffer(size)); 16 | 17 | stream.writeStruct(WAVESignature, { 18 | riff: 'RIFF', 19 | length: size - 8, 20 | wave: 'WAVE' 21 | }); 22 | 23 | stream.writeStruct(WAVEChunkStart, { 24 | chunkType: 'fmt ', 25 | length: WAVEFMTChunkBody.size 26 | }); 27 | 28 | stream.writeStruct(WAVEFMTChunkBody, { 29 | format: 1, 30 | channels: channels, 31 | sampleRate: sampleRate, 32 | bytesPerSec: sampleRate * 2 * channels, 33 | blockAlignment: channels * 2, 34 | bitsPerSample: 16 35 | }); 36 | 37 | stream.writeStruct(WAVEChunkStart, { 38 | chunkType: 'data', 39 | length: size - stream.position - WAVEChunkStart.size 40 | }); 41 | 42 | stream.writeBytes(samplesUint8); 43 | 44 | return stream.uint8a; 45 | } 46 | 47 | static encode (intSamples, options) { 48 | return new WAVFile().encode(intSamples, options); 49 | } 50 | 51 | static samples (bytes) { 52 | const headerLength = new WAVEChunkStart(bytes, WAVESignature.size).length; 53 | const bodyLength = new WAVEChunkStart(bytes, WAVESignature.size + WAVEChunkStart.size + headerLength).length; 54 | return bodyLength / 2; 55 | } 56 | } 57 | 58 | export {WAVFile}; 59 | -------------------------------------------------------------------------------- /src/coders/wav-packets.js: -------------------------------------------------------------------------------- 1 | import {Packet} from './byte-packets'; 2 | import {Uint16LE, Uint32LE, FixedAsciiString} from './byte-primitives'; 3 | 4 | class WAVESignature extends Packet.extend({ 5 | riff: new FixedAsciiString(4), 6 | length: Uint32LE, 7 | wave: new FixedAsciiString(4) 8 | }) {} 9 | 10 | Packet.initConstructor(WAVESignature); 11 | 12 | export {WAVESignature}; 13 | 14 | class WAVEChunkStart extends Packet.extend({ 15 | chunkType: new FixedAsciiString(4), 16 | length: Uint32LE 17 | }) {} 18 | 19 | Packet.initConstructor(WAVEChunkStart); 20 | 21 | export {WAVEChunkStart}; 22 | 23 | class WAVEFMTChunkBody extends Packet.extend({ 24 | format: Uint16LE, 25 | channels: Uint16LE, 26 | sampleRate: Uint32LE, 27 | bytesPerSec: Uint32LE, 28 | blockAlignment: Uint16LE, 29 | bitsPerSample: Uint16LE 30 | }) {} 31 | 32 | Packet.initConstructor(WAVEFMTChunkBody); 33 | 34 | export {WAVEFMTChunkBody}; 35 | -------------------------------------------------------------------------------- /src/playground/array.js: -------------------------------------------------------------------------------- 1 | import {assert} from '../util/assert'; 2 | 3 | class SB1ArrayAbstractView { 4 | constructor (array, start, end) { 5 | this.array = array instanceof SB1ArrayAbstractView ? array.array : array; 6 | this.start = start; 7 | this.end = end; 8 | } 9 | 10 | get length () { 11 | return this.end - this.start; 12 | } 13 | 14 | get name () { 15 | throw new Error('Not implemented'); 16 | } 17 | 18 | map (fn) { 19 | const out = []; 20 | for (let i = this.start; i < this.end; i++) { 21 | out.push(fn(this.array[i], i, this)); 22 | } 23 | return out; 24 | } 25 | } 26 | 27 | class SB1ArrayFullView extends SB1ArrayAbstractView { 28 | constructor (array) { 29 | super(array, array.start || 0, array.end || array.length); 30 | } 31 | 32 | get name () { 33 | return 'all'; 34 | } 35 | } 36 | 37 | class SB1ArraySubView extends SB1ArrayAbstractView { 38 | get name () { 39 | return `${this.start + 1} - ${this.end}`; 40 | } 41 | 42 | static views (array) { 43 | if (array instanceof SB1ArrayFullView) { 44 | return array; 45 | } 46 | if (array.length > 100) { 47 | const scale = Math.pow(10, Math.ceil(Math.log(array.length) / Math.log(10))); 48 | const increment = scale / 10; 49 | 50 | const views = []; 51 | for (let i = (array.start || 0); i < (array.end || array.length); i += increment) { 52 | views.push(new SB1ArraySubView(array, i, Math.min(i + increment, array.end || array.length))); 53 | assert(views.length <= 10, 'Too many subviews'); 54 | } 55 | views.push(new SB1ArrayFullView(array)); 56 | return views; 57 | } 58 | return array; 59 | } 60 | } 61 | 62 | class ArrayRenderer { 63 | static check (data) { 64 | return Array.isArray(data) || data instanceof SB1ArrayAbstractView; 65 | } 66 | 67 | render (data, view) { 68 | if (data.length) view.renderArrow(); 69 | view.renderTitle(`Array (${data.length})`); 70 | if (data.length) { 71 | view.renderExpand(() => ( 72 | SB1ArraySubView.views(data) 73 | .map((field, index) => ( 74 | view.child( 75 | field, 76 | field instanceof SB1ArrayAbstractView ? field.name : index + 1, `[${index}]` 77 | ) 78 | )) 79 | )); 80 | } 81 | } 82 | } 83 | 84 | export {ArrayRenderer}; 85 | -------------------------------------------------------------------------------- /src/playground/field-object.js: -------------------------------------------------------------------------------- 1 | import {PNGFile} from '../coders/png-file'; 2 | import {WAVFile} from '../coders/wav-file'; 3 | 4 | import {FieldObject} from '../squeak/field-object'; 5 | 6 | import {ObjectRenderer} from './object'; 7 | 8 | const allPropertyDescriptors = prototype => { 9 | if (prototype === null) return {}; 10 | return Object.assign( 11 | allPropertyDescriptors(Object.getPrototypeOf(prototype)), 12 | Object.getOwnPropertyDescriptors(prototype) 13 | ); 14 | }; 15 | 16 | class FieldObjectRenderer { 17 | static check (data) { 18 | return data instanceof FieldObject; 19 | } 20 | 21 | addOptionalPreview (obj) { 22 | if (obj.decoded) { 23 | let mime; 24 | let tag; 25 | let encoded; 26 | if (obj.extension === 'uncompressed') { 27 | mime = 'image/png'; 28 | tag = new Image(); 29 | encoded = new Uint8Array(PNGFile.encode( 30 | obj.width, 31 | obj.height, 32 | obj.decoded 33 | )); 34 | } else if (obj.extension === 'jpg') { 35 | mime = 'image/jpg'; 36 | tag = new Image(); 37 | encoded = obj.decoded; 38 | } else if (obj.extension === 'pcm') { 39 | mime = 'audio/wav'; 40 | tag = new Audio(); 41 | tag.controls = true; 42 | encoded = new Uint8Array(WAVFile.encode(obj.decoded, { 43 | sampleRate: obj.rate && obj.rate.value 44 | })); 45 | } 46 | 47 | tag.src = URL.createObjectURL(new Blob([encoded.buffer], {type: mime})); 48 | 49 | obj.preview = tag; 50 | } 51 | return obj; 52 | } 53 | 54 | render (data, view) { 55 | new ObjectRenderer().render( 56 | Object.assign(() => this.addOptionalPreview( 57 | Object.entries( 58 | allPropertyDescriptors(Object.getPrototypeOf(data)) 59 | ) 60 | .filter(([, desc]) => desc.get) 61 | .reduce((carry, [key]) => { 62 | Object.defineProperty(carry, key, { 63 | enumerable: true, 64 | get () { 65 | return data[key]; 66 | } 67 | }); 68 | return carry; 69 | }, {}) 70 | ), { 71 | toString () { 72 | return data.toString(); 73 | } 74 | }), 75 | view 76 | ); 77 | } 78 | } 79 | 80 | export {FieldObjectRenderer}; 81 | -------------------------------------------------------------------------------- /src/playground/field.js: -------------------------------------------------------------------------------- 1 | import {Field, Header, Reference, Value} from '../squeak/fields'; 2 | import {TYPES, TYPE_NAMES} from '../squeak/ids'; 3 | 4 | class FieldRenderer { 5 | static check (data) { 6 | return data instanceof Field; 7 | } 8 | 9 | render (data, view) { 10 | if (data instanceof Reference) { 11 | view.renderTitle(`Reference { index: ${data.index} }`); 12 | } else if (data instanceof Header) { 13 | view.renderTitle(`Header { classId: ${data.classId} (${TYPE_NAMES[data.classId]}), size: ${data.size} }`); 14 | } else if ((data instanceof Value) && ( 15 | data.classId === TYPES.COLOR || 16 | data.classId === TYPES.TRANSLUCENT_COLOR 17 | )) { 18 | view.renderTitle((+data).toString(16).padStart(8, '0')).style.fontFamily = 'monospace'; 19 | } else if (data instanceof Value) { 20 | if (data.value && data.value.buffer) { 21 | view.renderTitle(`${data.value.constructor.name} (${data.value.length})`); 22 | } else { 23 | view.renderTitle(String(data)); 24 | } 25 | } 26 | } 27 | } 28 | 29 | export {FieldRenderer}; 30 | -------------------------------------------------------------------------------- /src/playground/index.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/playground/index.js: -------------------------------------------------------------------------------- 1 | import {SB1File} from '../..'; 2 | import {SB1View} from './view'; 3 | 4 | import {ArrayRenderer} from './array'; 5 | import {FieldObjectRenderer} from './field-object'; 6 | import {FieldRenderer} from './field'; 7 | import {JSPrimitiveRenderer} from './js-primitive'; 8 | import {ObjectRenderer} from './object'; 9 | import {ViewableRenderer} from './viewable'; 10 | 11 | SB1View.register(ArrayRenderer); 12 | SB1View.register(FieldObjectRenderer); 13 | SB1View.register(FieldRenderer); 14 | SB1View.register(JSPrimitiveRenderer); 15 | SB1View.register(ObjectRenderer); 16 | SB1View.register(ViewableRenderer); 17 | 18 | const createDownload = (name, mime, content) => { 19 | const anchor = document.createElement('a'); 20 | anchor.download = name; 21 | anchor.href = URL.createObjectURL(new Blob([content], {type: mime})); 22 | anchor.innerText = name; 23 | return anchor; 24 | }; 25 | 26 | let last = null; 27 | const readFile = f => { 28 | const reader = new FileReader(); 29 | reader.onload = function (event) { 30 | if (last) { 31 | last.forEach(document.body.removeChild, document.body); 32 | } 33 | const sb1 = new SB1File(event.target.result); 34 | last = [ 35 | new SB1View(sb1, 'file').element, 36 | new SB1View(Array.from(sb1.infoRaw()), 'raw - info').element, 37 | new SB1View(Array.from(sb1.dataRaw()), 'raw - data').element, 38 | new SB1View(Array.from(sb1.infoTable()), 'table - info').element, 39 | new SB1View(Array.from(sb1.dataTable()), 'table - data').element, 40 | new SB1View(sb1.info(), 'info').element, 41 | new SB1View(sb1.data(), 'data').element, 42 | new SB1View(sb1.images(), 'images').element, 43 | new SB1View(sb1.sounds(), 'sounds').element, 44 | new SB1View(sb1.json, 'json').element, 45 | createDownload(`${f.name}.json`, 'application/json', JSON.stringify(sb1.json)) 46 | ]; 47 | last.forEach(document.body.appendChild, document.body); 48 | }; 49 | reader.readAsArrayBuffer(f); 50 | }; 51 | 52 | Array.from(document.getElementsByClassName('file')).forEach(el => { 53 | el.addEventListener('change', () => { 54 | Array.from(el.files).forEach(readFile); 55 | }); 56 | }); 57 | 58 | document.body.addEventListener('drop', e => { 59 | e.preventDefault(); 60 | e.dataTransfer.dropEffect = 'copy'; 61 | document.getElementsByClassName('file')[0].files = e.dataTransfer.files; 62 | }); 63 | 64 | document.body.addEventListener('dragover', e => { 65 | e.preventDefault(); 66 | e.dataTransfer.dropEffect = 'copy'; 67 | }); 68 | -------------------------------------------------------------------------------- /src/playground/js-primitive.js: -------------------------------------------------------------------------------- 1 | const PRIMITIVE_TYPEOFS = ['undefined', 'string', 'number', 'boolean']; 2 | 3 | class JSPrimitiveRenderer { 4 | static check (data) { 5 | return PRIMITIVE_TYPEOFS.includes(typeof data) || data === null; 6 | } 7 | 8 | render (data, view) { 9 | view.renderTitle(String(data)); 10 | } 11 | } 12 | 13 | export {JSPrimitiveRenderer}; 14 | -------------------------------------------------------------------------------- /src/playground/object.js: -------------------------------------------------------------------------------- 1 | const log = require('../util/log'); 2 | 3 | class ObjectRenderer { 4 | static check (data) { 5 | return data && data.constructor === Object; 6 | } 7 | 8 | render (dataOrFn, view) { 9 | view.renderArrow(); 10 | view.renderTitle(String(dataOrFn) === '[object Object]' ? 'Object' : String(dataOrFn)); 11 | view.renderExpand(() => { 12 | const data = typeof dataOrFn === 'function' ? dataOrFn() : dataOrFn; 13 | return Object.keys(data) 14 | .map(key => { 15 | try { 16 | if (typeof data[key] === 'function') return null; 17 | return view.child(data[key], key, `.${key}`); 18 | } catch (err) { 19 | log.error(err); 20 | return view.child('An error occured rendering view data.', key, `.${key}`); 21 | } 22 | }) 23 | .filter(Boolean); 24 | }); 25 | } 26 | } 27 | 28 | export {ObjectRenderer}; 29 | -------------------------------------------------------------------------------- /src/playground/view.js: -------------------------------------------------------------------------------- 1 | const log = require('../util/log'); 2 | 3 | const _expanded = {}; 4 | 5 | const _registry = []; 6 | 7 | class DefaultRenderer { 8 | static check () { 9 | return true; 10 | } 11 | 12 | render (data, view) { 13 | if (data instanceof HTMLElement) { 14 | view.content.appendChild(data); 15 | } else { 16 | view.renderTitle(`Unknown Structure(${data ? data.classId || data.constructor.name : ''})`); 17 | } 18 | } 19 | } 20 | 21 | class SB1View { 22 | constructor (data, prefix = '', path = prefix) { 23 | this._elements = {}; 24 | 25 | this.element = document.createElement('div'); 26 | this.element.style.position = 'relative'; 27 | this.element.style.top = '0'; 28 | this.element.style.left = '0'; 29 | // this.element.style.overflow = 'hidden'; 30 | 31 | this.content = this.element; 32 | 33 | this.data = data; 34 | this.prefix = prefix; 35 | this.path = path; 36 | this.expanded = !!_expanded[this.path]; 37 | this.canExpand = false; 38 | 39 | this.toggle = this.toggle.bind(this); 40 | 41 | this.element.addEventListener('click', this.toggle); 42 | 43 | this.renderer = SB1View.createRenderer(this.data, this); 44 | 45 | this.render(); 46 | } 47 | 48 | toggle (event) { 49 | if (!this.canExpand) return; 50 | 51 | if (event.target !== this._elements.arrow && event.target !== this._elements.title) return; 52 | 53 | _expanded[this.path] = this.expanded = !this.expanded; 54 | this.render(); 55 | 56 | event.preventDefault(); 57 | event.stopPropagation(); 58 | return false; 59 | } 60 | 61 | createElement (type, name) { 62 | if (!this._elements[name]) { 63 | this._elements[name] = document.createElement(type); 64 | } 65 | this._elements[name].innerHTML = ''; 66 | return this._elements[name]; 67 | } 68 | 69 | child (value, key, path) { 70 | return new SB1View(value, key, `${this.path}${path}`); 71 | } 72 | 73 | renderClear () { 74 | this.canExpand = false; 75 | while (this.element.children.length) { 76 | this.element.removeChild(this.element.children[0]); 77 | } 78 | this.content = this.element; 79 | } 80 | 81 | renderArrow () { 82 | this.canExpand = true; 83 | const arrowDiv = this.createElement('div', 'arrow'); 84 | arrowDiv.innerHTML = '▶'; 85 | arrowDiv.style.position = 'absolute'; 86 | arrowDiv.style.left = '0'; 87 | arrowDiv.style.width = '1em'; 88 | arrowDiv.style.transform = this.expanded ? 'rotateZ(90deg)' : ''; 89 | arrowDiv.style.transition = 'transform 3s'; 90 | this.element.appendChild(arrowDiv); 91 | 92 | const contentDiv = this.createElement('div', 'arrowContent'); 93 | contentDiv.style.position = 'relative'; 94 | contentDiv.style.left = '1em'; 95 | contentDiv.style.right = '0'; 96 | this.element.appendChild(contentDiv); 97 | this.content = contentDiv; 98 | } 99 | 100 | renderTitle (title) { 101 | const titleDiv = this.createElement('div', 'title'); 102 | const fullTitle = (this.prefix ? `${this.prefix}: ` : '') + title; 103 | if (['\n', '\r', '
'].some(str => fullTitle.indexOf(str) !== -1) || fullTitle.length > 80) { 104 | this.renderArrow(); 105 | if (this.expanded) { 106 | titleDiv.innerText = fullTitle; 107 | } else { 108 | const maxLength = Math.min( 109 | fullTitle.lastIndexOf(' ', 80), 110 | ['\n', '\r', '
'].reduce((value, str) => { 111 | if (fullTitle.indexOf(str) !== -1) { 112 | return Math.min(value, fullTitle.indexOf(str)); 113 | } 114 | return value; 115 | }, Infinity) 116 | ); 117 | titleDiv.innerText = `${fullTitle.substring(0, maxLength)} ...`; 118 | } 119 | } else { 120 | titleDiv.innerText = fullTitle; 121 | } 122 | this.content.appendChild(titleDiv); 123 | return titleDiv; 124 | } 125 | 126 | expand (fn, elsefn) { 127 | if (this.expanded) { 128 | elsefn(); 129 | } else { 130 | fn(); 131 | } 132 | } 133 | 134 | renderExpand (fn) { 135 | if (this.expanded) { 136 | try { 137 | const div = this.createElement('div', 'expanded'); 138 | fn.call(this, div) 139 | .forEach(view => this.content.appendChild(view.element)); 140 | } catch (error) { 141 | log.error(error); 142 | const divError = this.createElement('div', 'expanded-error'); 143 | divError.innerText = 'Error rendering expanded area ...'; 144 | this.content.appendChild(divError); 145 | } 146 | } 147 | } 148 | 149 | render () { 150 | this.renderClear(); 151 | this.renderer.render(this.data, this); 152 | } 153 | 154 | static register (Class) { 155 | _registry.push([Class.check, Class]); 156 | } 157 | 158 | static findRenderer (data, view) { 159 | return _registry.reduce((carry, [check, Class]) => { 160 | if (check(data, view)) return Class; 161 | return carry; 162 | }, DefaultRenderer); 163 | } 164 | 165 | static createRenderer (data, view) { 166 | const Renderer = SB1View.findRenderer(data, view); 167 | return new Renderer(view); 168 | } 169 | } 170 | 171 | export {SB1View}; 172 | -------------------------------------------------------------------------------- /src/playground/viewable.js: -------------------------------------------------------------------------------- 1 | import {ObjectRenderer} from './object'; 2 | 3 | class ViewableRenderer { 4 | static check (data) { 5 | return data && typeof data.view === 'function'; 6 | } 7 | 8 | render (data, view) { 9 | new ObjectRenderer().render(Object.assign(() => data.view(), { 10 | toString () { 11 | return data.constructor.name; 12 | } 13 | }), view); 14 | } 15 | } 16 | 17 | export {ViewableRenderer}; 18 | -------------------------------------------------------------------------------- /src/sb1-file-packets.js: -------------------------------------------------------------------------------- 1 | import {assert} from './util/assert'; 2 | 3 | import {Packet} from './coders/byte-packets'; 4 | import {FixedAsciiString, Uint8, Uint32BE} from './coders/byte-primitives'; 5 | 6 | /** 7 | * @augments Packet 8 | */ 9 | class SB1Signature extends Packet.extend({ 10 | /** 11 | * 10 byte ascii string equaling `'ScratchV01'` or `'ScratchV02'`. 12 | * @type {string} 13 | * @memberof SB1Signature# 14 | */ 15 | version: new FixedAsciiString(10), 16 | 17 | /** 18 | * Number of bytes in the info block. 19 | * @type {number} 20 | * @memberof SB1Signature# 21 | */ 22 | infoByteLength: Uint32BE 23 | }) { 24 | /** 25 | * Is this a valid SB1Signature? 26 | * @method 27 | * @throws {AssertionError} Throws if it is not valid. 28 | */ 29 | validate () { 30 | assert.validate( 31 | this.equals({version: 'ScratchV01'}) || 32 | this.equals({version: 'ScratchV02'}), 33 | 'Invalid Scratch file signature.' 34 | ); 35 | } 36 | } 37 | 38 | Packet.initConstructor(SB1Signature); 39 | 40 | class SB1Header extends Packet.extend({ 41 | ObjS: new FixedAsciiString(4), 42 | ObjSValue: Uint8, 43 | Stch: new FixedAsciiString(4), 44 | StchValue: Uint8, 45 | numObjects: Uint32BE 46 | }) { 47 | validate () { 48 | assert.validate( 49 | this.equals({ 50 | ObjS: 'ObjS', 51 | ObjSValue: 1, 52 | Stch: 'Stch', 53 | StchValue: 1 54 | }), 55 | 'Invalid Scratch file info packet header.' 56 | ); 57 | } 58 | } 59 | 60 | Packet.initConstructor(SB1Header); 61 | 62 | export {SB1Signature, SB1Header}; 63 | -------------------------------------------------------------------------------- /src/sb1-file.js: -------------------------------------------------------------------------------- 1 | import {ByteStream} from './coders/byte-stream'; 2 | 3 | import {ByteTakeIterator} from './squeak/byte-take-iterator'; 4 | import {FieldIterator} from './squeak/field-iterator'; 5 | import {TypeIterator} from './squeak/type-iterator'; 6 | import {ReferenceFixer} from './squeak/reference-fixer'; 7 | import {ImageMediaData, SoundMediaData} from './squeak/types'; 8 | 9 | import {toSb2FakeZipApi} from './to-sb2/fake-zip'; 10 | import {toSb2Json} from './to-sb2/json-generator'; 11 | 12 | import {SB1Header, SB1Signature} from './sb1-file-packets'; 13 | 14 | class SB1File { 15 | constructor (buffer) { 16 | this.buffer = buffer; 17 | this.stream = new ByteStream(buffer); 18 | 19 | this.signature = this.stream.readStruct(SB1Signature); 20 | this.signature.validate(); 21 | 22 | this.infoHeader = this.stream.readStruct(SB1Header); 23 | this.infoHeader.validate(); 24 | 25 | this.stream.position += this.signature.infoByteLength - SB1Header.size; 26 | 27 | this.dataHeader = this.stream.readStruct(SB1Header); 28 | this.dataHeader.validate(); 29 | } 30 | 31 | get json () { 32 | return toSb2Json({ 33 | info: this.info(), 34 | stageData: this.data(), 35 | images: this.images(), 36 | sounds: this.sounds() 37 | }); 38 | } 39 | 40 | get zip () { 41 | return toSb2FakeZipApi({ 42 | // Use of this `zip` getter assumes that `json` will be used to 43 | // fetch the json and not have it read from the produced "fake" zip. 44 | images: this.images(), 45 | sounds: this.sounds() 46 | }); 47 | } 48 | 49 | view () { 50 | return { 51 | signature: this.signature, 52 | infoHeader: this.infoHeader, 53 | dataHeader: this.dataHeader, 54 | toString () { 55 | return 'SB1File'; 56 | } 57 | }; 58 | } 59 | 60 | infoRaw () { 61 | return new ByteTakeIterator( 62 | new FieldIterator(this.buffer, this.infoHeader.offset + SB1Header.size), 63 | this.signature.infoByteLength + SB1Signature.size 64 | ); 65 | } 66 | 67 | infoTable () { 68 | return new TypeIterator(this.infoRaw()); 69 | } 70 | 71 | info () { 72 | if (!this._info) { 73 | this._info = new ReferenceFixer(this.infoTable()).table[0]; 74 | } 75 | return this._info; 76 | } 77 | 78 | dataRaw () { 79 | return new ByteTakeIterator( 80 | new FieldIterator(this.buffer, this.dataHeader.offset + SB1Header.size), 81 | this.stream.uint8a.length 82 | ); 83 | } 84 | 85 | dataTable () { 86 | return new TypeIterator(this.dataRaw()); 87 | } 88 | 89 | dataFixed () { 90 | if (!this._data) { 91 | this._data = new ReferenceFixer(this.dataTable()).table; 92 | } 93 | return this._data; 94 | } 95 | 96 | data () { 97 | return this.dataFixed()[0]; 98 | } 99 | 100 | images () { 101 | const unique = new Set(); 102 | return this.dataFixed().filter(obj => { 103 | if (obj instanceof ImageMediaData) { 104 | if (unique.has(obj.crc)) return false; 105 | unique.add(obj.crc); 106 | return true; 107 | } 108 | return false; 109 | }); 110 | } 111 | 112 | sounds () { 113 | const unique = new Set(); 114 | return this.dataFixed().filter(obj => { 115 | if (obj instanceof SoundMediaData) { 116 | if (unique.has(obj.crc)) return false; 117 | unique.add(obj.crc); 118 | return true; 119 | } 120 | return false; 121 | }); 122 | } 123 | } 124 | 125 | export {SB1File}; 126 | -------------------------------------------------------------------------------- /src/squeak/byte-primitives.js: -------------------------------------------------------------------------------- 1 | import {TextDecoder as JSTextDecoder} from 'text-encoding'; 2 | 3 | import {assert} from '../util/assert'; 4 | 5 | import {IS_HOST_LITTLE_ENDIAN, Int16BE, BytePrimitive, Uint8, Uint32BE} from '../coders/byte-primitives'; 6 | 7 | const BUFFER_TOO_BIG = 10 * 1024 * 1024; 8 | 9 | /** 10 | * @const ReferenceBE 11 | * @type BytePrimitive 12 | */ 13 | let ReferenceBE; 14 | if (IS_HOST_LITTLE_ENDIAN) { 15 | ReferenceBE = new BytePrimitive({ 16 | size: 3, 17 | read (uint8a, position) { 18 | return ( 19 | (uint8a[position + 0] << 16) | 20 | (uint8a[position + 1] << 8) | 21 | uint8a[position + 2] 22 | ); 23 | } 24 | }); 25 | } else { 26 | ReferenceBE = new BytePrimitive({ 27 | size: 3, 28 | read (uint8a, position) { 29 | return ( 30 | (uint8a[position + 2] << 16) | 31 | (uint8a[position + 1] << 8) | 32 | uint8a[position + 0] 33 | ); 34 | } 35 | }); 36 | } 37 | 38 | /** 39 | * @const LargeInt 40 | * @type BytePrimitive 41 | */ 42 | const LargeInt = new BytePrimitive({ 43 | sizeOf (uint8a, position) { 44 | const count = Int16BE.read(uint8a, position); 45 | return Int16BE.size + count; 46 | }, 47 | read (uint8a, position) { 48 | let num = 0; 49 | let multiplier = 0; 50 | const count = Int16BE.read(uint8a, position); 51 | for (let i = 0; i < count; i++) { 52 | num = num + (multiplier * Uint8.read(uint8a, position++)); 53 | multiplier *= 256; 54 | } 55 | return num; 56 | } 57 | }); 58 | 59 | /** 60 | * @const AsciiString 61 | * @type BytePrimitive 62 | */ 63 | const AsciiString = new BytePrimitive({ 64 | sizeOf (uint8a, position) { 65 | const count = Uint32BE.read(uint8a, position); 66 | return Uint32BE.size + count; 67 | }, 68 | read (uint8a, position) { 69 | const count = Uint32BE.read(uint8a, position); 70 | assert(count < BUFFER_TOO_BIG, 'asciiString too big'); 71 | position += 4; 72 | let str = ''; 73 | for (let i = 0; i < count; i++) { 74 | str += String.fromCharCode(uint8a[position++]); 75 | } 76 | return str; 77 | } 78 | }); 79 | 80 | /** 81 | * @const Bytes 82 | * @type BytePrimitive 83 | */ 84 | const Bytes = new BytePrimitive({ 85 | sizeOf (uint8a, position) { 86 | return Uint32BE.size + Uint32BE.read(uint8a, position); 87 | }, 88 | read (uint8a, position) { 89 | const count = Uint32BE.read(uint8a, position); 90 | assert(count < BUFFER_TOO_BIG, 'bytes too big'); 91 | position += Uint32BE.size; 92 | 93 | assert(count < BUFFER_TOO_BIG, 'uint8a array too big'); 94 | return new Uint8Array(uint8a.buffer, position, count); 95 | } 96 | }); 97 | 98 | /** 99 | * @const SoundBytes 100 | * @type BytePrimitive 101 | */ 102 | const SoundBytes = new BytePrimitive({ 103 | sizeOf (uint8a, position) { 104 | return Uint32BE.size + (Uint32BE.read(uint8a, position) * 2); 105 | }, 106 | read (uint8a, position) { 107 | const samples = Uint32BE.read(uint8a, position); 108 | assert(samples < BUFFER_TOO_BIG, 'sound too big'); 109 | position += Uint32BE.size; 110 | 111 | const count = samples * 2; 112 | assert(count < BUFFER_TOO_BIG, 'uint8a array too big'); 113 | return new Uint8Array(uint8a.buffer, position, count); 114 | } 115 | }); 116 | 117 | /** 118 | * @const Bitmap32BE 119 | * @type BytePrimitive 120 | */ 121 | const Bitmap32BE = new BytePrimitive({ 122 | sizeOf (uint8a, position) { 123 | return Uint32BE.size + (Uint32BE.read(uint8a, position) * Uint32BE.size); 124 | }, 125 | read (uint8a, position) { 126 | const count = Uint32BE.read(uint8a, position); 127 | assert(count < BUFFER_TOO_BIG, 'bitmap too big'); 128 | position += Uint32BE.size; 129 | 130 | assert(count < BUFFER_TOO_BIG, 'uint8a array too big'); 131 | const value = new Uint32Array(count); 132 | for (let i = 0; i < count; i++) { 133 | value[i] = Uint32BE.read(uint8a, position); 134 | position += Uint32BE.size; 135 | } 136 | return value; 137 | } 138 | }); 139 | 140 | let decoder; 141 | if (typeof TextDecoder === 'undefined') { 142 | decoder = new JSTextDecoder(); 143 | } else { 144 | decoder = new TextDecoder(); 145 | } 146 | 147 | /** 148 | * @const UTF8 149 | * @type BytePrimitive 150 | */ 151 | const UTF8 = new BytePrimitive({ 152 | sizeOf (uint8a, position) { 153 | return Uint32BE.size + Uint32BE.read(uint8a, position); 154 | }, 155 | read (uint8a, position) { 156 | const count = Uint32BE.read(uint8a, position); 157 | assert(count < BUFFER_TOO_BIG, 'utf8 too big'); 158 | position += Uint32BE.size; 159 | 160 | assert(count < BUFFER_TOO_BIG, 'uint8a array too big'); 161 | return decoder.decode(new Uint8Array(uint8a.buffer, position, count)); 162 | } 163 | }); 164 | 165 | /** 166 | * @const OpaqueColor 167 | * @type BytePrimitive 168 | */ 169 | const OpaqueColor = new BytePrimitive({ 170 | size: 4, 171 | read (uint8a, position) { 172 | const rgb = Uint32BE.read(uint8a, position); 173 | const a = 0xff; 174 | const r = (rgb >> 22) & 0xff; 175 | const g = (rgb >> 12) & 0xff; 176 | const b = (rgb >> 2) & 0xff; 177 | return ((a << 24) | (r << 16) | (g << 8) | b) >>> 0; 178 | } 179 | }); 180 | 181 | /** 182 | * @const TranslucentColor 183 | * @type BytePrimitive 184 | */ 185 | const TranslucentColor = new BytePrimitive({ 186 | size: 5, 187 | read (uint8a, position) { 188 | const rgb = Uint32BE.read(uint8a, position); 189 | const a = Uint8.read(uint8a, position); 190 | const r = (rgb >> 22) & 0xff; 191 | const g = (rgb >> 12) & 0xff; 192 | const b = (rgb >> 2) & 0xff; 193 | return ((a << 24) | (r << 16) | (g << 8) | b) >>> 0; 194 | } 195 | }); 196 | 197 | export { 198 | BUFFER_TOO_BIG, 199 | ReferenceBE, 200 | LargeInt, 201 | AsciiString, 202 | Bytes, 203 | SoundBytes, 204 | Bitmap32BE, 205 | UTF8, 206 | OpaqueColor, 207 | TranslucentColor 208 | }; 209 | -------------------------------------------------------------------------------- /src/squeak/byte-take-iterator.js: -------------------------------------------------------------------------------- 1 | /** 2 | * An iterator that only takes bytes up to a certain position. 3 | * 4 | * Take iterators constrain the number of times an inner iterator can return 5 | * values. Normally it constrains the number of returned values. 6 | * ByteTakeIterator instead constrains the number of bytes the inner iterator 7 | * may take from its stream before ByteTakeIterator returns done objects. 8 | * 9 | * Primarily used to wrap {@link FieldIterator}. 10 | */ 11 | class ByteTakeIterator { 12 | /** 13 | * @param {{stream: ByteStream}} iter - Iterator with `stream` member. 14 | * @param {number} [maxPosition=Infinity] - Position `stream` may not go 15 | * beyond when yielding the next value. 16 | */ 17 | constructor (iter, maxPosition = Infinity) { 18 | this.iter = iter; 19 | this.maxPosition = maxPosition; 20 | } 21 | 22 | /** 23 | * @returns {ByteTakeIterator} - Returns itself. 24 | */ 25 | [Symbol.iterator] () { 26 | return this; 27 | } 28 | 29 | /** 30 | * @returns {{value: *, done: boolean}} - Return the next value or indicate 31 | * the Iterator has reached its end. 32 | */ 33 | next () { 34 | if (this.iter.stream.position >= this.maxPosition) { 35 | return { 36 | value: null, 37 | done: true 38 | }; 39 | } 40 | 41 | return this.iter.next(); 42 | } 43 | } 44 | 45 | export {ByteTakeIterator}; 46 | -------------------------------------------------------------------------------- /src/squeak/field-iterator.js: -------------------------------------------------------------------------------- 1 | import {Uint8, Int16BE, Int32BE, DoubleBE} from '../coders/byte-primitives'; 2 | import {ByteStream} from '../coders/byte-stream'; 3 | 4 | import { 5 | ReferenceBE, LargeInt, AsciiString, UTF8, Bytes, SoundBytes, Bitmap32BE, OpaqueColor, TranslucentColor 6 | } from './byte-primitives'; 7 | import {BuiltinObjectHeader, FieldObjectHeader, Header, Reference, Value} from './fields'; 8 | import {TYPES} from './ids'; 9 | 10 | /** 11 | * Consume values for the byte stream with a iterator-like interface. 12 | */ 13 | class Consumer { 14 | /** 15 | * @param {object} options - Define the consumer. 16 | * @param {function} [options.type=Value] - The {@link Field} type to 17 | * create. 18 | * @param {BytePrimitive} options.read - How to read the third Field 19 | * argument. The third field argument is the value the field represented in 20 | * the `.sb` file. It is either the Value's value, the Reference's index, 21 | * or the Header's field size. 22 | * @param {function} [options.value] - How to produce the third Field 23 | * argument from a stream. Defaults to `stream => 24 | * stream.read(options.read)`. 25 | */ 26 | constructor ({ 27 | type = Value, 28 | read, 29 | value = read ? (stream => stream.read(read)) : null 30 | }) { 31 | this.type = type; 32 | this.value = value; 33 | } 34 | 35 | /** 36 | * @param {ByteStream} stream - Stream to read from. 37 | * @param {TYPES} classId - FieldObject TYPES identifying the value to read. 38 | * @param {number} position - Position in the stream the classId was read 39 | * from. 40 | * @returns {{value: *, done: boolean}} - An iterator.next() return value. 41 | */ 42 | next (stream, classId, position) { 43 | return { 44 | value: new this.type(classId, position, this.value(stream)), 45 | done: false 46 | }; 47 | } 48 | } 49 | 50 | /** 51 | * @const CONSUMER_PROTOS 52 | * @type {Object.} 53 | */ 54 | const CONSUMER_PROTOS = { 55 | [TYPES.NULL]: {value: () => null}, 56 | [TYPES.TRUE]: {value: () => true}, 57 | [TYPES.FALSE]: {value: () => false}, 58 | [TYPES.SMALL_INT]: {read: Int32BE}, 59 | [TYPES.SMALL_INT_16]: {read: Int16BE}, 60 | [TYPES.LARGE_INT_POSITIVE]: {read: LargeInt}, 61 | [TYPES.LARGE_INT_NEGATIVE]: {read: LargeInt}, 62 | [TYPES.FLOATING]: {read: DoubleBE}, 63 | [TYPES.STRING]: {read: AsciiString}, 64 | [TYPES.SYMBOL]: {read: AsciiString}, 65 | [TYPES.BYTES]: {read: Bytes}, 66 | [TYPES.SOUND]: {read: SoundBytes}, 67 | [TYPES.BITMAP]: {read: Bitmap32BE}, 68 | [TYPES.UTF8]: {read: UTF8}, 69 | [TYPES.ARRAY]: {type: Header, read: Int32BE}, 70 | [TYPES.ORDERED_COLLECTION]: {type: Header, read: Int32BE}, 71 | [TYPES.SET]: {type: Header, read: Int32BE}, 72 | [TYPES.IDENTITY_SET]: {type: Header, read: Int32BE}, 73 | [TYPES.DICTIONARY]: { 74 | type: Header, 75 | value: stream => stream.read(Int32BE) * 2 76 | }, 77 | [TYPES.IDENTITY_DICTIONARY]: { 78 | type: Header, 79 | value: stream => stream.read(Int32BE) * 2 80 | }, 81 | [TYPES.COLOR]: {read: OpaqueColor}, 82 | [TYPES.TRANSLUCENT_COLOR]: {read: TranslucentColor}, 83 | [TYPES.POINT]: {type: Header, value: () => 2}, 84 | [TYPES.RECTANGLE]: {type: Header, value: () => 4}, 85 | [TYPES.FORM]: {type: Header, value: () => 5}, 86 | [TYPES.SQUEAK]: {type: Header, value: () => 6}, 87 | [TYPES.OBJECT_REF]: {type: Reference, read: ReferenceBE} 88 | }; 89 | 90 | /** 91 | * @const CONSUMERS 92 | * @type {Array.} 93 | */ 94 | const CONSUMERS = Array.from( 95 | {length: 256}, 96 | (_, i) => { 97 | if (CONSUMER_PROTOS[i]) return new Consumer(CONSUMER_PROTOS[i]); 98 | return null; 99 | } 100 | ); 101 | 102 | const builtinConsumer = new Consumer({ 103 | type: BuiltinObjectHeader, 104 | value: () => null 105 | }); 106 | 107 | /** 108 | * Field iterator. 109 | */ 110 | class FieldIterator { 111 | /** 112 | * @param {ArrayBuffer} buffer - Buffer to read from. 113 | * @param {number} position - Position in buffer to start at. 114 | */ 115 | constructor (buffer, position) { 116 | this.buffer = buffer; 117 | this.stream = new ByteStream(buffer, position); 118 | } 119 | 120 | /** 121 | * @returns {FieldIterator} - Returns this. 122 | */ 123 | [Symbol.iterator] () { 124 | return this; 125 | } 126 | 127 | /** 128 | * @returns {{value: *, done: boolean}} - An iterator.next() value. 129 | */ 130 | next () { 131 | if (this.stream.position >= this.stream.uint8a.length) { 132 | return { 133 | value: null, 134 | done: true 135 | }; 136 | } 137 | 138 | const position = this.stream.position; 139 | const classId = this.stream.read(Uint8); 140 | 141 | const consumer = CONSUMERS[classId]; 142 | 143 | if (consumer !== null) { 144 | return consumer.next(this.stream, classId, position); 145 | } else if (classId < TYPES.OBJECT_REF) { 146 | // TODO: Does this ever happen? 147 | return builtinConsumer.next(this.stream, classId, position); 148 | } 149 | const classVersion = this.stream.read(Uint8); 150 | const size = this.stream.read(Uint8); 151 | return { 152 | value: new FieldObjectHeader(classId, position, classVersion, size), 153 | done: false 154 | }; 155 | } 156 | } 157 | 158 | export {FieldIterator}; 159 | -------------------------------------------------------------------------------- /src/squeak/field-object.js: -------------------------------------------------------------------------------- 1 | import {TYPE_NAMES} from './ids'; 2 | 3 | const toTitleCase = str => ( 4 | str.toLowerCase().replace(/_(\w)/g, ([, letter]) => letter.toUpperCase()) 5 | ); 6 | 7 | /** 8 | * A object representation of a {@link Header} collecting the given {@link 9 | * Header#size} in fields. 10 | */ 11 | class FieldObject { 12 | /** 13 | * @param {TYPES} classId - {@link TYPES} id that informs what the shape of 14 | * this object is. 15 | * @param {number} version - Version number of this object. Some items in 16 | * the same class may have different content and so will be different 17 | * versions. 18 | * @param {Array.} fields - An array of fields in this FieldObject. 19 | */ 20 | constructor ({classId, version, fields}) { 21 | /** @type {number} */ 22 | this.classId = classId; 23 | 24 | /** @type {number} */ 25 | this.version = version; 26 | 27 | /** @type {Array.} */ 28 | this.fields = fields; 29 | } 30 | 31 | /** 32 | * @type {object} 33 | */ 34 | get FIELDS () { 35 | return []; 36 | } 37 | 38 | /** 39 | * @type {Array.} 40 | */ 41 | get RAW_FIELDS () { 42 | return this.fields; 43 | } 44 | 45 | string (field) { 46 | return String(this.fields[field]); 47 | } 48 | 49 | number (field) { 50 | return +this.fields[field]; 51 | } 52 | 53 | boolean (field) { 54 | return !!this.fields[field]; 55 | } 56 | 57 | toString () { 58 | if (this.constructor === FieldObject) { 59 | return `${this.constructor.name} ${this.classId} ${TYPE_NAMES[this.classId]}`; 60 | } 61 | return this.constructor.name; 62 | } 63 | 64 | /** 65 | * Define a FieldObject subclass by mapping field names to indices in 66 | * {@link FieldObject#fields}. 67 | * @param {object} FIELDS - Mapping of ALL_CAPS keys to index in {@link 68 | * FieldObject#fields}. 69 | * @param {function} [Super] - Parent class of the returned subclass. 70 | * @returns {function} - FieldObject subclass constructor. 71 | */ 72 | static define (FIELDS, Super = FieldObject) { 73 | class DefinedObject extends Super { 74 | get FIELDS () { 75 | return FIELDS; 76 | } 77 | 78 | static get FIELDS () { 79 | return FIELDS; 80 | } 81 | } 82 | 83 | Object.keys(FIELDS).forEach(key => { 84 | const index = FIELDS[key]; 85 | Object.defineProperty(DefinedObject.prototype, toTitleCase(key), { 86 | get () { 87 | return this.fields[index]; 88 | } 89 | }); 90 | }); 91 | 92 | return DefinedObject; 93 | } 94 | } 95 | 96 | export {FieldObject}; 97 | -------------------------------------------------------------------------------- /src/squeak/fields.js: -------------------------------------------------------------------------------- 1 | import {TYPES} from './ids'; 2 | 3 | /** 4 | * An abstract value contained in a `.sb` file. 5 | * 6 | * `.sb` files are made up of two blocks of Fields. Each field in the binary 7 | * file defines its "class" and is possibly followed by some binary data 8 | * depending on the class. Each class explicitly defines what follows. Knowing 9 | * all the possible classes each block can be broken up into a series of Field 10 | * objects. 11 | */ 12 | class Field { 13 | /** 14 | * @param {TYPES} classId - The class identifier of this Field. 15 | * @param {number} position - Byte position in the `.sb` file. 16 | */ 17 | constructor (classId, position) { 18 | /** 19 | * The class identifier of this Field. 20 | * @type {TYPES} 21 | */ 22 | this.classId = classId; 23 | 24 | /** 25 | * Byte position in the `.sb` file. 26 | * @type {number} 27 | */ 28 | this.position = position; 29 | } 30 | } 31 | 32 | const valueOf = obj => { 33 | if (typeof obj === 'object' && obj) return obj.valueOf(); 34 | return obj; 35 | }; 36 | 37 | /** 38 | * A concrete value contained in a `.sb` file. 39 | * @extends Field 40 | */ 41 | class Value extends Field { 42 | /** 43 | * @param {TYPES} classId - The class identifier of this Field. 44 | * @param {number} position - Byte position in the `.sb` file. 45 | * @param {*} value - A value decoded according to `classId` from an `.sb` 46 | * file. 47 | */ 48 | constructor (classId, position, value) { 49 | super(classId, position); 50 | 51 | /** 52 | * A value decoded according to `classId` from an `.sb` file. 53 | * @type {*} 54 | */ 55 | this.value = value; 56 | } 57 | 58 | valueOf () { 59 | return this.value; 60 | } 61 | 62 | toJSON () { 63 | if ( 64 | this.classId === TYPES.TRANSLUCENT_COLOR || 65 | this.classId === TYPES.COLOR 66 | ) { 67 | // TODO: Can colors be 32 bit in scratch-packets? 68 | return this.value & 0xffffff; 69 | } 70 | return this.value; 71 | } 72 | 73 | toString () { 74 | return this.value; 75 | } 76 | } 77 | 78 | /** 79 | * A header for a FieldObject representing its class and how many fields are in 80 | * the object. 81 | * 82 | * The `size` of a header is the number of Fields that appear in the byte 83 | * stream after the header that are related to the header. That set of `size` 84 | * length Fields make up a FieldObject of `classId` passed to this header. 85 | * @extends Field 86 | */ 87 | class Header extends Field { 88 | /** 89 | * @param {TYPES} classId - The class identifier of this Field. 90 | * @param {number} position - Byte position in the `.sb` file. 91 | * @param {number} size - The number of fields to collect. 92 | */ 93 | constructor (classId, position, size) { 94 | super(classId, position); 95 | 96 | /** 97 | * The number of fields to collect. 98 | * @type {number} 99 | */ 100 | this.size = size; 101 | } 102 | } 103 | 104 | /** 105 | * A integer reference of an object in an array produced by TypeIterator of 106 | * Values and FieldObjects. 107 | * @extends Field 108 | */ 109 | class Reference extends Field { 110 | /** 111 | * @param {TYPES} classId - The class identifier of this Field. 112 | * @param {number} position - Byte position in the `.sb` file. 113 | * @param {number} index - The index this Reference refers to. 114 | */ 115 | constructor (classId, position, index) { 116 | super(classId, position); 117 | 118 | /** 119 | * The index this Reference refers to. 120 | * @type {number} 121 | */ 122 | this.index = index; 123 | } 124 | 125 | valueOf () { 126 | return `Ref(${this.index})`; 127 | } 128 | } 129 | 130 | /** 131 | * An object header of 0 size. 132 | * @extends Header 133 | */ 134 | class BuiltinObjectHeader extends Header { 135 | constructor (classId, position) { 136 | super(classId, position, 0); 137 | } 138 | } 139 | 140 | 141 | /** 142 | * An object header with an id more than 99, a version, and a size. The version 143 | * and size appear in the `sb` file as one byte for version followed by another 144 | * byte for the size. 145 | * @extends Header 146 | */ 147 | class FieldObjectHeader extends Header { 148 | /** 149 | * @param {TYPES} classId - The class identifier of this Field. 150 | * @param {number} position - Byte position in the `.sb` file. 151 | * @param {number} version - The version of this instance of a certain 152 | * value. 153 | * @param {number} size - The number of fields in this object. 154 | */ 155 | constructor (classId, position, version, size) { 156 | super(classId, position, size); 157 | 158 | /** 159 | * The version of this instance of a certain value. 160 | * @type {number} 161 | */ 162 | this.version = version; 163 | } 164 | } 165 | 166 | export { 167 | Field, 168 | valueOf as value, 169 | Value, 170 | Header, 171 | Reference, 172 | BuiltinObjectHeader, 173 | FieldObjectHeader 174 | }; 175 | -------------------------------------------------------------------------------- /src/squeak/ids.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A numeric identifier for each possible class of {@link Field} that can be in 3 | * a `.sb` file. 4 | * @enum {number} 5 | */ 6 | const TYPES = { 7 | /** A `null` {@link Value}. No data is stored after the class id. */ 8 | NULL: 1, 9 | 10 | /** A `true` {@link Value}. No data is stored after the class id. */ 11 | TRUE: 2, 12 | 13 | /** A `false` {@link Value}. No data is stored after the class id. */ 14 | FALSE: 3, 15 | 16 | /** A small integer {@link Value}. The next 4 bytes represent an integer. */ 17 | SMALL_INT: 4, 18 | 19 | /** A small integer {@link Value}. The next 2 bytes represent an integer. */ 20 | SMALL_INT_16: 5, 21 | 22 | /** A large integer {@link Value}. The value is a variable number of bytes. 23 | * The next byte defines the number of bytes after that represent the 24 | * integer. The integer's bytes are stored least value first (little 25 | * endian). */ 26 | LARGE_INT_POSITIVE: 6, 27 | 28 | /** A large integer {@link Value}. The value is a variable number of bytes. 29 | * The next byte defines the number of bytes after that represent the 30 | * integer. The integer's bytes are stored least value first (little 31 | * endian). */ 32 | LARGE_INT_NEGATIVE: 7, 33 | 34 | /** A floating point {@link Value}. The next 8 bytes are stored as a double 35 | * precision floating point value. */ 36 | FLOATING: 8, 37 | 38 | /** A ascii string {@link Value}. The next 4 bytes defines the number of 39 | * following bytes that make up the string. */ 40 | STRING: 9, 41 | 42 | /** A ascii string {@link Value}. The next 4 bytes defines the number of 43 | * following bytes that make up the string. */ 44 | SYMBOL: 10, 45 | 46 | /** A sequence of bytes ({@link Value}). The next 4 bytes defines the 47 | * number of bytes in the sequence. */ 48 | BYTES: 11, 49 | 50 | /** A sequence of 16 bit samples ({@link Value}). The next 4 bytes defines 51 | * the number of samples in the sequence. */ 52 | SOUND: 12, 53 | 54 | /** A sequence of 32 bit color integers ({@link Value}). The next 4 bytes 55 | * defines the number of colors in the bitmap. */ 56 | BITMAP: 13, 57 | 58 | /** A utf8 string {@link Value}. The next 4 bytes defines the number of 59 | * bytes used by the string. */ 60 | UTF8: 14, 61 | 62 | /** An array {@link Header}. The next 4 bytes defines the following number 63 | * of fields in the array. */ 64 | ARRAY: 20, 65 | 66 | /** An array {@link Header}. The next 4 bytes defines the following number 67 | * of fields in the array. */ 68 | ORDERED_COLLECTION: 21, 69 | 70 | /** An array {@link Header}. The next 4 bytes defines the following number 71 | * of fields in the array. */ 72 | SET: 22, 73 | 74 | /** An array {@link Header}. The next 4 bytes defines the following number 75 | * of fields in the array. */ 76 | IDENTITY_SET: 23, 77 | 78 | /** A dictionary {@link Header}. The next 4 bytes defines the following 79 | * number of key/value field pairs in the dictionary. */ 80 | DICTIONARY: 24, 81 | 82 | /** A dictionary {@link Header}. The next 4 bytes defines the following 83 | * number of key/value field pairs in the dictionary. */ 84 | IDENTITY_DICTIONARY: 25, 85 | 86 | /** A color {@link Value}. The next 4 bytes represents the color. */ 87 | COLOR: 30, 88 | 89 | /** A color {@link Value}. The next 4 bytes represents the red, green, and 90 | * blue subpixels. The following byte represents the alpha. */ 91 | TRANSLUCENT_COLOR: 31, 92 | 93 | /** A 2 field point {@link Header}. The next 2 fields are the x and y 94 | * values of this point. */ 95 | POINT: 32, 96 | 97 | /** A 4 field rectangle {@link Header}. The next 4 fields are the x, y, x2, 98 | * y2 values of this rectangle. */ 99 | RECTANGLE: 33, 100 | 101 | /** A 5 field image {@link Header}. The next 5 fields are the width, 102 | * height, bit depth, unused, and bytes. */ 103 | FORM: 34, 104 | 105 | /** A 6 field image {@link Header}. The next 6 fields are the width, 106 | * height, bit depth, unsued, bytes and colormap. */ 107 | SQUEAK: 35, 108 | 109 | /** An object {@link Reference} to a position in the top level array of fields in a 110 | * block. */ 111 | OBJECT_REF: 99, 112 | 113 | /** A variable {@link FieldObjectHeader}. */ 114 | MORPH: 100, 115 | 116 | /** A variable {@link FieldObjectHeader}. */ 117 | ALIGNMENT: 104, 118 | 119 | /** A variable {@link FieldObjectHeader}. 120 | * 121 | * In Scratch 2 this is called String. To reduce confusion in the set of 122 | * types, this is called STATIC_STRING in this converter. */ 123 | STATIC_STRING: 105, 124 | 125 | /** A variable {@link FieldObjectHeader}. */ 126 | UPDATING_STRING: 106, 127 | 128 | /** A variable {@link FieldObjectHeader}. */ 129 | SAMPLED_SOUND: 109, 130 | 131 | /** A variable {@link FieldObjectHeader}. */ 132 | IMAGE_MORPH: 110, 133 | 134 | /** A variable {@link FieldObjectHeader}. */ 135 | SPRITE: 124, 136 | 137 | /** A variable {@link FieldObjectHeader}. */ 138 | STAGE: 125, 139 | 140 | /** A variable {@link FieldObjectHeader}. */ 141 | WATCHER: 155, 142 | 143 | /** A variable {@link FieldObjectHeader}. */ 144 | IMAGE_MEDIA: 162, 145 | 146 | /** A variable {@link FieldObjectHeader}. */ 147 | SOUND_MEDIA: 164, 148 | 149 | /** A variable {@link FieldObjectHeader}. */ 150 | MULTILINE_STRING: 171, 151 | 152 | /** A variable {@link FieldObjectHeader}. */ 153 | WATCHER_READOUT_FRAME: 173, 154 | 155 | /** A variable {@link FieldObjectHeader}. */ 156 | WATCHER_SLIDER: 174, 157 | 158 | /** A variable {@link FieldObjectHeader}. */ 159 | LIST_WATCHER: 175 160 | }; 161 | 162 | /** 163 | * A inverted map of TYPES. Map id numbers to their string names. 164 | * @type {object.} 165 | */ 166 | const TYPE_NAMES = Object.entries(TYPES) 167 | .reduce((carry, [key, value]) => { 168 | carry[value] = key; 169 | return carry; 170 | }, {}); 171 | 172 | export {TYPES, TYPE_NAMES}; 173 | -------------------------------------------------------------------------------- /src/squeak/reference-fixer.js: -------------------------------------------------------------------------------- 1 | import {Reference} from './fields'; 2 | 3 | class ReferenceFixer { 4 | constructor (table) { 5 | this.table = Array.from(table); 6 | this.fixed = this.fix(this.table); 7 | } 8 | 9 | fix () { 10 | const fixed = []; 11 | 12 | for (let i = 0; i < this.table.length; i++) { 13 | this.fixItem(this.table[i]); 14 | fixed.push(this.table[i]); 15 | } 16 | 17 | return fixed; 18 | } 19 | 20 | fixItem (item) { 21 | if (typeof item.fields !== 'undefined') { 22 | item = item.fields; 23 | } 24 | if (Array.isArray(item)) { 25 | for (let i = 0; i < item.length; i++) { 26 | item[i] = this.deref(item[i]); 27 | } 28 | } 29 | } 30 | 31 | deref (ref) { 32 | if (ref instanceof Reference) { 33 | return this.table[ref.index - 1]; 34 | } 35 | return ref; 36 | } 37 | } 38 | 39 | export {ReferenceFixer}; 40 | -------------------------------------------------------------------------------- /src/squeak/type-iterator.js: -------------------------------------------------------------------------------- 1 | import {FieldObjectHeader, Header} from './fields'; 2 | import {FieldObject} from './field-object'; 3 | import {FIELD_OBJECT_CONTRUCTORS} from './types'; 4 | 5 | class TypeIterator { 6 | constructor (valueIterator) { 7 | this.valueIterator = valueIterator; 8 | } 9 | 10 | [Symbol.iterator] () { 11 | return this; 12 | } 13 | 14 | next () { 15 | const nextHeader = this.valueIterator.next(); 16 | if (nextHeader.done) { 17 | return nextHeader; 18 | } 19 | 20 | const header = nextHeader.value; 21 | const {classId} = header; 22 | 23 | let value = header; 24 | 25 | if (header instanceof Header) { 26 | value = []; 27 | 28 | for (let i = 0; i < header.size; i++) { 29 | value.push(this.next().value); 30 | } 31 | } 32 | 33 | if ( 34 | FIELD_OBJECT_CONTRUCTORS[classId] !== null || 35 | header instanceof FieldObjectHeader 36 | ) { 37 | const constructor = FIELD_OBJECT_CONTRUCTORS[header.classId] || FieldObject; 38 | 39 | value = new constructor({ 40 | classId: header.classId, 41 | version: header.version, 42 | fields: value 43 | }); 44 | } 45 | 46 | return { 47 | value, 48 | done: false 49 | }; 50 | } 51 | } 52 | 53 | export {TypeIterator}; 54 | -------------------------------------------------------------------------------- /src/squeak/types.js: -------------------------------------------------------------------------------- 1 | import {CRC32} from '../coders/crc32'; 2 | import {SqueakImage} from '../coders/squeak-image'; 3 | import {SqueakSound} from '../coders/squeak-sound'; 4 | import {WAVFile} from '../coders/wav-file'; 5 | 6 | import {FieldObject} from './field-object'; 7 | import {value as valueOf} from './fields'; 8 | import {TYPES} from './ids'; 9 | 10 | import md5 from 'js-md5'; 11 | 12 | /** 13 | * @extends FieldObject 14 | */ 15 | class PointData extends FieldObject.define({ 16 | /** 17 | * @memberof PointData# 18 | * @type {Value} 19 | */ 20 | X: 0, 21 | 22 | /** 23 | * @memberof PointData# 24 | * @type {Value} 25 | */ 26 | Y: 1 27 | }) {} 28 | 29 | export {PointData}; 30 | 31 | class RectangleData extends FieldObject.define({ 32 | X: 0, 33 | Y: 1, 34 | X2: 2, 35 | Y2: 3 36 | }) { 37 | get width () { 38 | return this.x2 - this.x; 39 | } 40 | 41 | get height () { 42 | return this.y2 - this.y; 43 | } 44 | } 45 | 46 | export {RectangleData}; 47 | 48 | const _bgra2rgbaInPlace = uint8a => { 49 | for (let i = 0; i < uint8a.length; i += 4) { 50 | const r = uint8a[i + 2]; 51 | const b = uint8a[i + 0]; 52 | uint8a[i + 2] = b; 53 | uint8a[i + 0] = r; 54 | } 55 | return uint8a; 56 | }; 57 | 58 | /** 59 | * @extends FieldObject 60 | */ 61 | class ImageData extends FieldObject.define({ 62 | /** 63 | * @memberof ImageData# 64 | * @type {Value} 65 | */ 66 | WIDTH: 0, 67 | 68 | /** 69 | * @memberof ImageData# 70 | * @type {Value} 71 | */ 72 | HEIGHT: 1, 73 | 74 | /** 75 | * @memberof ImageData# 76 | * @type {Value} 77 | */ 78 | DEPTH: 2, 79 | 80 | /** 81 | * @memberof ImageData# 82 | * @type {Value} 83 | */ 84 | BYTES: 4, 85 | 86 | /** 87 | * @memberof ImageData# 88 | * @type {Value} 89 | */ 90 | COLORMAP: 5 91 | }) { 92 | /** 93 | * @type {Uint8Array} 94 | */ 95 | get decoded () { 96 | if (!this._decoded) { 97 | this._decoded = _bgra2rgbaInPlace(new Uint8Array( 98 | new SqueakImage().decode( 99 | this.width.value, 100 | this.height.value, 101 | this.depth.value, 102 | this.bytes.value, 103 | this.colormap && this.colormap.map(color => color.valueOf()) 104 | ).buffer 105 | )); 106 | } 107 | return this._decoded; 108 | } 109 | 110 | /** 111 | * @type {string} 112 | */ 113 | get extension () { 114 | return 'uncompressed'; 115 | } 116 | } 117 | 118 | export {ImageData}; 119 | 120 | class StageData extends FieldObject.define({ 121 | STAGE_CONTENTS: 2, 122 | OBJ_NAME: 6, 123 | VARS: 7, 124 | BLOCKS_BIN: 8, 125 | IS_CLONE: 9, 126 | MEDIA: 10, 127 | CURRENT_COSTUME: 11, 128 | ZOOM: 12, 129 | H_PAN: 13, 130 | V_PAN: 14, 131 | OBSOLETE_SAVED_STATE: 15, 132 | SPRITE_ORDER_IN_LIBRARY: 16, 133 | VOLUME: 17, 134 | TEMPO_BPM: 18, 135 | SCENE_STATES: 19, 136 | LISTS: 20 137 | }) { 138 | get spriteOrderInLibrary () { 139 | return this.fields[this.FIELDS.SPRITE_ORDER_IN_LIBRARY] || null; 140 | } 141 | 142 | get tempoBPM () { 143 | return this.fields[this.FIELDS.TEMPO_BPM] || 0; 144 | } 145 | 146 | get lists () { 147 | return this.fields[this.FIELDS.LISTS] || []; 148 | } 149 | } 150 | 151 | export {StageData}; 152 | 153 | class SpriteData extends FieldObject.define({ 154 | BOX: 0, 155 | PARENT: 1, 156 | COLOR: 3, 157 | VISIBLE: 4, 158 | OBJ_NAME: 6, 159 | VARS: 7, 160 | BLOCKS_BIN: 8, 161 | IS_CLONE: 9, 162 | MEDIA: 10, 163 | CURRENT_COSTUME: 11, 164 | VISIBILITY: 12, 165 | SCALE_POINT: 13, 166 | ROTATION_DEGREES: 14, 167 | ROTATION_STYLE: 15, 168 | VOLUME: 16, 169 | TEMPO_BPM: 17, 170 | DRAGGABLE: 18, 171 | SCENE_STATES: 19, 172 | LISTS: 20 173 | }) { 174 | get scratchX () { 175 | return this.box.x + this.currentCostume.rotationCenter.x - 240; 176 | } 177 | 178 | get scratchY () { 179 | return 180 - (this.box.y + this.currentCostume.rotationCenter.y); 180 | } 181 | 182 | get visible () { 183 | return (this.fields[this.FIELDS.VISIBLE] & 1) === 0; 184 | } 185 | 186 | get tempoBPM () { 187 | return this.fields[this.FIELDS.TEMPO_BPM] || 0; 188 | } 189 | 190 | get lists () { 191 | return this.fields[this.FIELDS.LISTS] || []; 192 | } 193 | } 194 | 195 | export {SpriteData}; 196 | 197 | class TextDetailsData extends FieldObject.define({ 198 | RECTANGLE: 0, 199 | FONT: 8, 200 | COLOR: 9, 201 | LINES: 11 202 | }) {} 203 | 204 | export {TextDetailsData}; 205 | 206 | class ImageMediaData extends FieldObject.define({ 207 | COSTUME_NAME: 0, 208 | BITMAP: 1, 209 | ROTATION_CENTER: 2, 210 | TEXT_DETAILS: 3, 211 | BASE_LAYER_DATA: 4, 212 | OLD_COMPOSITE: 5 213 | }) { 214 | get image () { 215 | if (this.oldComposite instanceof ImageData) { 216 | return this.oldComposite; 217 | } 218 | if (this.baseLayerData.value) { 219 | return null; 220 | } 221 | return this.bitmap; 222 | } 223 | 224 | get width () { 225 | if (this.image === null) { 226 | return -1; 227 | } 228 | return this.image.width; 229 | } 230 | 231 | get height () { 232 | if (this.image === null) { 233 | return -1; 234 | } 235 | return this.image.height; 236 | } 237 | 238 | get rawBytes () { 239 | if (this.image === null) { 240 | return this.baseLayerData.value.slice(); 241 | } 242 | return this.image.bytes.value; 243 | } 244 | 245 | get decoded () { 246 | if (this.image === null) { 247 | return this.baseLayerData.value.slice(); 248 | } 249 | return this.image.decoded; 250 | } 251 | 252 | get crc () { 253 | if (!this._crc) { 254 | const crc = new CRC32() 255 | .update(new Uint8Array(new Uint32Array([this.bitmap.width]).buffer)) 256 | .update(new Uint8Array(new Uint32Array([this.bitmap.height]).buffer)) 257 | .update(new Uint8Array(new Uint32Array([this.bitmap.depth]).buffer)) 258 | .update(this.rawBytes); 259 | this._crc = crc.digest; 260 | } 261 | return this._crc; 262 | } 263 | 264 | get extension () { 265 | if (this.oldComposite instanceof ImageData) return 'uncompressed'; 266 | if (this.baseLayerData.value) return 'jpg'; 267 | return 'uncompressed'; 268 | } 269 | 270 | toString () { 271 | return `ImageMediaData "${this.costumeName}"`; 272 | } 273 | } 274 | 275 | export {ImageMediaData}; 276 | 277 | class UncompressedData extends FieldObject.define({ 278 | DATA: 3, 279 | RATE: 4 280 | }) {} 281 | 282 | export {UncompressedData}; 283 | 284 | const reverseBytes16 = input => { 285 | const uint8a = new Uint8Array(input); 286 | for (let i = 0; i < uint8a.length; i += 2) { 287 | uint8a[i] = input[i + 1]; 288 | uint8a[i + 1] = input[i]; 289 | } 290 | return uint8a; 291 | }; 292 | 293 | class SoundMediaData extends FieldObject.define({ 294 | NAME: 0, 295 | UNCOMPRESSED: 1, 296 | RATE: 4, 297 | BITS_PER_SAMPLE: 5, 298 | DATA: 6 299 | }) { 300 | get rate () { 301 | if (this.uncompressed.data.value.length !== 0) { 302 | return this.uncompressed.rate; 303 | } 304 | return this.fields[this.FIELDS.RATE]; 305 | } 306 | 307 | get rawBytes () { 308 | if (this.data && this.data.value) { 309 | return this.data.value; 310 | } 311 | return this.uncompressed.data.value; 312 | } 313 | 314 | get decoded () { 315 | if (!this._decoded) { 316 | if (this.data && this.data.value) { 317 | this._decoded = new SqueakSound(this.bitsPerSample.value).decode( 318 | this.data.value 319 | ); 320 | } else { 321 | this._decoded = new Int16Array(reverseBytes16(this.uncompressed.data.value.slice()).buffer); 322 | } 323 | } 324 | return this._decoded; 325 | } 326 | 327 | get crc () { 328 | if (!this._crc) { 329 | this._crc = new CRC32() 330 | .update(new Uint32Array([this.rate])) 331 | .update(this.rawBytes) 332 | .digest; 333 | } 334 | return this._crc; 335 | } 336 | 337 | get sampleCount () { 338 | if (this.data && this.data.value) { 339 | return SqueakSound.samples(this.bitsPerSample.value, this.data.value); 340 | } 341 | return this.uncompressed.data.value.length / 2; 342 | } 343 | 344 | get extension () { 345 | return 'pcm'; 346 | } 347 | 348 | get wavEncodedData () { 349 | if (!this._wavEncodedData) { 350 | this._wavEncodedData = new Uint8Array(WAVFile.encode(this.decoded, { 351 | sampleRate: this.rate && this.rate.value 352 | })); 353 | } 354 | return this._wavEncodedData; 355 | } 356 | 357 | get md5 () { 358 | if (!this._md5) { 359 | this._md5 = md5(this.wavEncodedData); 360 | } 361 | return this._md5; 362 | } 363 | 364 | toString () { 365 | return `SoundMediaData "${this.name}"`; 366 | } 367 | } 368 | 369 | export {SoundMediaData}; 370 | 371 | class ListWatcherData extends FieldObject.define({ 372 | BOX: 0, 373 | HIDDEN_WHEN_NULL: 1, 374 | LIST_NAME: 8, 375 | CONTENTS: 9, 376 | TARGET: 10 377 | }) { 378 | get x () { 379 | if (valueOf(this.hiddenWhenNull) === null) return 5; 380 | return this.box.x + 1; 381 | } 382 | 383 | get y () { 384 | if (valueOf(this.hiddenWhenNull) === null) return 5; 385 | return this.box.y + 1; 386 | } 387 | 388 | get width () { 389 | return this.box.width - 2; 390 | } 391 | 392 | get height () { 393 | return this.box.height - 2; 394 | } 395 | } 396 | 397 | export {ListWatcherData}; 398 | 399 | class AlignmentData extends FieldObject.define({ 400 | BOX: 0, 401 | PARENT: 1, 402 | FRAMES: 2, 403 | COLOR: 3, 404 | DIRECTION: 8, 405 | ALIGNMENT: 9 406 | }) {} 407 | 408 | export {AlignmentData}; 409 | 410 | class MorphData extends FieldObject.define({ 411 | BOX: 0, 412 | PARENT: 1, 413 | COLOR: 3 414 | }) {} 415 | 416 | export {MorphData}; 417 | 418 | class StaticStringData extends FieldObject.define({ 419 | BOX: 0, 420 | COLOR: 3, 421 | VALUE: 8 422 | }) {} 423 | 424 | export {StaticStringData}; 425 | 426 | class UpdatingStringData extends FieldObject.define({ 427 | BOX: 0, 428 | READOUT_FRAME: 1, 429 | COLOR: 3, 430 | FONT: 6, 431 | VALUE: 8, 432 | TARGET: 10, 433 | CMD: 11, 434 | PARAM: 13 435 | }) {} 436 | 437 | export {UpdatingStringData}; 438 | 439 | class WatcherReadoutFrameData extends FieldObject.define({ 440 | BOX: 0 441 | }) {} 442 | 443 | export {WatcherReadoutFrameData}; 444 | 445 | const WATCHER_MODES = { 446 | NORMAL: 1, 447 | LARGE: 2, 448 | SLIDER: 3, 449 | TEXT: 4 450 | }; 451 | 452 | export {WATCHER_MODES}; 453 | 454 | class WatcherData extends FieldObject.define({ 455 | BOX: 0, 456 | TARGET: 1, 457 | SHAPE: 2, 458 | READOUT: 14, 459 | READOUT_FRAME: 15, 460 | SLIDER: 16, 461 | ALIGNMENT: 17, 462 | SLIDER_MIN: 20, 463 | SLIDER_MAX: 21 464 | }) { 465 | get x () { 466 | return this.box.x; 467 | } 468 | 469 | get y () { 470 | return this.box.y; 471 | } 472 | 473 | get mode () { 474 | if (valueOf(this.slider) === null) { 475 | if (this.readoutFrame.box.height <= 14) { 476 | return WATCHER_MODES.NORMAL; 477 | } 478 | return WATCHER_MODES.LARGE; 479 | } 480 | return WATCHER_MODES.SLIDER; 481 | } 482 | 483 | get isDiscrete () { 484 | return ( 485 | Math.floor(this.sliderMin) === this.sliderMin && 486 | Math.floor(this.sliderMax) === this.sliderMax && 487 | Math.floor(this.readout.value) === this.readout.value 488 | ); 489 | } 490 | } 491 | 492 | export {WatcherData}; 493 | 494 | const FIELD_OBJECT_CONTRUCTOR_PROTOS = { 495 | [TYPES.POINT]: PointData, 496 | [TYPES.RECTANGLE]: RectangleData, 497 | [TYPES.FORM]: ImageData, 498 | [TYPES.SQUEAK]: ImageData, 499 | [TYPES.SAMPLED_SOUND]: UncompressedData, 500 | [TYPES.SPRITE]: SpriteData, 501 | [TYPES.STAGE]: StageData, 502 | [TYPES.IMAGE_MEDIA]: ImageMediaData, 503 | [TYPES.SOUND_MEDIA]: SoundMediaData, 504 | [TYPES.ALIGNMENT]: AlignmentData, 505 | [TYPES.MORPH]: MorphData, 506 | [TYPES.WATCHER_READOUT_FRAME]: WatcherReadoutFrameData, 507 | [TYPES.STATIC_STRING]: StaticStringData, 508 | [TYPES.UPDATING_STRING]: UpdatingStringData, 509 | [TYPES.WATCHER]: WatcherData, 510 | [TYPES.LIST_WATCHER]: ListWatcherData 511 | }; 512 | 513 | const FIELD_OBJECT_CONTRUCTORS = Array.from( 514 | {length: 256}, 515 | (_, i) => (FIELD_OBJECT_CONTRUCTOR_PROTOS[i] || null) 516 | ); 517 | 518 | export {FIELD_OBJECT_CONTRUCTORS}; 519 | -------------------------------------------------------------------------------- /src/to-sb2/fake-zip.js: -------------------------------------------------------------------------------- 1 | import {assert} from '../util/assert'; 2 | 3 | import {PNGFile} from '../coders/png-file'; 4 | 5 | class FakeZipFile { 6 | constructor (file) { 7 | this.file = file; 8 | } 9 | 10 | async (outputType) { 11 | assert(outputType === 'uint8array', 'SB1FakeZipFile only supports uint8array'); 12 | 13 | return Promise.resolve(this.file.bytes); 14 | } 15 | } 16 | 17 | export {FakeZipFile}; 18 | 19 | class FakeZip { 20 | constructor (files) { 21 | this.files = files; 22 | } 23 | 24 | file (file) { 25 | if (file in this.files) { 26 | return new FakeZipFile(this.files[file]); 27 | } 28 | } 29 | } 30 | 31 | export {FakeZip}; 32 | 33 | const toSb2ImageExtension = imageMedia => { 34 | if (imageMedia.extension === 'uncompressed') { 35 | return 'png'; 36 | } 37 | return 'jpg'; 38 | }; 39 | 40 | const toSb2ImageMedia = imageMedia => { 41 | if (imageMedia.extension === 'uncompressed') { 42 | return new Uint8Array(PNGFile.encode( 43 | imageMedia.width, 44 | imageMedia.height, 45 | imageMedia.decoded 46 | )); 47 | } 48 | return imageMedia.decoded; 49 | }; 50 | 51 | const toSb2SoundMedia = soundMedia => soundMedia.wavEncodedData; 52 | 53 | const toSb2FakeZipApi = ({images, sounds}) => { 54 | const files = {}; 55 | 56 | let index = 0; 57 | for (const image of images) { 58 | files[`${index++}.${toSb2ImageExtension(image)}`] = { 59 | bytes: toSb2ImageMedia(image) 60 | }; 61 | } 62 | 63 | index = 0; 64 | for (const sound of sounds) { 65 | files[`${index++}.wav`] = { 66 | bytes: toSb2SoundMedia(sound) 67 | }; 68 | } 69 | 70 | return new FakeZip(files); 71 | }; 72 | 73 | export {toSb2FakeZipApi}; 74 | -------------------------------------------------------------------------------- /src/to-sb2/json-generator.js: -------------------------------------------------------------------------------- 1 | /* eslint no-use-before-define:1 */ 2 | 3 | import {ImageMediaData, SoundMediaData, StageData, SpriteData} from '../squeak/types'; 4 | import md5 from 'js-md5'; 5 | 6 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L292-L308 7 | const fixMouseEdgeRef = block => { 8 | const oldVal = String(block[block.length - 1]); 9 | const last = block.length - 1; 10 | if (oldVal === 'mouse') { 11 | block[last] = '_mouse_'; 12 | } else if (oldVal === 'edge') { 13 | block[last] = '_edge_'; 14 | } else if (block[block.length - 1] instanceof StageData) { 15 | block[last] = '_stage_'; 16 | } 17 | return block; 18 | }; 19 | 20 | const sb1SpecMap = { 21 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L197-L199 22 | 'getParam': ([a, b, c, d]) => [a, b, c, d || 'r'], 23 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L200-L212 24 | 'changeVariable': block => [block[2], block[1], block[3]], 25 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L213-L219 26 | 'EventHatMorph': block => { 27 | if (String(block[1]) === 'Scratch-StartClicked') { 28 | return ['whenGreenFlag']; 29 | } 30 | return ['whenIReceive', block[1]]; 31 | }, 32 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L220-L222 33 | 'MouseClickEventHatMorph': () => ['whenClicked'], 34 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L223-L226 35 | 'KeyEventHatMorph': block => ['whenKeyPressed', block[1]], 36 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L227-L235 37 | 'stopScripts': block => { 38 | if (String(block[1]) === 'other scripts') { 39 | return [block[0], 'other scripts in sprite']; 40 | } 41 | return block; 42 | }, 43 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L249-L253 44 | 'abs': block => ['computeFunction:of:', 'abs', block[1]], 45 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L254-L258 46 | 'sqrt': block => ['computeFunction:of:', 'sqrt', block[1]], 47 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L137 48 | '\\\\': block => ['%', ...block.slice(1)], 49 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L259-L262 50 | 'doReturn': () => ['stopScripts', 'this script'], 51 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L263-L266 52 | 'stopAll': () => ['stopScripts', 'all'], 53 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L267-L270 54 | 'showBackground:': block => ['startScene', block[1]], 55 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L271-L273 56 | 'nextBackground': () => ['nextScene'], 57 | // https://github.com/LLK/scratch-flash/blob/cb5f42f039ef633710faf9c63b69e8368b280372/src/blocks/BlockIO.as#L274-L282 58 | 'doForeverIf': block => ['doForever', [['doIf', block[1], block[2]]]], 59 | 'getAttribute:of:': fixMouseEdgeRef, 60 | 'gotoSpriteOrMouse:': fixMouseEdgeRef, 61 | 'distanceTo:': fixMouseEdgeRef, 62 | 'pointTowards:': fixMouseEdgeRef, 63 | 'touching:': fixMouseEdgeRef 64 | }; 65 | 66 | const valueOf = obj => { 67 | if (typeof obj === 'object' && obj) return obj.valueOf(); 68 | return obj; 69 | }; 70 | 71 | const toSb2Json = root => { 72 | const {info, stageData, images, sounds} = root; 73 | 74 | const pairs = array => { 75 | const _pairs = []; 76 | for (let i = 0; i < array.length; i += 2) { 77 | _pairs.push([array[i], array[i + 1]]); 78 | } 79 | return _pairs; 80 | }; 81 | 82 | const toSb2JsonVariable = ([name, value]) => ({ 83 | name, 84 | value, 85 | isPersistent: false 86 | }); 87 | 88 | const toSb2JsonList = ([, { 89 | listName, contents, x, y, width, height, hiddenWhenNull 90 | }]) => ({ 91 | listName: listName, 92 | contents: contents, 93 | isPersistent: false, 94 | x: x, 95 | y: y, 96 | width: width, 97 | height: height, 98 | visible: valueOf(hiddenWhenNull) !== null 99 | }); 100 | 101 | // TODO: Implement toSb2JsonWatcher 102 | // const toSb2JsonWatcher = watcher => { 103 | // 104 | // }; 105 | 106 | // TODO: Implement toSb2JsonListWatcher 107 | // const toSb2JsonListWatcher = listWatcher => { 108 | // 109 | // }; 110 | 111 | const toSb2JsonSound = soundMediaData => { 112 | const soundID = sounds.findIndex(sound => sound.crc === soundMediaData.crc); 113 | return { 114 | soundName: soundMediaData.name, 115 | soundID, 116 | md5: `${soundMediaData.md5}.wav`, 117 | sampleCount: soundMediaData.sampleCount, 118 | rate: soundMediaData.rate, 119 | format: '' 120 | }; 121 | }; 122 | 123 | const toSb2ImageExtension = imageMedia => { 124 | if (imageMedia.extension === 'uncompressed') { 125 | return 'png'; 126 | } 127 | return 'jpg'; 128 | }; 129 | 130 | const toSb2JsonCostume = imageMediaData => { 131 | const baseLayerID = images.findIndex(image => image.crc === imageMediaData.crc); 132 | return { 133 | costumeName: imageMediaData.costumeName, 134 | baseLayerID, 135 | baseLayerMD5: `${md5(imageMediaData.rawBytes)}.${toSb2ImageExtension(imageMediaData)}`, 136 | bitmapResolution: 1, 137 | rotationCenterX: imageMediaData.rotationCenter.x, 138 | rotationCenterY: imageMediaData.rotationCenter.y 139 | }; 140 | }; 141 | 142 | const toSb2JsonBlock = blockData => { 143 | let output = blockData.map(toSb2JsonBlockArg); 144 | const spec = sb1SpecMap[output[0]]; 145 | if (spec) { 146 | output = spec(output); 147 | } 148 | return output; 149 | }; 150 | 151 | const toSb2JsonStack = stackData => stackData.map(toSb2JsonBlock); 152 | 153 | const toSb2JsonBlockArg = argData => { 154 | if (argData instanceof SpriteData) { 155 | return argData.objName; 156 | } else if (Array.isArray(argData)) { 157 | if (argData.length === 0 || Array.isArray(argData[0])) { 158 | return toSb2JsonStack(argData); 159 | } 160 | return toSb2JsonBlock(argData); 161 | } 162 | return argData; 163 | }; 164 | 165 | const toSb2JsonScript = scriptData => ( 166 | [ 167 | scriptData[0].x, 168 | scriptData[0].y, 169 | toSb2JsonStack(scriptData[1]) 170 | ] 171 | ); 172 | 173 | const toSb2JsonSprite = spriteData => { 174 | const rawCostumes = spriteData.media 175 | .filter(data => data instanceof ImageMediaData); 176 | const rawSounds = spriteData.media 177 | .filter(data => data instanceof SoundMediaData); 178 | return { 179 | objName: spriteData.objName, 180 | variables: pairs(spriteData.vars).map(toSb2JsonVariable), 181 | lists: pairs(spriteData.lists).map(toSb2JsonList), 182 | scripts: spriteData.blocksBin.map(toSb2JsonScript), 183 | costumes: rawCostumes 184 | .map(toSb2JsonCostume), 185 | currentCostumeIndex: rawCostumes.findIndex(image => image.crc === spriteData.currentCostume.crc), 186 | sounds: rawSounds.map(toSb2JsonSound), 187 | scratchX: spriteData.scratchX, 188 | scratchY: spriteData.scratchY, 189 | scale: spriteData.scalePoint.x, 190 | direction: (Math.round(spriteData.rotationDegrees * 1e6) / 1e6) - 270, 191 | rotationStyle: spriteData.rotationStyle, 192 | isDraggable: spriteData.draggable, 193 | indexInLibrary: stageData.spriteOrderInLibrary.indexOf(spriteData), 194 | visible: spriteData.visible, 195 | spriteInfo: {} 196 | }; 197 | }; 198 | 199 | const toSb2JsonChild = child => { 200 | if (child instanceof SpriteData) { 201 | return toSb2JsonSprite(child); 202 | } 203 | return null; 204 | }; 205 | 206 | const toSb2JsonStage = _stageData => { 207 | const rawCostumes = _stageData.media 208 | .filter(data => data instanceof ImageMediaData); 209 | const rawSounds = _stageData.media 210 | .filter(data => data instanceof SoundMediaData); 211 | return { 212 | objName: _stageData.objName, 213 | variables: pairs(_stageData.vars).map(toSb2JsonVariable), 214 | lists: pairs(_stageData.lists).map(toSb2JsonList), 215 | scripts: _stageData.blocksBin.map(toSb2JsonScript), 216 | costumes: rawCostumes 217 | .map(toSb2JsonCostume), 218 | currentCostumeIndex: rawCostumes.findIndex(image => image.crc === _stageData.currentCostume.crc), 219 | sounds: rawSounds.map(toSb2JsonSound), 220 | // TODO: Where does this come from? Is it always the same for SB1? 221 | penLayerMD5: '5c81a336fab8be57adc039a8a2b33ca9.png', 222 | penLayerID: 0, 223 | tempoBPM: _stageData.tempoBPM, 224 | videoAlpha: 0.5, 225 | children: _stageData.stageContents 226 | .map(toSb2JsonChild) 227 | .filter(Boolean) 228 | .reverse() 229 | }; 230 | }; 231 | 232 | const toSb2JsonInfo = _info => { 233 | const obj = {}; 234 | for (let i = 0; i < _info.length; i += 2) { 235 | if (String(_info[i]) === 'thumbnail') continue; 236 | obj[String(_info[i])] = String(_info[i + 1]); 237 | } 238 | return obj; 239 | }; 240 | 241 | return JSON.parse(JSON.stringify(Object.assign(toSb2JsonStage(stageData), { 242 | info: toSb2JsonInfo(info) 243 | }))); 244 | }; 245 | 246 | export {toSb2Json}; 247 | -------------------------------------------------------------------------------- /src/util/assert.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A `scratch-sb1-converter` assertion. 3 | */ 4 | class AssertionError extends Error {} 5 | 6 | /** 7 | * A `scratch-sb1-converter` validation error. 8 | */ 9 | class ValidationError extends AssertionError {} 10 | 11 | const assert = function (test, message) { 12 | if (!test) throw new AssertionError(message); 13 | }; 14 | 15 | assert.validate = function (test, message) { 16 | if (!test) throw new ValidationError(message); 17 | }; 18 | 19 | export { 20 | assert, 21 | AssertionError, 22 | ValidationError 23 | }; 24 | -------------------------------------------------------------------------------- /src/util/log.js: -------------------------------------------------------------------------------- 1 | const minilog = require('minilog'); 2 | 3 | module.exports = new minilog('sb1-converter'); 4 | -------------------------------------------------------------------------------- /test/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | rules: { 3 | 'no-undefined': [0] 4 | } 5 | }; 6 | -------------------------------------------------------------------------------- /test/fixtures/valid/bouncing-music-balls.sb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-sb1-converter/f6e78a620574454f40d95e04ab40e6532f994863/test/fixtures/valid/bouncing-music-balls.sb -------------------------------------------------------------------------------- /test/fixtures/valid/default.sb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-sb1-converter/f6e78a620574454f40d95e04ab40e6532f994863/test/fixtures/valid/default.sb -------------------------------------------------------------------------------- /test/fixtures/valid/ewe-and-me.sb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-sb1-converter/f6e78a620574454f40d95e04ab40e6532f994863/test/fixtures/valid/ewe-and-me.sb -------------------------------------------------------------------------------- /test/integration/default.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const test = require('tap').test; 4 | 5 | const {SB1File} = require('../..'); 6 | 7 | test('default', t => { 8 | const uri = path.resolve(__dirname, '../fixtures/valid/default.sb'); 9 | const file = fs.readFileSync(uri); 10 | 11 | const sb1 = new SB1File(file); 12 | const json = sb1.json; 13 | 14 | t.type(json, Object); 15 | t.deepEqual(json.variables, []); 16 | t.deepEqual(json.lists, []); 17 | t.deepEqual(json.scripts, []); 18 | 19 | t.true(Array.isArray(json.costumes)); 20 | t.equal(json.costumes[0].costumeName, 'background1'); 21 | t.equal(json.costumes[0].baseLayerID, 0); 22 | t.equal(json.costumes[0].baseLayerMD5, 'be2aa84eeac485ab8d9ca51294cd926e.png'); 23 | t.equal(json.costumes[0].bitmapResolution, 1); 24 | t.equal(json.costumes[0].rotationCenterX, 240); 25 | t.equal(json.costumes[0].rotationCenterY, 180); 26 | 27 | t.true(Array.isArray(json.sounds)); 28 | t.equal(json.sounds[0].soundName, 'pop'); 29 | t.equal(json.sounds[0].soundID, 0); 30 | t.equal(json.sounds[0].md5, '83a9787d4cb6f3b7632b4ddfebf74367.wav'); 31 | t.equal(json.sounds[0].sampleCount, 258); 32 | t.equal(json.sounds[0].rate, 11025); 33 | t.equal(json.sounds[0].format, ''); 34 | 35 | t.true(Array.isArray(json.children)); 36 | t.equal(json.children[0].objName, 'Sprite1'); 37 | t.equal(json.children[0].currentCostumeIndex, 0); 38 | t.equal(json.children[0].scratchX, 0); 39 | t.equal(json.children[0].scratchY, 0); 40 | t.equal(json.children[0].scale, 1); 41 | t.equal(json.children[0].direction, -270); 42 | t.equal(json.children[0].rotationStyle, 'normal'); 43 | t.equal(json.children[0].isDraggable, false); 44 | t.equal(json.children[0].indexInLibrary, 0); 45 | t.equal(json.children[0].visible, true); 46 | t.deepEqual(json.children[0].variables, []); 47 | t.deepEqual(json.children[0].lists, []); 48 | t.deepEqual(json.children[0].scripts, []); 49 | t.deepEqual(json.children[0].costumes, [ 50 | { 51 | baseLayerID: 1, 52 | baseLayerMD5: '87b6d14fce8842fb56155dc7f6496308.png', 53 | bitmapResolution: 1, 54 | costumeName: 'costume1', 55 | rotationCenterX: 47, 56 | rotationCenterY: 55 57 | }, 58 | { 59 | baseLayerID: 2, 60 | baseLayerMD5: '07a12efdb3cd7ffc94b55563268367b1.png', 61 | bitmapResolution: 1, 62 | costumeName: 'costume2', 63 | rotationCenterX: 47, 64 | rotationCenterY: 55 65 | } 66 | ]); 67 | t.deepEqual(json.children[0].sounds, [ 68 | { 69 | format: '', 70 | md5: '83c36d806dc92327b9e7049a565c6bff.wav', 71 | rate: 22050, 72 | sampleCount: 18688, 73 | soundID: 1, 74 | soundName: 'meow' 75 | } 76 | ]); 77 | 78 | t.equal(json.tempoBPM, 60); 79 | t.equal(json.currentCostumeIndex, 0); 80 | t.equal(json.videoAlpha, 0.5); 81 | t.type(json.info, Object); 82 | 83 | t.end(); 84 | }); 85 | -------------------------------------------------------------------------------- /test/integration/valid.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const test = require('tap').test; 4 | 5 | const {SB1File} = require('../..'); 6 | 7 | test('bouncing-music-balls', t => { 8 | const uri = path.resolve(__dirname, '../fixtures/valid/bouncing-music-balls.sb'); 9 | const file = fs.readFileSync(uri); 10 | 11 | const sb1 = new SB1File(file); 12 | const json = sb1.json; 13 | 14 | t.type(json, Object); 15 | t.true(Array.isArray(json.variables)); 16 | t.equal(json.variables.length, 34); 17 | t.deepEqual(json.variables[0], { 18 | isPersistent: false, 19 | name: 'decrease', 20 | value: 0 21 | }); 22 | t.deepEqual(json.lists, []); 23 | t.true(Array.isArray(json.scripts)); 24 | t.equal(json.scripts.length, 5); 25 | t.equal(json.scripts[0][0], 113); 26 | t.equal(json.scripts[0][1], 53); 27 | t.equal(json.scripts[0][2][0][0], 'whenGreenFlag'); 28 | 29 | t.true(Array.isArray(json.costumes)); 30 | t.equal(json.costumes[0].costumeName, 'openEdges'); 31 | t.equal(json.costumes[0].baseLayerID, 1); 32 | t.equal(json.costumes[0].baseLayerMD5, '4c9df7bf7300ef254616a47d98eac474.png'); 33 | t.equal(json.costumes[0].bitmapResolution, 1); 34 | t.equal(json.costumes[0].rotationCenterX, 240); 35 | t.equal(json.costumes[0].rotationCenterY, 180); 36 | 37 | t.true(Array.isArray(json.sounds)); 38 | t.equal(json.sounds[0].soundName, 'pop'); 39 | t.equal(json.sounds[0].soundID, 0); 40 | t.equal(json.sounds[0].md5, '83a9787d4cb6f3b7632b4ddfebf74367.wav'); 41 | t.equal(json.sounds[0].sampleCount, 258); 42 | t.equal(json.sounds[0].rate, 11025); 43 | t.equal(json.sounds[0].format, ''); 44 | 45 | t.true(Array.isArray(json.children)); 46 | t.equal(json.children[0].objName, 'Emitter'); 47 | t.equal(json.children[0].currentCostumeIndex, 0); 48 | t.equal(json.children[0].scratchX, -217); 49 | t.equal(json.children[0].scratchY, 98); 50 | t.equal(json.children[0].scale, 1); 51 | t.equal(json.children[0].direction, 38); 52 | t.equal(json.children[0].rotationStyle, 'normal'); 53 | t.equal(json.children[0].isDraggable, false); 54 | t.equal(json.children[0].indexInLibrary, 0); 55 | t.equal(json.children[0].visible, true); 56 | t.deepEqual(json.children[0].variables, []); 57 | t.deepEqual(json.children[0].lists, []); 58 | t.true(Array.isArray(json.children[0].scripts)); 59 | t.equal(json.children[0].scripts.length, 14); 60 | t.true(Array.isArray(json.children[0].costumes)); 61 | t.equal(json.children[0].costumes.length, 1); 62 | 63 | t.equal(json.tempoBPM, 100); 64 | t.equal(json.currentCostumeIndex, 1); 65 | t.equal(json.videoAlpha, 0.5); 66 | t.type(json.info, Object); 67 | 68 | t.end(); 69 | }); 70 | 71 | test('ewe-and-me', t => { 72 | const uri = path.resolve(__dirname, '../fixtures/valid/ewe-and-me.sb'); 73 | const file = fs.readFileSync(uri); 74 | 75 | const sb1 = new SB1File(file); 76 | const json = sb1.json; 77 | 78 | t.type(json, Object); 79 | t.deepEqual(json.variables, []); 80 | t.deepEqual(json.lists, []); 81 | t.deepEqual(json.scripts, []); 82 | 83 | t.true(Array.isArray(json.costumes)); 84 | t.equal(json.costumes[0].costumeName, 'background1'); 85 | t.equal(json.costumes[0].baseLayerID, 0); 86 | t.equal(json.costumes[0].baseLayerMD5, '477e98a9e6b26f4d5bbf58f9e135eb45.png'); 87 | t.equal(json.costumes[0].bitmapResolution, 1); 88 | t.equal(json.costumes[0].rotationCenterX, 240); 89 | t.equal(json.costumes[0].rotationCenterY, 180); 90 | 91 | t.true(Array.isArray(json.sounds)); 92 | t.equal(json.sounds[0].soundName, 'pop'); 93 | t.equal(json.sounds[0].soundID, 0); 94 | t.equal(json.sounds[0].md5, '83a9787d4cb6f3b7632b4ddfebf74367.wav'); 95 | t.equal(json.sounds[0].sampleCount, 258); 96 | t.equal(json.sounds[0].rate, 11025); 97 | t.equal(json.sounds[0].format, ''); 98 | 99 | t.true(Array.isArray(json.children)); 100 | t.equal(json.children[0].objName, 'animation'); 101 | t.equal(json.children[0].currentCostumeIndex, 0); 102 | t.equal(json.children[0].scratchX, 2); 103 | t.equal(json.children[0].scratchY, -1); 104 | t.equal(json.children[0].scale, 1.5); 105 | t.equal(json.children[0].direction, -270); 106 | t.equal(json.children[0].rotationStyle, 'normal'); 107 | t.equal(json.children[0].isDraggable, false); 108 | t.equal(json.children[0].indexInLibrary, 0); 109 | t.equal(json.children[0].visible, true); 110 | t.deepEqual(json.children[0].variables, []); 111 | t.deepEqual(json.children[0].lists, []); 112 | t.true(Array.isArray(json.children[0].scripts)); 113 | t.equal(json.children[0].scripts.length, 3); 114 | t.true(Array.isArray(json.children[0].costumes)); 115 | t.equal(json.children[0].costumes.length, 23); 116 | 117 | t.equal(json.tempoBPM, 100); 118 | t.equal(json.currentCostumeIndex, 0); 119 | t.equal(json.videoAlpha, 0.5); 120 | t.type(json.info, Object); 121 | 122 | t.end(); 123 | }); 124 | -------------------------------------------------------------------------------- /test/unit/adler32.js: -------------------------------------------------------------------------------- 1 | const test = require('tap').test; 2 | 3 | const {Adler32} = require('../../src/coders/adler32'); 4 | 5 | test('spec', t => { 6 | const instance = new Adler32(); 7 | t.type(Adler32, 'function'); 8 | t.type(instance.update, 'function'); 9 | t.type(instance.digest, 'number'); 10 | t.end(); 11 | }); 12 | 13 | test('digest', t => { 14 | const instance = new Adler32(); 15 | const buf = new Uint8Array(128); 16 | instance.update(buf, 0, buf.length); 17 | t.equal(instance.digest, 8388609); 18 | t.end(); 19 | }); 20 | -------------------------------------------------------------------------------- /test/unit/byte-packets.js: -------------------------------------------------------------------------------- 1 | const test = require('tap').test; 2 | 3 | const {Packet} = require('../../src/coders/byte-packets'); 4 | const {Uint8, Uint16LE} = require('../../src/coders/byte-primitives'); 5 | 6 | test('spec', t => { 7 | t.type(Packet, 'function'); 8 | t.type(Packet.initConstructor, 'function'); 9 | t.type(Packet.extend, 'function'); 10 | 11 | const uint8a = new Uint8Array(128); 12 | const instance = new Packet(uint8a, 0); 13 | t.type(instance.uint8a, 'object'); 14 | t.type(instance.offset, 'number'); 15 | t.type(instance.equals, 'function'); 16 | t.type(instance.view, 'function'); 17 | t.end(); 18 | }); 19 | 20 | test('equals (true)', t => { 21 | const packet = new Packet(); 22 | t.true(packet.equals({ 23 | offset: 0 24 | })); 25 | t.end(); 26 | }); 27 | 28 | test('equals (false)', t => { 29 | const packet = new Packet(); 30 | t.false(packet.equals({ 31 | offset: 1 32 | })); 33 | t.end(); 34 | }); 35 | 36 | test('equals (undefined)', t => { 37 | const packet = new Packet(); 38 | t.false(packet.equals({ 39 | foo: 'bar' 40 | })); 41 | t.end(); 42 | }); 43 | 44 | test('view', t => { 45 | const packet = new Packet(); 46 | const view = packet.view(); 47 | t.type(view, 'object'); 48 | t.type(view.toString, 'function'); 49 | t.type(view.toString(), 'string'); 50 | t.end(); 51 | }); 52 | 53 | test('extend (valid)', t => { 54 | class TestPacket extends Packet.extend({ 55 | binaryType: Uint8, 56 | value: Uint16LE 57 | }) {} 58 | 59 | Packet.initConstructor(TestPacket); 60 | const packet = new TestPacket(); 61 | t.type(packet, 'object'); 62 | t.end(); 63 | }); 64 | 65 | test('extend (invalid)', t => { 66 | const shouldThrow = function () { 67 | Uint8.size = 0; 68 | class TestPacket extends Packet.extend({ 69 | binaryType: Uint8, 70 | value: Uint16LE 71 | }) {} 72 | t.type(TestPacket, 'undefined'); 73 | }; 74 | t.throws(shouldThrow); 75 | t.end(); 76 | }); 77 | -------------------------------------------------------------------------------- /test/unit/byte-primitives.js: -------------------------------------------------------------------------------- 1 | const test = require('tap').test; 2 | 3 | const { 4 | BytePrimitive, 5 | Uint8, 6 | Uint16BE, 7 | Uint16LE, 8 | Uint32BE, 9 | Uint32LE, 10 | Int16BE, 11 | Int32BE, 12 | DoubleBE, 13 | FixedAsciiString 14 | } = require('../../src/coders/byte-primitives'); 15 | 16 | test('spec', t => { 17 | t.type(BytePrimitive, 'function'); 18 | 19 | const instance = new BytePrimitive({size: 1}); 20 | t.type(instance, 'object'); 21 | t.type(instance.asPropertyObject, 'function'); 22 | t.end(); 23 | }); 24 | 25 | test('Uint8', t => { 26 | t.type(Uint8, 'object'); 27 | t.type(Uint8.size, 'number'); 28 | t.type(Uint8.read, 'function'); 29 | t.type(Uint8.write, 'function'); 30 | t.type(Uint8.toBytes, 'object'); 31 | 32 | const bytes = new Uint8Array(2); 33 | t.equal(Uint8.write(bytes, 0, 255), 255); 34 | t.equal(Uint8.read(bytes, 0), 255); 35 | t.equal(Uint8.read(bytes, 1), 0); 36 | t.end(); 37 | }); 38 | 39 | test('Uint16BE', t => { 40 | t.type(Uint16BE, 'object'); 41 | t.type(Uint16BE.size, 'number'); 42 | t.type(Uint16BE.read, 'function'); 43 | t.type(Uint16BE.write, 'function'); 44 | t.type(Uint16BE.toBytes, 'object'); 45 | 46 | const bytes = new Uint8Array(3); 47 | t.equal(Uint16BE.write(bytes, 0, 65535), 65535); 48 | t.equal(Uint16BE.read(bytes, 0), 65535); 49 | t.equal(Uint16BE.read(bytes, 1), 65280); 50 | t.equal(Uint16BE.read(bytes, 2), 0); 51 | t.end(); 52 | }); 53 | 54 | test('Uint16LE', t => { 55 | t.type(Uint16LE, 'object'); 56 | t.type(Uint16LE.size, 'number'); 57 | t.type(Uint16LE.read, 'function'); 58 | t.type(Uint16LE.write, 'function'); 59 | t.type(Uint16LE.toBytes, 'object'); 60 | 61 | const bytes = new Uint8Array(3); 62 | t.equal(Uint16LE.write(bytes, 0, 65535), 65535); 63 | t.equal(Uint16LE.read(bytes, 0), 65535); 64 | t.equal(Uint16LE.read(bytes, 1), 255); 65 | t.equal(Uint16LE.read(bytes, 2), 0); 66 | t.end(); 67 | }); 68 | 69 | test('Uint32BE', t => { 70 | t.type(Uint32BE, 'object'); 71 | t.type(Uint32BE.size, 'number'); 72 | t.type(Uint32BE.read, 'function'); 73 | t.type(Uint32BE.write, 'function'); 74 | t.type(Uint32BE.toBytes, 'object'); 75 | 76 | const bytes = new Uint8Array(5); 77 | t.equal(Uint32BE.write(bytes, 0, 4294967295), 4294967295); 78 | t.equal(Uint32BE.read(bytes, 0), 4294967295); 79 | t.equal(Uint32BE.read(bytes, 1), 4294967040); 80 | t.equal(Uint32BE.read(bytes, 2), 4294901760); 81 | t.equal(Uint32BE.read(bytes, 3), 4278190080); 82 | t.equal(Uint32BE.read(bytes, 4), 0); 83 | t.end(); 84 | }); 85 | 86 | test('Uint32LE', t => { 87 | t.type(Uint32LE, 'object'); 88 | t.type(Uint32LE.size, 'number'); 89 | t.type(Uint32LE.read, 'function'); 90 | t.type(Uint32LE.write, 'function'); 91 | t.type(Uint32LE.toBytes, 'object'); 92 | 93 | const bytes = new Uint8Array(5); 94 | t.equal(Uint32LE.write(bytes, 0, 4294967295), 4294967295); 95 | t.equal(Uint32LE.read(bytes, 0), 4294967295); 96 | t.equal(Uint32LE.read(bytes, 1), 16777215); 97 | t.equal(Uint32LE.read(bytes, 2), 65535); 98 | t.equal(Uint32LE.read(bytes, 3), 255); 99 | t.equal(Uint32LE.read(bytes, 4), 0); 100 | t.end(); 101 | }); 102 | 103 | test('Int16BE', t => { 104 | t.type(Int16BE, 'object'); 105 | t.type(Int16BE.size, 'number'); 106 | t.type(Int16BE.read, 'function'); 107 | t.type(Int16BE.write, 'function'); 108 | t.type(Int16BE.toBytes, 'object'); 109 | 110 | const bytes = new Uint8Array(3); 111 | t.equal(Int16BE.write(bytes, 0, 65535), 65535); 112 | t.equal(Int16BE.read(bytes, 0), -1); 113 | t.equal(Int16BE.read(bytes, 1), -256); 114 | t.equal(Int16BE.read(bytes, 2), 0); 115 | t.end(); 116 | }); 117 | 118 | test('Int32BE', t => { 119 | t.type(Int32BE, 'object'); 120 | t.type(Int32BE.size, 'number'); 121 | t.type(Int32BE.read, 'function'); 122 | t.type(Int32BE.write, 'function'); 123 | t.type(Int32BE.toBytes, 'object'); 124 | 125 | const bytes = new Uint8Array(5); 126 | t.equal(Int32BE.write(bytes, 0, 4294967295), 4294967295); 127 | t.equal(Int32BE.read(bytes, 0), -1); 128 | t.equal(Int32BE.read(bytes, 1), -256); 129 | t.equal(Int32BE.read(bytes, 2), -65536); 130 | t.equal(Int32BE.read(bytes, 3), -16777216); 131 | t.equal(Int32BE.read(bytes, 4), 0); 132 | t.end(); 133 | }); 134 | 135 | test('DoubleBE', t => { 136 | t.type(DoubleBE, 'object'); 137 | t.type(DoubleBE.size, 'number'); 138 | t.type(DoubleBE.read, 'function'); 139 | t.type(DoubleBE.write, 'function'); 140 | t.type(DoubleBE.toBytes, 'object'); 141 | 142 | const bytes = new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 0]); 143 | t.true(DoubleBE.read(bytes, 0) > 0); 144 | t.throws(() => { 145 | DoubleBE.write(bytes, 0, -1); 146 | }); 147 | t.end(); 148 | }); 149 | 150 | test('FixedAsciiString', t => { 151 | const instance = new FixedAsciiString(3); 152 | t.type(instance, 'object'); 153 | t.type(instance.size, 'number'); 154 | t.type(instance.read, 'function'); 155 | t.type(instance.write, 'function'); 156 | t.type(instance.toBytes, 'object'); 157 | 158 | const bytes = new Uint8Array(3); 159 | t.equal(instance.write(bytes, 0, 'foo'), 'foo'); 160 | t.equal(instance.read(bytes, 0), 'foo'); 161 | t.end(); 162 | }); 163 | -------------------------------------------------------------------------------- /test/unit/byte-stream.js: -------------------------------------------------------------------------------- 1 | const test = require('tap').test; 2 | 3 | const {ByteStream} = require('../../src/coders/byte-stream'); 4 | const {Packet} = require('../../src/coders/byte-packets'); 5 | const {Uint8} = require('../../src/coders/byte-primitives'); 6 | 7 | test('spec', t => { 8 | t.type(ByteStream, 'function'); 9 | 10 | const buffer = new ArrayBuffer(128); 11 | const instance = new ByteStream(buffer, 0); 12 | t.type(instance.buffer, 'object'); 13 | t.type(instance.position, 'number'); 14 | t.type(instance.uint8a, 'object'); 15 | t.type(instance.read, 'function'); 16 | t.type(instance.readStruct, 'function'); 17 | t.type(instance.resize, 'function'); 18 | t.type(instance.write, 'function'); 19 | t.type(instance.writeStruct, 'function'); 20 | t.type(instance.writeBytes, 'function'); 21 | t.end(); 22 | }); 23 | 24 | test('read', t => { 25 | const buffer = new Uint8Array([0, 1, 255]).buffer; 26 | const instance = new ByteStream(buffer); 27 | t.equal(instance.read(Uint8), 0); 28 | t.equal(instance.read(Uint8), 1); 29 | t.equal(instance.read(Uint8), 255); 30 | t.type(instance.read(Uint8), 'undefined'); 31 | t.end(); 32 | }); 33 | 34 | test('readStruct', t => { 35 | const buffer = new Uint8Array([0, 1, 10, 255]).buffer; 36 | const instance = new ByteStream(buffer); 37 | const result = instance.readStruct(Packet); 38 | t.type(result, 'object'); 39 | // @todo This should use a "Packet" subclass and validate the contents of 40 | // the returned packet 41 | t.end(); 42 | }); 43 | 44 | test('resize', t => { 45 | const buffer = new Uint8Array([]).buffer; 46 | const instance = new ByteStream(buffer); 47 | t.equal(instance.buffer.byteLength, 0); 48 | instance.resize(8); 49 | t.equal(instance.buffer.byteLength, 8); 50 | instance.resize(2); 51 | t.equal(instance.buffer.byteLength, 8); 52 | t.end(); 53 | }); 54 | 55 | test('write', t => { 56 | const buffer = new Uint8Array([0, 1, 255]).buffer; 57 | const instance = new ByteStream(buffer); 58 | t.equal(instance.read(Uint8), 0); 59 | t.equal(instance.read(Uint8), 1); 60 | t.equal(instance.read(Uint8), 255); 61 | t.equal(instance.write(Uint8, 255), 255); 62 | t.type(instance.read(Uint8), 'undefined'); 63 | t.end(); 64 | }); 65 | 66 | test('writeStruct', t => { 67 | const buffer = new Uint8Array([0, 1, 255]).buffer; 68 | const bytes = new Uint8Array([0, 0, 0]); 69 | const instance = new ByteStream(buffer); 70 | const result = instance.writeStruct(Packet, bytes); 71 | t.type(result, 'object'); 72 | // @todo This should use a "Packet" subclass and validate the contents of 73 | // the returned packet 74 | t.end(); 75 | }); 76 | 77 | test('writeBytes', t => { 78 | const buffer = new Uint8Array([0, 1, 255]).buffer; 79 | const bytes = new Uint8Array([0, 0, 0]); 80 | const instance = new ByteStream(buffer); 81 | const result = instance.writeBytes(bytes); 82 | t.type(result, 'object'); 83 | t.equal(result, bytes); 84 | t.end(); 85 | }); 86 | 87 | test('writeBytes (invalid)', t => { 88 | const buffer = new Uint8Array([0, 1, 255]).buffer; 89 | const instance = new ByteStream(buffer); 90 | t.throws(() => { 91 | instance.writeBytes([0, 0, 0]); 92 | }); 93 | t.end(); 94 | }); 95 | -------------------------------------------------------------------------------- /test/unit/crc32.js: -------------------------------------------------------------------------------- 1 | const test = require('tap').test; 2 | 3 | const {CRC32} = require('../../src/coders/crc32'); 4 | 5 | test('spec', t => { 6 | const instance = new CRC32(); 7 | t.type(CRC32, 'function'); 8 | t.type(instance.update, 'function'); 9 | t.type(instance.digest, 'number'); 10 | t.end(); 11 | }); 12 | 13 | test('digest', t => { 14 | const instance = new CRC32(); 15 | const buf = new Uint8Array(128); 16 | instance.update(buf, 0, buf.length); 17 | t.equal(instance.digest, 3265854109); 18 | t.end(); 19 | }); 20 | -------------------------------------------------------------------------------- /test/unit/spec.js: -------------------------------------------------------------------------------- 1 | const test = require('tap').test; 2 | 3 | const SB1 = require('../..'); 4 | 5 | test('spec', t => { 6 | t.type(SB1, Object); 7 | t.type(SB1.SB1File, Function); 8 | t.type(SB1.AssertionError, Function); 9 | t.type(SB1.ValidationError, Function); 10 | t.end(); 11 | }); 12 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 4 | 5 | module.exports = { 6 | mode: process.env.NODE_ENV === 'production' ? 'production' : 'development', 7 | devServer: { 8 | contentBase: false, 9 | host: '0.0.0.0', 10 | port: process.env.PORT || 8093 11 | }, 12 | entry: { 13 | main: './index.js', 14 | view: './src/playground/index.js' 15 | }, 16 | output: { 17 | path: path.resolve(__dirname, 'playground'), 18 | libraryTarget: 'commonjs2' 19 | }, 20 | externals: ['text-encoding'], 21 | module: { 22 | rules: [{ 23 | test: /\.js$/, 24 | loader: 'babel-loader', 25 | include: path.resolve(__dirname, 'src'), 26 | query: { 27 | presets: [['@babel/preset-env', {targets: {browsers: ['last 3 versions', 'Safari >= 8', 'iOS >= 8']}}]] 28 | } 29 | }] 30 | }, 31 | plugins: [ 32 | new HtmlWebpackPlugin({ 33 | template: './src/playground/index.html', 34 | chunks: ['view'] 35 | }) 36 | ] 37 | }; 38 | --------------------------------------------------------------------------------