diff --git a/package-lock.json b/package-lock.json
index c0a7bd30b3c..b66c3740902 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,6 +10,7 @@
"license": "AGPL-3.0-only",
"workspaces": [
"packages/task-herder",
+ "packages/scratch-storage",
"packages/scratch-svg-renderer",
"packages/scratch-render",
"packages/scratch-vm",
@@ -22,6 +23,7 @@
"globals": "16.5.0",
"husky": "8.0.3",
"npm": "10.9.4",
+ "sort-package-json": "3.6.1",
"ts-node": "10.9.2"
}
},
@@ -1855,6 +1857,37 @@
"@babel/core": "^7.0.0-0"
}
},
+ "node_modules/@babel/plugin-transform-runtime": {
+ "version": "7.28.5",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.28.5.tgz",
+ "integrity": "sha512-20NUVgOrinudkIBzQ2bNxP08YpKprUkRTiRSd2/Z5GOdPImJGkoN4Z7IQe1T5AdyKI1i5L6RBmluqdSzvaq9/w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-module-imports": "^7.27.1",
+ "@babel/helper-plugin-utils": "^7.27.1",
+ "babel-plugin-polyfill-corejs2": "^0.4.14",
+ "babel-plugin-polyfill-corejs3": "^0.13.0",
+ "babel-plugin-polyfill-regenerator": "^0.6.5",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-runtime/node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
"node_modules/@babel/plugin-transform-shorthand-properties": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.27.1.tgz",
@@ -6402,6 +6435,10 @@
"resolved": "packages/scratch-render",
"link": true
},
+ "node_modules/@scratch/scratch-storage": {
+ "resolved": "packages/scratch-storage",
+ "link": true
+ },
"node_modules/@scratch/scratch-svg-renderer": {
"resolved": "packages/scratch-svg-renderer",
"link": true
@@ -15737,6 +15774,19 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
+ "node_modules/detect-indent": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-7.0.2.tgz",
+ "integrity": "sha512-y+8xyqdGLL+6sh0tVeHcfP/QDd8gUgbasolJJpY7NgeQGSZ739bDtSiaiDgtoicy+mtYB81dKLxO9xRhCyIB3A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -19872,6 +19922,16 @@
"node": ">= 4.0.0"
}
},
+ "node_modules/git-hooks-list": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/git-hooks-list/-/git-hooks-list-4.2.1.tgz",
+ "integrity": "sha512-WNvqJjOxxs/8ZP9+DWdwWJ7cDsd60NHf39XnD82pDVrKO5q7xfPqpkK6hwEAmBa/ZSEE4IOoR75EzbbIuwGlMw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/fisker/git-hooks-list?sponsor=1"
+ }
+ },
"node_modules/git-log-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/git-log-parser/-/git-log-parser-1.2.1.tgz",
@@ -24626,6 +24686,18 @@
"node": ">=6"
}
},
+ "node_modules/json": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/json/-/json-10.0.0.tgz",
+ "integrity": "sha512-iK7tAZtpoghibjdB1ncCWykeBMmke3JThUe+rnkD4qkZaglOIQ70Pw7r5UJ4lyUT+7gnw7ehmmLUHDuhqzQD+g==",
+ "dev": true,
+ "bin": {
+ "json": "lib/json.js"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/json-buffer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
@@ -35388,28 +35460,6 @@
"semantic-release": ">=19.0.2"
}
},
- "node_modules/scratch-storage": {
- "version": "6.1.3",
- "resolved": "https://registry.npmjs.org/scratch-storage/-/scratch-storage-6.1.3.tgz",
- "integrity": "sha512-xoUIB7/MNF2864lz6mfwGxKwlp7LdpvM4k+amzp3RwtYlQIjca9t/U8dngKKS0zEz4Fc1fuykYRqRPchVnE+Fg==",
- "license": "AGPL-3.0-only",
- "dependencies": {
- "@babel/runtime": "^7.21.0",
- "@scratch/task-herder": "12.6.0",
- "arraybuffer-loader": "^1.0.3",
- "base64-js": "^1.3.0",
- "buffer": "6.0.3",
- "fastestsmallesttextencoderdecoder": "^1.0.7",
- "js-md5": "^0.7.3",
- "minilog": "^3.1.0"
- }
- },
- "node_modules/scratch-storage/node_modules/@scratch/task-herder": {
- "version": "12.6.0",
- "resolved": "https://registry.npmjs.org/@scratch/task-herder/-/task-herder-12.6.0.tgz",
- "integrity": "sha512-T5sO3GnNan4ffGpkNSq6NcRGQA5AIED7Oujg9kdGVnbGiHVZu8WwsRgwneTOQ99cfeADnLzWQPJpOsNAZBmMng==",
- "license": "AGPL-3.0-only"
- },
"node_modules/scratch-translate-extension-languages": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/scratch-translate-extension-languages/-/scratch-translate-extension-languages-1.0.7.tgz",
@@ -36821,6 +36871,74 @@
"node": ">=0.10.0"
}
},
+ "node_modules/sort-object-keys": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/sort-object-keys/-/sort-object-keys-2.1.0.tgz",
+ "integrity": "sha512-SOiEnthkJKPv2L6ec6HMwhUcN0/lppkeYuN1x63PbyPRrgSPIuBJCiYxYyvWRTtjMlOi14vQUCGUJqS6PLVm8g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/sort-package-json": {
+ "version": "3.6.1",
+ "resolved": "https://registry.npmjs.org/sort-package-json/-/sort-package-json-3.6.1.tgz",
+ "integrity": "sha512-Chgejw1+10p2D0U2tB7au1lHtz6TkFnxmvZktyBCRyV0GgmF6nl1IxXxAsPtJVsUyg/fo+BfCMAVVFUVRkAHrQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "detect-indent": "^7.0.2",
+ "detect-newline": "^4.0.1",
+ "git-hooks-list": "^4.1.1",
+ "is-plain-obj": "^4.1.0",
+ "semver": "^7.7.3",
+ "sort-object-keys": "^2.0.1",
+ "tinyglobby": "^0.2.15"
+ },
+ "bin": {
+ "sort-package-json": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/sort-package-json/node_modules/detect-newline": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-4.0.1.tgz",
+ "integrity": "sha512-qE3Veg1YXzGHQhlA6jzebZN2qVf6NX+A7m7qlhCGG30dJixrAQhYOsJjsnBjJkCSmuOPpCk30145fr8FV0bzog==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/sort-package-json/node_modules/is-plain-obj": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/sort-package-json/node_modules/semver": {
+ "version": "7.7.3",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/source-list-map": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz",
@@ -39551,6 +39669,16 @@
}
}
},
+ "node_modules/ts-jest-mock-import-meta": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/ts-jest-mock-import-meta/-/ts-jest-mock-import-meta-1.3.1.tgz",
+ "integrity": "sha512-KGrp9Nh/SdyrQs5hZvtkp0CFPOgAh3DL57NZgFRbtlvMyEo7XuXLbeyylmxFZGGu30pL338h9KxwSxrNDndygw==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "ts-jest": ">=20.0.0"
+ }
+ },
"node_modules/ts-jest/node_modules/semver": {
"version": "7.7.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
@@ -42492,6 +42620,7 @@
"@microbit/microbit-universal-hex": "0.2.2",
"@radix-ui/react-context-menu": "2.2.16",
"@scratch/scratch-render": "12.6.1",
+ "@scratch/scratch-storage": "12.6.1",
"@scratch/scratch-svg-renderer": "12.6.1",
"@scratch/scratch-vm": "12.6.1",
"@tensorflow-models/face-detection": "1.0.3",
@@ -42549,7 +42678,6 @@
"scratch-l10n": "6.1.60",
"scratch-paint": "4.1.50",
"scratch-render-fonts": "1.0.252",
- "scratch-storage": "6.1.3",
"startaudiocontext": "1.2.1",
"style-loader": "4.0.0",
"text-encoding": "0.7.0",
@@ -42652,6 +42780,7 @@
"@babel/core": "7.28.6",
"@babel/polyfill": "7.12.1",
"@babel/preset-env": "7.28.6",
+ "@scratch/scratch-storage": "12.6.1",
"@scratch/scratch-vm": "12.6.1",
"babel-loader": "9.2.1",
"copy-webpack-plugin": "6.4.1",
@@ -42664,7 +42793,6 @@
"playwright-chromium": "1.58.1",
"scratch-render-fonts": "1.0.252",
"scratch-semantic-release-config": "4.0.1",
- "scratch-storage": "6.1.3",
"scratch-webpack-configuration": "3.1.1",
"semantic-release": "25.0.3",
"tap": "21.5.0",
@@ -42805,6 +42933,159 @@
"node": ">= 4.0.0"
}
},
+ "packages/scratch-storage": {
+ "name": "@scratch/scratch-storage",
+ "version": "12.6.1",
+ "license": "AGPL-3.0-only",
+ "dependencies": {
+ "@babel/runtime": "^7.21.0",
+ "@scratch/task-herder": "12.6.0",
+ "arraybuffer-loader": "^1.0.3",
+ "base64-js": "^1.3.0",
+ "buffer": "6.0.3",
+ "fastestsmallesttextencoderdecoder": "^1.0.7",
+ "js-md5": "^0.7.3",
+ "minilog": "^3.1.0"
+ },
+ "devDependencies": {
+ "@babel/core": "7.28.6",
+ "@babel/plugin-transform-runtime": "7.28.5",
+ "@babel/polyfill": "7.12.1",
+ "@babel/preset-env": "7.28.6",
+ "@types/jest": "29.5.14",
+ "babel-loader": "9.2.1",
+ "eslint": "9.39.2",
+ "eslint-config-scratch": "12.0.49",
+ "file-loader": "6.2.0",
+ "jest": "29.7.0",
+ "json": "10.0.0",
+ "rimraf": "6.1.2",
+ "scratch-semantic-release-config": "4.0.1",
+ "scratch-webpack-configuration": "3.1.1",
+ "semantic-release": "25.0.3",
+ "ts-jest": "29.4.6",
+ "ts-jest-mock-import-meta": "1.3.1",
+ "ts-loader": "9.5.4",
+ "webpack": "5.104.1",
+ "webpack-cli": "5.1.4"
+ }
+ },
+ "packages/scratch-storage/node_modules/@scratch/task-herder": {
+ "version": "12.6.0",
+ "resolved": "https://registry.npmjs.org/@scratch/task-herder/-/task-herder-12.6.0.tgz",
+ "integrity": "sha512-T5sO3GnNan4ffGpkNSq6NcRGQA5AIED7Oujg9kdGVnbGiHVZu8WwsRgwneTOQ99cfeADnLzWQPJpOsNAZBmMng==",
+ "license": "AGPL-3.0-only"
+ },
+ "packages/scratch-storage/node_modules/@types/jest": {
+ "version": "29.5.14",
+ "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz",
+ "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "expect": "^29.0.0",
+ "pretty-format": "^29.0.0"
+ }
+ },
+ "packages/scratch-storage/node_modules/ansi-styles": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "packages/scratch-storage/node_modules/glob": {
+ "version": "13.0.0",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.0.tgz",
+ "integrity": "sha512-tvZgpqk6fz4BaNZ66ZsRaZnbHvP/jG3uKJvAZOwEVUL4RTA5nJeeLYfyN9/VA8NX/V3IBG+hkeuGpKjvELkVhA==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "minimatch": "^10.1.1",
+ "minipass": "^7.1.2",
+ "path-scurry": "^2.0.0"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "packages/scratch-storage/node_modules/minimatch": {
+ "version": "10.1.1",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.1.1.tgz",
+ "integrity": "sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/brace-expansion": "^5.0.0"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "packages/scratch-storage/node_modules/minipass": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
+ "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
+ "packages/scratch-storage/node_modules/pretty-format": {
+ "version": "29.7.0",
+ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz",
+ "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jest/schemas": "^29.6.3",
+ "ansi-styles": "^5.0.0",
+ "react-is": "^18.0.0"
+ },
+ "engines": {
+ "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
+ }
+ },
+ "packages/scratch-storage/node_modules/react-is": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
+ "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "packages/scratch-storage/node_modules/rimraf": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.2.tgz",
+ "integrity": "sha512-cFCkPslJv7BAXJsYlK1dZsbP8/ZNLkCAQ0bi1hf5EKX2QHegmDFEFA6QhuYJlk7UDdc+02JjO80YSOrWPpw06g==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "glob": "^13.0.0",
+ "package-json-from-dist": "^1.0.1"
+ },
+ "bin": {
+ "rimraf": "dist/esm/bin.mjs"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"packages/scratch-svg-renderer": {
"name": "@scratch/scratch-svg-renderer",
"version": "12.6.1",
@@ -42882,6 +43163,7 @@
"license": "AGPL-3.0-only",
"dependencies": {
"@scratch/scratch-render": "12.6.1",
+ "@scratch/scratch-storage": "12.6.1",
"@scratch/scratch-svg-renderer": "12.6.1",
"@vernier/godirect": "1.8.3",
"arraybuffer-loader": "1.0.8",
@@ -42897,7 +43179,6 @@
"scratch-audio": "2.0.268",
"scratch-parser": "6.0.0",
"scratch-sb1-converter": "2.0.279",
- "scratch-storage": "6.1.3",
"scratch-translate-extension-languages": "1.0.7",
"text-encoding": "0.7.0",
"tslog": "4.10.2",
diff --git a/package.json b/package.json
index 736857f1d5c..feab59cf9fd 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"author": "Scratch Foundation",
"workspaces": [
"packages/task-herder",
+ "packages/scratch-storage",
"packages/scratch-svg-renderer",
"packages/scratch-render",
"packages/scratch-vm",
@@ -43,6 +44,7 @@
"globals": "16.5.0",
"husky": "8.0.3",
"npm": "10.9.4",
+ "sort-package-json": "3.6.1",
"ts-node": "10.9.2"
}
}
diff --git a/packages/scratch-gui/package.json b/packages/scratch-gui/package.json
index 529b180570a..6f1208ee350 100644
--- a/packages/scratch-gui/package.json
+++ b/packages/scratch-gui/package.json
@@ -113,6 +113,7 @@
"@microbit/microbit-universal-hex": "0.2.2",
"@radix-ui/react-context-menu": "2.2.16",
"@scratch/scratch-render": "12.6.1",
+ "@scratch/scratch-storage": "12.6.1",
"@scratch/scratch-svg-renderer": "12.6.1",
"@scratch/scratch-vm": "12.6.1",
"@tensorflow-models/face-detection": "1.0.3",
@@ -170,7 +171,6 @@
"scratch-l10n": "6.1.60",
"scratch-paint": "4.1.50",
"scratch-render-fonts": "1.0.252",
- "scratch-storage": "6.1.3",
"startaudiocontext": "1.2.1",
"style-loader": "4.0.0",
"text-encoding": "0.7.0",
diff --git a/packages/scratch-gui/src/gui-config.ts b/packages/scratch-gui/src/gui-config.ts
index 0773972d328..686206da165 100644
--- a/packages/scratch-gui/src/gui-config.ts
+++ b/packages/scratch-gui/src/gui-config.ts
@@ -1,5 +1,5 @@
import PropTypes from 'prop-types';
-import {ScratchStorage} from 'scratch-storage';
+import {ScratchStorage} from '@scratch/scratch-storage';
export type GUIConfigFactory = () => GUIConfig;
export type ProjectId = string | number;
diff --git a/packages/scratch-gui/src/index-standalone.tsx b/packages/scratch-gui/src/index-standalone.tsx
index 2bf3d94f87a..b02913d99df 100644
--- a/packages/scratch-gui/src/index-standalone.tsx
+++ b/packages/scratch-gui/src/index-standalone.tsx
@@ -14,7 +14,7 @@ export {setAppElement} from 'react-modal';
export * from './gui-config';
export * from './exported-reducers';
-export * from 'scratch-storage';
+export * from '@scratch/scratch-storage';
export {default as buildDefaultProject} from './lib/default-project';
diff --git a/packages/scratch-gui/src/lib/legacy-storage.ts b/packages/scratch-gui/src/lib/legacy-storage.ts
index 33cb8ece0ce..71db19f7454 100644
--- a/packages/scratch-gui/src/lib/legacy-storage.ts
+++ b/packages/scratch-gui/src/lib/legacy-storage.ts
@@ -1,4 +1,4 @@
-import {ScratchStorage, Asset} from 'scratch-storage';
+import {ScratchStorage, Asset} from '@scratch/scratch-storage';
import defaultProject from './default-project';
import {GUIStorage, TranslatorFunction} from '../gui-config';
diff --git a/packages/scratch-gui/webpack.config.js b/packages/scratch-gui/webpack.config.js
index 515bbd011ff..d9eecb5e4ef 100644
--- a/packages/scratch-gui/webpack.config.js
+++ b/packages/scratch-gui/webpack.config.js
@@ -87,12 +87,12 @@ const baseConfig = new ScratchWebpackConfigBuilder(
noErrorOnMissing: true
},
{
- context: '../../node_modules/scratch-storage/dist/web',
+ context: '../../node_modules/@scratch/scratch-storage/dist/web',
from: 'chunks/fetch-worker.*.{js,js.map}',
noErrorOnMissing: true
},
{
- context: '../../node_modules/scratch-storage/dist/web',
+ context: '../../node_modules/@scratch/scratch-storage/dist/web',
from: 'chunks/vendors-*.{js,js.map}',
noErrorOnMissing: true
},
diff --git a/packages/scratch-render/package.json b/packages/scratch-render/package.json
index cb5d1196d36..2adec2295e8 100644
--- a/packages/scratch-render/package.json
+++ b/packages/scratch-render/package.json
@@ -67,6 +67,7 @@
"@babel/core": "7.28.6",
"@babel/polyfill": "7.12.1",
"@babel/preset-env": "7.28.6",
+ "@scratch/scratch-storage": "12.6.1",
"@scratch/scratch-vm": "12.6.1",
"babel-loader": "9.2.1",
"copy-webpack-plugin": "6.4.1",
@@ -79,7 +80,6 @@
"playwright-chromium": "1.58.1",
"scratch-render-fonts": "1.0.252",
"scratch-semantic-release-config": "4.0.1",
- "scratch-storage": "6.1.3",
"scratch-webpack-configuration": "3.1.1",
"semantic-release": "25.0.3",
"tap": "21.5.0",
diff --git a/packages/scratch-render/test/integration/cpu-render.html b/packages/scratch-render/test/integration/cpu-render.html
index 2e3192f80c7..49932f81908 100644
--- a/packages/scratch-render/test/integration/cpu-render.html
+++ b/packages/scratch-render/test/integration/cpu-render.html
@@ -1,6 +1,6 @@
-
+
diff --git a/packages/scratch-render/test/integration/index.html b/packages/scratch-render/test/integration/index.html
index 10477380287..c755395fc75 100644
--- a/packages/scratch-render/test/integration/index.html
+++ b/packages/scratch-render/test/integration/index.html
@@ -1,6 +1,6 @@
-
+
diff --git a/packages/scratch-storage/.browserslistrc b/packages/scratch-storage/.browserslistrc
new file mode 100644
index 00000000000..d9edb146a3d
--- /dev/null
+++ b/packages/scratch-storage/.browserslistrc
@@ -0,0 +1,7 @@
+# See https://scratch.mit.edu/faq
+Chrome >= 63
+Edge >= 15
+Firefox >= 57
+Safari >= 11
+Android >= 63
+iOS >= 11
diff --git a/packages/scratch-storage/.editorconfig b/packages/scratch-storage/.editorconfig
new file mode 100644
index 00000000000..c847f6fa405
--- /dev/null
+++ b/packages/scratch-storage/.editorconfig
@@ -0,0 +1,15 @@
+root = true
+
+[*]
+end_of_line = lf
+insert_final_newline = true
+charset = utf-8
+indent_size = 4
+trim_trailing_whitespace = true
+
+[*.json,*.json5]
+indent_style = space
+indent_size = 2
+
+[*.{js}]
+indent_style = space
diff --git a/packages/scratch-storage/.gitattributes b/packages/scratch-storage/.gitattributes
new file mode 100644
index 00000000000..6ebbc296baa
--- /dev/null
+++ b/packages/scratch-storage/.gitattributes
@@ -0,0 +1,29 @@
+# Set the default behavior, in case people don't have core.autocrlf set.
+* text=auto
+
+# Explicitly specify line endings for as many files as possible.
+# People who (for example) rsync between Windows and Linux need this.
+
+# File types which we know are binary
+*.png binary
+*.wav binary
+
+# Prefer LF for most file types
+*.js text eol=lf
+*.js.map text eol=lf
+*.json text eol=lf
+*.json5 text eol=lf
+*.md text eol=lf
+*.svg text eol=lf
+*.yml text eol=lf
+
+# Prefer LF for these files
+.editorconfig text eol=lf
+.eslintignore text eol=lf
+.gitattributes text eol=lf
+.gitignore text eol=lf
+.npmignore text eol=lf
+LICENSE text eol=lf
+TRADEMARK text eol=lf
+
+# Use CRLF for Windows-specific file types
diff --git a/packages/scratch-storage/.github/CODEOWNERS.md b/packages/scratch-storage/.github/CODEOWNERS.md
new file mode 100644
index 00000000000..a905f98fa17
--- /dev/null
+++ b/packages/scratch-storage/.github/CODEOWNERS.md
@@ -0,0 +1 @@
+@scratchfoundation/scratch-engineering
diff --git a/packages/scratch-storage/.github/CONTRIBUTING.md b/packages/scratch-storage/.github/CONTRIBUTING.md
new file mode 100644
index 00000000000..b66180b9fa2
--- /dev/null
+++ b/packages/scratch-storage/.github/CONTRIBUTING.md
@@ -0,0 +1,66 @@
+## Contributing
+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.
+
+### Ways to Help
+
+* **Documenting bugs**
+ * If you've identified a bug in Scratch you should first check to see if it's been filed as an issue, if not you can file one. Make sure you follow the issue template.
+ * It's important that we can consistently reproduce issues. When writing an issue, be sure to follow our [reproduction step guidelines](https://github.com/LLK/scratch-gui/wiki/Writing-good-repro-steps).
+ * Some issues are marked "Needs Repro". Adding a comment with good reproduction steps to those issues is a great way to help.
+ * If you don't have an issue in mind already, you can look through the [Bugs & Glitches forum.](https://scratch.mit.edu/discuss/3/) Look for users reporting problems, reproduce the problem yourself, and file new issues following our guidelines.
+
+* **Fixing bugs**
+ * You can request to fix a bug in a comment on the issue if you at mention the repo coordinator, who for this repo is @cwillisf.
+ * If the issue is marked "Help Wanted" you can go ahead and start working on it!
+ * **We will only accept Pull Requests for bugs that have an issue filed that has a priority label**
+ * If you're interested in fixing a bug with no issue, file the issue first and wait for it to have a priority added to it.
+
+ * We are not looking for Pull Requests ("PR") for every issue and may deny a PR if it doesn't fit our criteria.
+ * We are far more likely to accept a PR if it is for an issue marked with Help Wanted.
+ * We will not accept PRs for issues marked with "Needs Discussion" or "Needs Design."
+ * Wait until the Repo Coordinator assigns the issue to you before you begin work or submit a PR.
+
+### Learning Git and Github
+
+If you want to work on fixing issues, you should be familiar with Git and Github.
+
+* [Learn Git branching](https://learngitbranching.js.org/) includes an introduction to basic git commands and useful branching features.
+* Here's a general introduction to [contributing to an open source project](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github).
+
+**Important:** we follow the [Github Flow process](https://guides.github.com/introduction/flow/) as our development process.
+
+### How to Fix Bugs
+1. Identify which Github issue you are working on. Leave a comment on the issue to let us (and other contributors) know you're working on it.
+2. Make sure you have a fork of this repo (see [Github's forking a repo](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) for details)
+3. Switch to the `develop` branch, and pull down the latest changes from upstream
+4. Run the code, and reproduce the problem
+5. Create your branch from the `develop` branch
+6. Make code changes to fix the problem
+7. Run `npm test` to make sure that your changes pass our tests
+8. Commit your changes
+9. Push your branch to your fork
+10. Create your pull request
+ 1. Make sure to follow the template in the PR description
+ 1. Remember to check the “[Allow edits from maintainers](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork)” box
+
+When submitting pull requests keep in mind:
+* please be patient -- it can take a while to find time to review them
+* try to change the least amount of code necessary to fix the bug
+* the code can't be radically changed without significant coordination with the Scratch Team, so these types of changes should be avoided
+* if you find yourself changing a substantial amount of code or considering radical changes, please ask for clarification -- we may have envisioned a different approach, or underestimated the amount of effort
+
+### Suggestions
+
+
+Please note: **_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. It's been said that the Scratch Team spends about one hour of design discussion for every pixel in Scratch. 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).
+
+We welcome suggestions! If you want to suggest a feature, please post in our [suggestions forum](https://scratch.mit.edu/discuss/1/). Your suggestion will be helped if you include a mockup design; this can be simple, even hand-drawn.
+
+### Other resources
+Beyond this repo, there are also some other resources that you might want to take a look at:
+* [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)
+* [Open Source forum](https://scratch.mit.edu/discuss/49/) on Scratch
+* [Suggestions forum](https://scratch.mit.edu/discuss/1/) on Scratch
+* [Bugs & Glitches forum](https://scratch.mit.edu/discuss/3/) on Scratch
diff --git a/packages/scratch-storage/.github/ISSUE_TEMPLATE.md b/packages/scratch-storage/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 00000000000..38756937c53
--- /dev/null
+++ b/packages/scratch-storage/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,15 @@
+### Expected Behavior
+
+_Please describe what should happen_
+
+### Actual Behavior
+
+_Describe what actually happens_
+
+### Steps to Reproduce
+
+_Explain what someone needs to do in order to see what's described in *Actual behavior* above_
+
+### Operating System and Browser
+
+_e.g. Mac OS 10.11.6 Safari 10.0_
diff --git a/packages/scratch-storage/.github/PULL_REQUEST_TEMPLATE.md b/packages/scratch-storage/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 00000000000..33ff6dfdeed
--- /dev/null
+++ b/packages/scratch-storage/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,15 @@
+### Resolves
+
+_What Github issue does this resolve (please include link)?_
+
+### Proposed Changes
+
+_Describe what this Pull Request does_
+
+### Reason for Changes
+
+_Explain why these changes should be made_
+
+### Test Coverage
+
+_Please show how you have added tests to cover your changes_
diff --git a/packages/scratch-storage/.github/workflows/ci-cd.yml b/packages/scratch-storage/.github/workflows/ci-cd.yml
new file mode 100644
index 00000000000..b0f75f3bca7
--- /dev/null
+++ b/packages/scratch-storage/.github/workflows/ci-cd.yml
@@ -0,0 +1,58 @@
+name: CI/CD
+
+on:
+ workflow_dispatch: # Allows you to run this workflow manually from the Actions tab
+ push: # Runs whenever a commit is pushed to the repository
+
+concurrency:
+ group: "${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}"
+ cancel-in-progress: true
+
+permissions:
+ contents: write # publish a GitHub release
+ pages: write # deploy to GitHub Pages
+ issues: write # comment on released issues
+ pull-requests: write # comment on released pull requests
+
+jobs:
+ ci-cd:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
+
+ - uses: wagoid/commitlint-github-action@5ce82f5d814d4010519d15f0552aec4f17a1e1fe # v5
+ if: github.event_name == 'pull_request'
+
+ - uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6
+ with:
+ cache: "npm"
+ node-version-file: ".nvmrc"
+
+ - name: Info
+ run: |
+ cat <
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+ .
diff --git a/packages/scratch-storage/README.md b/packages/scratch-storage/README.md
new file mode 100644
index 00000000000..2e2012ff8f4
--- /dev/null
+++ b/packages/scratch-storage/README.md
@@ -0,0 +1,154 @@
+## scratch-storage
+#### Scratch Storage is a library for loading and storing project and asset files for Scratch 3.0
+
+[](https://circleci.com/gh/LLK/scratch-storage?branch=develop)
+
+[](https://coveralls.io/github/LLK/scratch-storage?branch=develop)
+[](https://greenkeeper.io/)
+
+## Installation
+This requires you to have Node.js installed.
+
+In your own Node.js environment/application:
+```bash
+npm install https://github.com/scratchfoundation/scratch-storage.git
+```
+
+If you want to edit/play yourself (requires Git):
+```bash
+git clone https://github.com/scratchfoundation/scratch-storage.git
+cd scratch-storage
+npm install
+```
+
+## Using scratch-storage
+
+### From HTML
+
+```html
+
+
+```
+
+### From Node.js / Webpack
+
+```js
+var storage = require('@scratch/scratch-storage');
+// continue to "Storage API Quick Start" section below
+```
+
+### Storage API Quick Start
+
+Once you have an instance of `scratch-storage`, add some web sources. For each source you'll need to provide a function
+to generate a URL for a supported type of asset:
+```js
+/**
+ * @param {Asset} asset - calculate a URL for this asset.
+ * @returns {string} a URL to download a project asset (PNG, WAV, etc.)
+ */
+var getAssetUrl = function (asset) {
+ var assetUrlParts = [
+ 'https://assets.example.com/path/to/assets/',
+ asset.assetId,
+ '.',
+ asset.dataFormat,
+ '/get/'
+ ];
+ return assetUrlParts.join('');
+};
+```
+
+Then, let the storage module know about your source:
+```js
+storage.addWebStore(
+ [AssetType.ImageVector, AssetType.ImageBitmap, AssetType.Sound],
+ getAssetUrl);
+```
+
+If you're using ES6 you may be able to simplify all of the above quite a bit:
+```js
+storage.addWebStore(
+ [AssetType.ImageVector, AssetType.ImageBitmap, AssetType.Sound],
+ asset => `https://assets.example.com/path/to/assets/${asset.assetId}.${asset.dataFormat}/get/`);
+```
+
+Once the storage module is aware of the sources you need, you can start loading assets:
+```js
+storage.load(AssetType.Sound, soundId).then(function (soundAsset) {
+ // `soundAsset` is an `Asset` object. File contents are stored in `soundAsset.data`.
+});
+```
+
+If you'd like to use `scratch-storage` with `scratch-vm` you must "attach" the storage module to the VM:
+```js
+vm.attachStorage(storage);
+```
+
+## Testing
+
+To run all tests:
+```bash
+npm test
+```
+
+To show test coverage:
+```bash
+npm run coverage
+```
+
+## Committing
+This project uses [semantic release](https://github.com/semantic-release/semantic-release)
+to ensure version bumps follow semver so that projects using the config don't
+break unexpectedly.
+
+In order to automatically determine the type of version bump necessary, semantic
+release expects commit messages to be formatted following
+[conventional-changelog](https://github.com/bcoe/conventional-changelog-standard/blob/master/convention.md).
+```
+():
+
+
+
+
+```
+
+`subject` and `body` are your familiar commit subject and body. `footer` is
+where you would include `BREAKING CHANGE` and `ISSUES FIXED` sections if
+applicable.
+
+`type` is one of:
+* `fix`: A bug fix **Causes a patch release (0.0.x)**
+* `feat`: A new feature **Causes a minor release (0.x.0)**
+* `docs`: Documentation only changes
+* `style`: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
+* `refactor`: A code change that neither fixes a bug nor adds a feature
+* `perf`: A code change that improves performance **May or may not cause a minor release. It's not clear.**
+* `test`: Adding missing tests or correcting existing tests
+* `ci`: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
+* `chore`: Other changes that don't modify src or test files
+* `revert`: Reverts a previous commit
+
+Use the [commitizen CLI](https://github.com/commitizen/cz-cli) to make commits
+formatted in this way:
+
+```bash
+npm install -g commitizen
+npm install
+```
+
+Now you're ready to make commits using `git cz`.
+
+## Breaking changes
+If you're committing a change that makes an API change, or will
+otherwise require changes to existing code, ensure your commit specifies a
+breaking change. In your commit body, prefix the changes with "BREAKING CHANGE: "
+This will cause a major version bump so downstream projects must choose to upgrade
+and will not break the build unexpectedly.
+
+## Donate
+We provide [Scratch](https://scratch.mit.edu) free of charge, and want to keep it that way! Please consider making a
+[donation](https://secure.donationpay.org/scratchfoundation/) to support our continued engineering, design, community,
+and resource development efforts. Donations of any size are appreciated. Thank you!
diff --git a/packages/scratch-storage/TRADEMARK b/packages/scratch-storage/TRADEMARK
new file mode 100644
index 00000000000..17b5d4c919c
--- /dev/null
+++ b/packages/scratch-storage/TRADEMARK
@@ -0,0 +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.
diff --git a/packages/scratch-storage/commitlint.config.js b/packages/scratch-storage/commitlint.config.js
new file mode 100644
index 00000000000..d89185ea291
--- /dev/null
+++ b/packages/scratch-storage/commitlint.config.js
@@ -0,0 +1,4 @@
+module.exports = {
+ extends: ['@commitlint/config-conventional'],
+ ignores: [message => message.startsWith('chore(release):')]
+};
diff --git a/packages/scratch-storage/eslint.config.mjs b/packages/scratch-storage/eslint.config.mjs
new file mode 100644
index 00000000000..d9c4232a4e5
--- /dev/null
+++ b/packages/scratch-storage/eslint.config.mjs
@@ -0,0 +1,47 @@
+import {eslintConfigScratch} from 'eslint-config-scratch';
+import {globalIgnores} from 'eslint/config';
+import globals from 'globals';
+
+export default eslintConfigScratch.defineConfig(
+ eslintConfigScratch.legacy.base,
+ {
+ files: [
+ '*.{js,cjs,mjs,ts}' // for example, webpack.config.js
+ ],
+ extends: [eslintConfigScratch.legacy.node]
+ },
+ {
+ files: ['src/**/*.{js,cjs,mjs,jsx,ts,tsx}'],
+ extends: [
+ eslintConfigScratch.legacy.es6,
+ eslintConfigScratch.legacy.typescript
+ ],
+ languageOptions: {
+ globals: globals.node
+ },
+ rules: {
+ // TODO: Enable these rules after fixing existing violations. This will change the API!
+ '@typescript-eslint/no-redeclare': 'off', // allow types and values with the same name
+ '@typescript-eslint/prefer-promise-reject-errors': 'off' // allow rejecting with non-Error values
+ }
+ },
+ {
+ files: ['test/**/*.{js,cjs,mjs,jsx,ts,tsx}'],
+ extends: [
+ eslintConfigScratch.legacy.es6
+ ],
+ languageOptions: {
+ globals: {
+ ...globals.jest,
+ ...globals.node
+ }
+ },
+ rules: {
+ 'no-console': 'off'
+ }
+ },
+ globalIgnores([
+ 'dist/**',
+ 'node_modules/**'
+ ])
+);
diff --git a/packages/scratch-storage/jest.config.js b/packages/scratch-storage/jest.config.js
new file mode 100644
index 00000000000..12257f5ae00
--- /dev/null
+++ b/packages/scratch-storage/jest.config.js
@@ -0,0 +1,37 @@
+const {createDefaultEsmPreset} = require('ts-jest');
+
+/** @type {import('ts-jest').JestConfigWithTsJest} */
+module.exports = {
+ moduleNameMapper: {
+ // Allows jest to find the asset files, otherwise it looks for them with the
+ // `?arrayBuffer` as part of the name and doesn't end up transforming them.
+ '^(.+)\\?arrayBuffer$': '$1'
+ },
+ moduleFileExtensions: ['ts', 'js'],
+ transform: {
+ ...createDefaultEsmPreset({
+ tsconfig: 'tsconfig.test.json',
+
+ // The webpack 5 way to include web workers is to use
+ // `new Worker(new URL('./worker.js', import.meta.url));`.
+ // See https://webpack.js.org/guides/web-workers/
+ // However, the `import.meta.url` is ESM-only and Jest's support for ESM is
+ // still experimental. So, we need to mock it instead (or use experimental
+ // jest & node features).
+ //
+ // Also see https://www.npmjs.com/package/ts-jest-mock-import-meta
+ diagnostics: {
+ ignoreCodes: [1343]
+ },
+ astTransformers: {
+ before: [
+ {
+ path: 'ts-jest-mock-import-meta',
+ options: {metaObjectReplacement: {url: 'https://example.com'}}
+ }
+ ]
+ }
+ }).transform,
+ '\\.(png|svg|wav)$': '/test/transformers/arraybuffer-loader.js'
+ }
+};
diff --git a/packages/scratch-storage/package.json b/packages/scratch-storage/package.json
new file mode 100644
index 00000000000..75a0a51f92e
--- /dev/null
+++ b/packages/scratch-storage/package.json
@@ -0,0 +1,73 @@
+{
+ "name": "@scratch/scratch-storage",
+ "version": "12.6.1",
+ "description": "Load and store project and asset files for Scratch 3.0",
+ "keywords": [],
+ "homepage": "https://github.com/scratchfoundation/scratch-storage#readme",
+ "bugs": {
+ "url": "https://github.com/scratchfoundation/scratch-storage/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/scratchfoundation/scratch-storage.git"
+ },
+ "license": "AGPL-3.0-only",
+ "author": "Scratch Foundation",
+ "main": "./dist/node/scratch-storage.js",
+ "browser": "./dist/web/scratch-storage.js",
+ "types": "./dist/types/index.d.ts",
+ "directories": {
+ "test": "test"
+ },
+ "scripts": {
+ "build": "npm run clean && webpack --mode=production",
+ "clean": "rimraf dist",
+ "commitmsg": "commitlint -e $GIT_PARAMS",
+ "coverage": "tap ./test/{unit,integration}/*.js --coverage --coverage-report=lcov",
+ "prepare": "husky",
+ "semantic-release": "semantic-release",
+ "test": "npm run test:lint && jest \"test[\\\\/](unit|integration)\"",
+ "test:build": "jest \"test[\\\\/]build\"",
+ "test:clearCache": "jest --clearCache",
+ "test:integration": "jest \"test[\\\\/]integration\"",
+ "test:lint": "eslint",
+ "test:unit": "jest \"test[\\\\/]unit\"",
+ "version": "json -f package.json -I -e \"this.repository.sha = '$(git log -n1 --pretty=format:%H)'\"",
+ "watch": "webpack --watch"
+ },
+ "tap": {
+ "check-coverage": false
+ },
+ "dependencies": {
+ "@babel/runtime": "^7.21.0",
+ "@scratch/task-herder": "12.6.0",
+ "arraybuffer-loader": "^1.0.3",
+ "base64-js": "^1.3.0",
+ "buffer": "6.0.3",
+ "fastestsmallesttextencoderdecoder": "^1.0.7",
+ "js-md5": "^0.7.3",
+ "minilog": "^3.1.0"
+ },
+ "devDependencies": {
+ "@babel/core": "7.28.6",
+ "@babel/plugin-transform-runtime": "7.28.5",
+ "@babel/polyfill": "7.12.1",
+ "@babel/preset-env": "7.28.6",
+ "@types/jest": "29.5.14",
+ "babel-loader": "9.2.1",
+ "eslint": "9.39.2",
+ "eslint-config-scratch": "12.0.49",
+ "file-loader": "6.2.0",
+ "jest": "29.7.0",
+ "json": "10.0.0",
+ "rimraf": "6.1.2",
+ "scratch-semantic-release-config": "4.0.1",
+ "scratch-webpack-configuration": "3.1.1",
+ "semantic-release": "25.0.3",
+ "ts-jest": "29.4.6",
+ "ts-jest-mock-import-meta": "1.3.1",
+ "ts-loader": "9.5.4",
+ "webpack": "5.104.1",
+ "webpack-cli": "5.1.4"
+ }
+}
diff --git a/packages/scratch-storage/release.config.js b/packages/scratch-storage/release.config.js
new file mode 100644
index 00000000000..cac550fe27d
--- /dev/null
+++ b/packages/scratch-storage/release.config.js
@@ -0,0 +1,14 @@
+module.exports = {
+ extends: 'scratch-semantic-release-config',
+ branches: [
+ {
+ name: 'develop'
+ // default channel
+ },
+ {
+ name: 'hotfix/*',
+ channel: 'hotfix',
+ prerelease: 'hotfix'
+ }
+ ]
+};
diff --git a/packages/scratch-storage/src/Asset.ts b/packages/scratch-storage/src/Asset.ts
new file mode 100644
index 00000000000..d71d517227e
--- /dev/null
+++ b/packages/scratch-storage/src/Asset.ts
@@ -0,0 +1,100 @@
+import md5 from 'js-md5';
+import {memoizedToString, _TextEncoder, _TextDecoder} from './memoizedToString';
+import {AssetType} from './AssetType';
+import {DataFormat} from './DataFormat';
+
+// TODO: The comments in this file indicate that the asset id is a string only, but
+// the types in BuiltinHelper and the default project builder in scratch-gui
+// allow for it to be a number as well.
+export type AssetId = string | number;
+
+// Projects are strings, other assets are byte arrays
+export type AssetData = string | Uint8Array;
+
+export default class Asset {
+ public assetType: AssetType;
+ public assetId?: AssetId;
+ public data?: AssetData;
+ public dataFormat?: DataFormat;
+ public dependencies: Asset[];
+ public clean?: boolean;
+
+ /**
+ * Construct an Asset.
+ * @param {AssetType} assetType - The type of this asset (sound, image, etc.)
+ * @param {string} assetId - The ID of this asset.
+ * @param {DataFormat} [dataFormat] - The format of the data (WAV, PNG, etc.); required iff `data` is present.
+ * @param {Buffer} [data] - The in-memory data for this asset; optional.
+ * @param {boolean} [generateId] - Whether to create id from an md5 hash of data
+ */
+ constructor (
+ assetType: AssetType,
+ assetId?: AssetId,
+ dataFormat?: DataFormat,
+ data?: AssetData,
+ generateId?: boolean
+ ) {
+ /** @type {AssetType} */
+ this.assetType = assetType;
+
+ /** @type {string} */
+ this.assetId = assetId;
+
+ this.setData(data, dataFormat || assetType.runtimeFormat, generateId);
+
+ /** @type {Asset[]} */
+ this.dependencies = [];
+ }
+
+ setData (data: AssetData | undefined, dataFormat: DataFormat | undefined, generateId?: boolean) {
+ if (data && !dataFormat) {
+ throw new Error('Data provided without specifying its format');
+ }
+
+ /** @type {DataFormat} */
+ this.dataFormat = dataFormat;
+
+ /** @type {Buffer} */
+ this.data = data;
+
+ if (generateId) this.assetId = md5(data);
+
+ // Mark as clean only if set is being called without generateId
+ // If a new id is being generated, mark this asset as not clean
+ this.clean = !generateId;
+ }
+
+ /**
+ * @returns {string} - This asset's data, decoded as text.
+ */
+ decodeText (): string {
+ const decoder = new _TextDecoder();
+
+ // The data may be string, but it seems like this function is only called if the data is a byte array?
+ // This was the behavior of the code when we added TS
+ return decoder.decode(this.data as Uint8Array);
+ }
+
+ /**
+ * Same as `setData` but encodes text first.
+ * @param {string} data - the text data to encode and store.
+ * @param {DataFormat} dataFormat - the format of the data (DataFormat.SVG for example).
+ * @param {boolean} generateId - after setting data, set the id to an md5 of the data?
+ */
+ encodeTextData (data: string, dataFormat: DataFormat, generateId: boolean): void {
+ const encoder = new _TextEncoder();
+ this.setData(encoder.encode(data), dataFormat, generateId);
+ }
+
+ /**
+ * @param {string} [contentType] - Optionally override the content type to be included in the data URI.
+ * @returns {string} - A data URI representing the asset's data.
+ */
+ encodeDataURI (contentType: string): string {
+ contentType = contentType || this.assetType.contentType;
+
+ // The data may be string, but it seems like this function is only called if the data is a byte array?
+ // This was the behavior of the code when we added TS
+ return `data:${contentType};base64,${memoizedToString(this.assetId!, this.data as Uint8Array)}`;
+ }
+}
diff --git a/packages/scratch-storage/src/AssetType.ts b/packages/scratch-storage/src/AssetType.ts
new file mode 100644
index 00000000000..de2f6160cfa
--- /dev/null
+++ b/packages/scratch-storage/src/AssetType.ts
@@ -0,0 +1,51 @@
+import {DataFormat} from './DataFormat';
+
+export interface AssetType {
+ contentType: string,
+ name: string,
+ runtimeFormat: DataFormat,
+ immutable: boolean
+}
+
+/**
+ * Enumeration of the supported asset types.
+ * @type {{[assetTypeName: string]: AssetType}}
+ * @typedef {object} AssetType - Information about a supported asset type.
+ * @property {string} contentType - the MIME type associated with this kind of data. Useful for data URIs, etc.
+ * @property {string} name - The human-readable name of this asset type.
+ * @property {DataFormat} runtimeFormat - The default format used for runtime, in-memory storage of this asset. For
+ * example, a project stored in SB2 format on disk will be returned as JSON when loaded into memory.
+ * @property {boolean} immutable - Indicates if the asset id is determined by the asset content.
+ */
+export const AssetType = {
+ ImageBitmap: {
+ contentType: 'image/png',
+ name: 'ImageBitmap',
+ runtimeFormat: DataFormat.PNG,
+ immutable: true
+ },
+ ImageVector: {
+ contentType: 'image/svg+xml',
+ name: 'ImageVector',
+ runtimeFormat: DataFormat.SVG,
+ immutable: true
+ },
+ Project: {
+ contentType: 'application/json',
+ name: 'Project',
+ runtimeFormat: DataFormat.JSON,
+ immutable: false
+ },
+ Sound: {
+ contentType: 'audio/x-wav',
+ name: 'Sound',
+ runtimeFormat: DataFormat.WAV,
+ immutable: true
+ },
+ Sprite: {
+ contentType: 'application/json',
+ name: 'Sprite',
+ runtimeFormat: DataFormat.JSON,
+ immutable: true
+ }
+} as const;
diff --git a/packages/scratch-storage/src/BuiltinHelper.ts b/packages/scratch-storage/src/BuiltinHelper.ts
new file mode 100644
index 00000000000..7d83d21f289
--- /dev/null
+++ b/packages/scratch-storage/src/BuiltinHelper.ts
@@ -0,0 +1,176 @@
+import md5 from 'js-md5';
+
+import log from './log';
+
+import Asset, {AssetData, AssetId} from './Asset';
+import {AssetType} from './AssetType';
+import {DataFormat} from './DataFormat';
+import Helper from './Helper';
+
+import defaultImageBitmap from './builtins/defaultBitmap.png?arrayBuffer';
+import defaultSound from './builtins/defaultSound.wav?arrayBuffer';
+import defaultImageVector from './builtins/defaultVector.svg?arrayBuffer';
+
+import {Buffer} from 'buffer/';
+import {ScratchStorage} from './ScratchStorage';
+
+/**
+ * @typedef {object} BuiltinAssetRecord
+ * @property {AssetType} type - The type of the asset.
+ * @property {DataFormat} format - The format of the asset's data.
+ * @property {?string} id - The asset's unique ID.
+ * @property {Buffer} data - The asset's data.
+ */
+
+interface BuiltinAssetRecord {
+ type: AssetType,
+ format: DataFormat,
+ id: AssetId | null,
+ data: AssetData
+}
+
+/**
+ * @type {BuiltinAssetRecord[]}
+ */
+const DefaultAssets: BuiltinAssetRecord[] = [
+ {
+ type: AssetType.ImageBitmap,
+ format: DataFormat.PNG,
+ id: null,
+ data: Buffer.from(defaultImageBitmap)
+ },
+ {
+ type: AssetType.Sound,
+ format: DataFormat.WAV,
+ id: null,
+ data: Buffer.from(defaultSound)
+ },
+ {
+ type: AssetType.ImageVector,
+ format: DataFormat.SVG,
+ id: null,
+ data: Buffer.from(defaultImageVector)
+ }
+];
+
+/**
+ * @type {BuiltinAssetRecord[]}
+ */
+const BuiltinAssets = DefaultAssets.concat([
+]);
+
+export default class BuiltinHelper extends Helper {
+ public assets: Record;
+
+ constructor (parent: ScratchStorage) {
+ super(parent);
+
+ /**
+ * In-memory storage for all built-in assets.
+ * @type {{[assetType: string]: AssetIdMap}} Maps asset type to a map of asset ID to actual assets.
+ * @typedef {{[id: string]: BuiltinAssetRecord}} AssetIdMap - Maps asset ID to asset.
+ */
+ this.assets = {};
+
+ BuiltinAssets.forEach(assetRecord => {
+ assetRecord.id = this._store(assetRecord.type, assetRecord.format, assetRecord.data, assetRecord.id);
+ });
+ }
+
+ /**
+ * Call `setDefaultAssetId` on the parent `ScratchStorage` instance to register all built-in default assets.
+ */
+ registerDefaultAssets (): void {
+ const numAssets = DefaultAssets.length;
+ for (let assetIndex = 0; assetIndex < numAssets; ++assetIndex) {
+ const assetRecord = DefaultAssets[assetIndex];
+ this.parent.setDefaultAssetId(assetRecord.type, assetRecord.id!);
+ }
+ }
+
+
+ /**
+ * Synchronously fetch a cached asset for a given asset id. Returns null if not found.
+ * @param {string} assetId - The id for the asset to fetch.
+ * @returns {?Asset} The asset for assetId, if it exists.
+ */
+ get (assetId: AssetId): Asset | null {
+ let asset: Asset | null = null;
+ if (Object.prototype.hasOwnProperty.call(this.assets, assetId)) {
+ /** @type {BuiltinAssetRecord} */
+ const assetRecord = this.assets[assetId];
+ asset = new Asset(assetRecord.type, assetRecord.id!, assetRecord.format, assetRecord.data);
+ }
+ return asset;
+ }
+
+ /**
+ * Alias for store (old name of store)
+ * @deprecated Use BuiltinHelper.store
+ * @param {AssetType} assetType - The type of the asset to cache.
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
+ * @param {Buffer} data - The data for the cached asset.
+ * @param {string} id - The id for the cached asset.
+ * @returns {string} The calculated id of the cached asset, or the supplied id if the asset is mutable.
+ */
+ cache (assetType: AssetType, dataFormat: DataFormat, data: AssetData, id: AssetId): AssetId {
+ log.warn('Deprecation: BuiltinHelper.cache has been replaced with BuiltinHelper.store.');
+ return this.store(assetType, dataFormat, data, id);
+ }
+
+ /**
+ * Deprecated external API for _store
+ * @deprecated Not for external use. Create assets and keep track of them outside of the storage instance.
+ * @param {AssetType} assetType - The type of the asset to cache.
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
+ * @param {Buffer} data - The data for the cached asset.
+ * @param {(string|number)} id - The id for the cached asset.
+ * @returns {string} The calculated id of the cached asset, or the supplied id if the asset is mutable.
+ */
+ store (assetType: AssetType, dataFormat: DataFormat, data: AssetData, id: AssetId): AssetId {
+ log.warn('Deprecation: use Storage.createAsset. BuiltinHelper is for internal use only.');
+ return this._store(assetType, dataFormat, data, id);
+ }
+
+ /**
+ * Cache an asset for future lookups by ID.
+ * @param {AssetType} assetType - The type of the asset to cache.
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
+ * @param {Buffer} data - The data for the cached asset.
+ * @param {(string|number)} id - The id for the cached asset.
+ * @returns {string} The calculated id of the cached asset, or the supplied id if the asset is mutable.
+ */
+ _store (assetType: AssetType, dataFormat: DataFormat, data: AssetData, id?: AssetId | null): AssetId {
+ let assetId = id;
+ if (!dataFormat) throw new Error('Data cached without specifying its format');
+ if (assetId !== '' && assetId !== null && typeof assetId !== 'undefined') {
+ if (Object.prototype.hasOwnProperty.call(this.assets, assetId) && assetType.immutable) return assetId;
+ } else if (assetType.immutable) {
+ assetId = md5(data);
+ } else {
+ throw new Error('Tried to cache data without an id');
+ }
+ this.assets[assetId!] = {
+ type: assetType,
+ format: dataFormat,
+ id: assetId!,
+ data: data
+ };
+ return assetId!;
+ }
+
+ /**
+ * Fetch an asset but don't process dependencies.
+ * @param {AssetType} assetType - The type of asset to fetch.
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
+ * @returns {?Promise.} A promise for the contents of the asset.
+ */
+ load (assetType: AssetType, assetId: AssetId): Promise | null {
+ if (!this.get(assetId)) {
+ // Return null immediately so Storage can quickly move to trying the
+ // next helper.
+ return null;
+ }
+ return Promise.resolve(this.get(assetId));
+ }
+}
diff --git a/packages/scratch-storage/src/DataFormat.ts b/packages/scratch-storage/src/DataFormat.ts
new file mode 100644
index 00000000000..2ec3d42c961
--- /dev/null
+++ b/packages/scratch-storage/src/DataFormat.ts
@@ -0,0 +1,16 @@
+/**
+ * Enumeration of the supported data formats.
+ * @enum {string}
+ */
+export const DataFormat = {
+ JPG: 'jpg',
+ JSON: 'json',
+ MP3: 'mp3',
+ PNG: 'png',
+ SB2: 'sb2',
+ SB3: 'sb3',
+ SVG: 'svg',
+ WAV: 'wav'
+} as const;
+
+export type DataFormat = typeof DataFormat[keyof typeof DataFormat];
diff --git a/packages/scratch-storage/src/FetchTool.ts b/packages/scratch-storage/src/FetchTool.ts
new file mode 100644
index 00000000000..61d097e756e
--- /dev/null
+++ b/packages/scratch-storage/src/FetchTool.ts
@@ -0,0 +1,59 @@
+import {AssetQueueOptions} from './HostQueues';
+import {scratchFetch} from './scratchFetch';
+import {ScratchGetRequest, ScratchSendRequest, Tool} from './Tool';
+
+/**
+ * @typedef {Request & {withCredentials: boolean}} ScratchSendRequest
+ */
+
+/**
+ * Get and send assets with the fetch standard web api.
+ */
+export class FetchTool implements Tool {
+ /**
+ * Is get supported?
+ * Always true for `FetchTool` because `scratchFetch` ponyfills `fetch` if necessary.
+ * @returns {boolean} Is get supported?
+ */
+ get isGetSupported (): boolean {
+ return true;
+ }
+
+ /**
+ * Request data from a server with fetch.
+ * @param {Request} reqConfig - Request configuration for data to get.
+ * @returns {Promise.} Resolve to Buffer of data from server.
+ */
+ get ({url, ...options}: ScratchGetRequest): Promise {
+ return scratchFetch(url, Object.assign({method: 'GET'}, options), {queueOptions: AssetQueueOptions})
+ .then((result: Response) => {
+ if (result.ok) return result.arrayBuffer().then(b => new Uint8Array(b));
+ if (result.status === 404) return null;
+ return Promise.reject(result.status); // TODO: we should throw a proper error
+ });
+ }
+
+ /**
+ * Is sending supported?
+ * Always true for `FetchTool` because `scratchFetch` ponyfills `fetch` if necessary.
+ * @returns {boolean} Is sending supported?
+ */
+ get isSendSupported (): boolean {
+ return true;
+ }
+
+ /**
+ * Send data to a server with fetch.
+ * @param {ScratchSendRequest} reqConfig - Request configuration for data to send.
+ * @returns {Promise.} Server returned metadata.
+ */
+ send ({url, withCredentials = false, ...options}: ScratchSendRequest): Promise {
+ return scratchFetch(url, Object.assign({
+ credentials: withCredentials ? 'include' : 'omit'
+ }, options), {queueOptions: AssetQueueOptions})
+ .then(response => {
+ if (response.ok) return response.text();
+ return Promise.reject(response.status);
+ });
+ }
+}
diff --git a/packages/scratch-storage/src/FetchWorkerTool.ts b/packages/scratch-storage/src/FetchWorkerTool.ts
new file mode 100644
index 00000000000..b7d42301d76
--- /dev/null
+++ b/packages/scratch-storage/src/FetchWorkerTool.ts
@@ -0,0 +1,217 @@
+import {Headers, applyMetadata} from './scratchFetch';
+import {ScratchGetRequest, Tool} from './Tool';
+
+interface DeferredJob {
+ id: string,
+ resolve: (buffer: ArrayBuffer) => void;
+ reject: (error: unknown) => void;
+}
+
+/**
+ * Get and send assets with a worker that uses fetch.
+ */
+class PrivateFetchWorkerTool implements Tool {
+ private _workerSupport: {fetch: boolean};
+ private _supportError: unknown;
+ private worker: Worker | null;
+ private jobs: Record;
+
+ constructor () {
+ /**
+ * What does the worker support of the APIs we need?
+ * @type {{fetch:boolean}}
+ */
+ this._workerSupport = {
+ fetch: typeof fetch !== 'undefined'
+ };
+
+ /**
+ * A possible error occurred standing up the worker.
+ * @type {Error?}
+ */
+ this._supportError = null;
+
+ /**
+ * The worker that runs fetch and returns data for us.
+ * @type {Worker?}
+ */
+ this.worker = null;
+
+ /**
+ * A map of ids to fetch job objects.
+ * @type {object}
+ */
+ this.jobs = {};
+
+ try {
+ if (this.isGetSupported) {
+ // Yes, this is a browser API and we've specified `browser: false` in the eslint env,
+ // but `isGetSupported` checks for the presence of Worker and uses it only if present.
+ // Also see https://webpack.js.org/guides/web-workers/
+ const worker = new Worker(
+ /* webpackChunkName: "fetch-worker" */ new URL('./FetchWorkerTool.worker', import.meta.url)
+ );
+
+ worker.addEventListener('message', ({data}) => {
+ if (data.support) {
+ this._workerSupport = data.support;
+ return;
+ }
+ for (const message of data) {
+ const job = this.jobs[message.id];
+ if (job) {
+ if (message.error) {
+ job.reject(message.error);
+ } else {
+ job.resolve(message.buffer);
+ }
+ delete this.jobs[message.id];
+ }
+ }
+ });
+
+ this.worker = worker;
+ }
+ } catch (error) {
+ this._supportError = error;
+ }
+ }
+
+ /**
+ * Is get supported?
+ *
+ * false if the environment does not workers, fetch, or fetch from inside a
+ * worker. Finding out the worker supports fetch is asynchronous and will
+ * guess that it does if the window does until the worker can inform us.
+ * @returns {boolean} Is get supported?
+ */
+ get isGetSupported (): boolean {
+ return (
+ typeof Worker !== 'undefined' &&
+ this._workerSupport.fetch &&
+ !this._supportError
+ );
+ }
+
+ /**
+ * Request data from a server with a worker using fetch.
+ * @param {{url:string}} reqConfig - Request configuration for data to get.
+ * @param {{method:string}} options - Additional options to configure fetch.
+ * @returns {Promise.} Resolve to Buffer of data from server.
+ */
+ get ({url, ...options}: ScratchGetRequest): Promise {
+ const worker = this.worker;
+
+ if (!worker) {
+ return Promise.reject(new Error('The worker could not be initialized'));
+ }
+
+ return new Promise((resolve, reject) => {
+ // TODO: Use a Scratch standard ID generator ...
+ const id = Math.random().toString(16)
+ .substring(2);
+ const augmentedOptions = applyMetadata(
+ Object.assign({method: 'GET'}, options)
+ );
+ // the Fetch spec says options.headers could be:
+ // "A Headers object, an object literal, or an array of two-item arrays to set request's headers."
+ // structured clone (postMessage) doesn't support Headers objects
+ // so turn it into an array of two-item arrays to make it to the worker intact
+ if (augmentedOptions && augmentedOptions.headers instanceof Headers) {
+ augmentedOptions.headers = Array.from(augmentedOptions.headers.entries());
+ }
+
+ worker.postMessage({
+ id,
+ url,
+ options: augmentedOptions
+ });
+ this.jobs[id] = {
+ id,
+ resolve,
+ reject
+ };
+ })
+ /* eslint no-confusing-arrow: ["error", {"allowParens": true}] */
+ .then(body => (body ? new Uint8Array(body) : null));
+ }
+
+ /**
+ * Is sending supported? always false for FetchWorkerTool.
+ * @returns {boolean} Is sending supported?
+ */
+ get isSendSupported (): boolean {
+ return false;
+ }
+
+ /**
+ * Send data to a server.
+ * @throws {Error} A not implemented error.
+ */
+ send (): never {
+ throw new Error('Not implemented.');
+ }
+
+ private static _instance?: PrivateFetchWorkerTool;
+
+ /**
+ * Return a static PrivateFetchWorkerTool instance on demand.
+ * @returns {PrivateFetchWorkerTool} A static PrivateFetchWorkerTool
+ * instance
+ */
+ static get instance () {
+ if (!this._instance) {
+ this._instance = new PrivateFetchWorkerTool();
+ }
+ return this._instance;
+ }
+}
+
+/**
+ * Get and send assets with a worker that uses fetch.
+ */
+export default class PublicFetchWorkerTool {
+ private inner: PrivateFetchWorkerTool;
+
+ constructor () {
+ /**
+ * Shared instance of an internal worker. PublicFetchWorkerTool proxies
+ * it.
+ * @type {PrivateFetchWorkerTool}
+ */
+ this.inner = PrivateFetchWorkerTool.instance;
+ }
+
+ /**
+ * Is get supported?
+ * @returns {boolean} Is get supported?
+ */
+ get isGetSupported (): boolean {
+ return this.inner.isGetSupported;
+ }
+
+ /**
+ * Request data from a server with a worker that uses fetch.
+ * @param {{url:string}} reqConfig - Request configuration for data to get.
+ * @returns {Promise.} Resolve to Buffer of data from server.
+ */
+ get (reqConfig: ScratchGetRequest): Promise {
+ return this.inner.get(reqConfig);
+ }
+
+ /**
+ * Is sending supported?
+ * @returns {boolean} Is sending supported?
+ */
+ get isSendSupported (): boolean {
+ return false;
+ }
+
+ /**
+ * Send data to a server with a worker that uses fetch.
+ * @throws {Error} A not implemented error.
+ */
+ send (): never {
+ throw new Error('Not implemented.');
+ }
+}
diff --git a/packages/scratch-storage/src/FetchWorkerTool.worker.ts b/packages/scratch-storage/src/FetchWorkerTool.worker.ts
new file mode 100644
index 00000000000..9825c87f7de
--- /dev/null
+++ b/packages/scratch-storage/src/FetchWorkerTool.worker.ts
@@ -0,0 +1,94 @@
+/* eslint-env worker */
+/* eslint-disable-next-line spaced-comment */
+///
+
+// This worker won't share the same queue as the main thread, but throttling should be okay
+// as long as we don't use FetchTool and FetchWorkerTool at the same time.
+// TODO: Communicate metadata from the main thread to workers or move the worker boundary "into" `scratchFetch`.
+// Make sure to benchmark any changes to avoid performance regressions, especially for large project loads.
+import {AssetQueueOptions} from './HostQueues';
+import {scratchFetch} from './scratchFetch';
+
+interface JobMessage {
+ id: string;
+ url: string;
+ options: RequestInit | undefined;
+}
+
+interface CompletionMessage {
+ id: string;
+ buffer?: ArrayBuffer | null;
+ error?: string;
+}
+
+let jobsActive = 0;
+const complete: CompletionMessage[] = [];
+
+let intervalId: ReturnType | undefined = void 0;
+
+/**
+ * Register a step function.
+ *
+ * Step checks if there are completed jobs and if there are sends them to the
+ * parent. Then it checks the jobs count. If there are no further jobs, clear
+ * the step.
+ */
+const registerStep = function () {
+ intervalId = setInterval(() => {
+ if (complete.length) {
+ // Send our chunk of completed requests and instruct postMessage to
+ // transfer the buffers instead of copying them.
+ postMessage(
+ complete.slice(),
+ // Instruct postMessage that these buffers in the sent message
+ // should use their Transferable trait. After the postMessage
+ // call the "buffers" will still be in complete if you looked,
+ // but they will all be length 0 as the data they reference has
+ // been sent to the window. This lets us send a lot of data
+ // without the normal postMessage behaviour of making a copy of
+ // all of the data for the window.
+ complete.map(response => response.buffer).filter(Boolean) as Transferable[]
+ );
+ complete.length = 0;
+ }
+ if (jobsActive === 0) {
+ clearInterval(intervalId);
+ intervalId = void 0;
+ }
+ }, 1);
+};
+
+/**
+ * Receive a job from the parent and fetch the requested data.
+ * @param message The message from the parent.
+ * @param message.data A job id, url, and options descriptor to perform.
+ */
+const onMessage = async ({data: job}: MessageEvent) => {
+ if (jobsActive === 0 && !intervalId) {
+ registerStep();
+ }
+
+ jobsActive++;
+
+ try {
+ const response = await scratchFetch(job.url, job.options, {queueOptions: AssetQueueOptions});
+
+ const result: CompletionMessage = {id: job.id};
+ if (response.ok) {
+ result.buffer = await response.arrayBuffer();
+ } else if (response.status === 404) {
+ result.buffer = null;
+ } else {
+ throw response.status;
+ }
+ complete.push(result);
+ } catch (error) {
+ complete.push({id: job.id, error: ((error as Error)?.message) || `Failed request: ${job.url}`});
+ } finally {
+ jobsActive--;
+ }
+};
+
+// "fetch" is supported in Node.js as of 16.15 and our target browsers as of ~2017
+postMessage({support: {fetch: true}});
+self.addEventListener('message', onMessage);
diff --git a/packages/scratch-storage/src/Helper.ts b/packages/scratch-storage/src/Helper.ts
new file mode 100644
index 00000000000..e82520b9cd1
--- /dev/null
+++ b/packages/scratch-storage/src/Helper.ts
@@ -0,0 +1,27 @@
+import Asset, {AssetId} from './Asset';
+import {AssetType} from './AssetType';
+import {DataFormat} from './DataFormat';
+import {ScratchStorage} from './ScratchStorage';
+
+/**
+ * Base class for asset load/save helpers.
+ * @abstract
+ */
+export default class Helper {
+ public parent!: ScratchStorage;
+
+ constructor (parent: ScratchStorage) {
+ this.parent = parent;
+ }
+
+ /**
+ * Fetch an asset but don't process dependencies.
+ * @param {AssetType} assetType - The type of asset to fetch.
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
+ * @param {DataFormat} dataFormat - The file format / file extension of the asset to fetch: PNG, JPG, etc.
+ * @returns {Promise.} A promise for the contents of the asset.
+ */
+ load (assetType: AssetType, assetId: AssetId, dataFormat: DataFormat): Promise | null {
+ return Promise.reject(new Error(`No asset of type ${assetType} for ID ${assetId} with format ${dataFormat}`));
+ }
+}
diff --git a/packages/scratch-storage/src/HostQueues.ts b/packages/scratch-storage/src/HostQueues.ts
new file mode 100644
index 00000000000..7000c6db490
--- /dev/null
+++ b/packages/scratch-storage/src/HostQueues.ts
@@ -0,0 +1,33 @@
+import {QueueManager, type QueueOptions} from '@scratch/task-herder';
+
+/**
+ * @summary A set of generous limits, for things like downloading assets from CDN.
+ * @description
+ * In practice, these limits seem to lead to slightly better performance than no limits at all, mostly due to the
+ * concurrency limit. For example, on my development computer & my relatively fast residential connection, a
+ * concurrency limit of 4 loads a particular test project in 21 seconds, as opposed to 25 seconds when I bypass the
+ * queue and call `fetch` directly. In that test, my setup downloads about 50 assets per second, so this set of options
+ * only affects concurrency and doesn't actually throttle the downloads. Limiting concurrency also fixes the issue
+ * where very large projects (thousands of assets) can lead to browser failures like `net::ERR_INSUFFICIENT_RESOURCES`.
+ * The exact concurrency limit doesn't seem to matter much since the browser limits parallel connections itself. It
+ * just needs to be high enough to avoid bubbles in the download pipeline and low enough to avoid resource exhaustion.
+ * @see {@link https://github.com/scratchfoundation/scratch-gui/issues/7111}
+ */
+export const AssetQueueOptions: QueueOptions = {
+ burstLimit: 64,
+ sustainRate: 64,
+ // WARNING: asset download concurrency >=5 can lead to corrupted buffers on Chrome (December 2025, Chrome 142.0)
+ // when using Scratch's bitmap load pipeline. Marking the canvas context as `{willReadFrequently: true}` seems to
+ // eliminate that issue, so maybe the problem is related to hardware acceleration.
+ concurrency: 64
+};
+
+/**
+ * Central registry of per-host queues.
+ * Uses strict limits by default. Override these strict limits as needed for specific hosts.
+ */
+export const hostQueueManager = new QueueManager({
+ burstLimit: 5,
+ sustainRate: 1,
+ concurrency: 1
+});
diff --git a/packages/scratch-storage/src/ProxyTool.ts b/packages/scratch-storage/src/ProxyTool.ts
new file mode 100644
index 00000000000..e6626f41101
--- /dev/null
+++ b/packages/scratch-storage/src/ProxyTool.ts
@@ -0,0 +1,107 @@
+import FetchWorkerTool from './FetchWorkerTool';
+import {FetchTool} from './FetchTool';
+import {ScratchGetRequest, ScratchSendRequest, Tool} from './Tool';
+
+/**
+ * @typedef {object} Request
+ * @property {string} url
+ * @property {*} body
+ * @property {string} method
+ * @property {boolean} withCredentials
+ */
+
+type ToolFilter = typeof ProxyTool.TOOL_FILTER[keyof typeof ProxyTool.TOOL_FILTER];
+
+/**
+ * Get and send assets with other tools in sequence.
+ */
+export default class ProxyTool implements Tool {
+ public tools: Tool[];
+
+ /**
+ * Constant values that filter the set of tools in a ProxyTool instance.
+ * @enum {string}
+ */
+ public static TOOL_FILTER = {
+ /**
+ * Use all tools.
+ */
+ ALL: 'all',
+
+ /**
+ * Use tools that are ready right now.
+ */
+ READY: 'ready'
+ } as const;
+
+ constructor (filter: ToolFilter = ProxyTool.TOOL_FILTER.ALL) {
+ let tools: Tool[];
+ if (filter === ProxyTool.TOOL_FILTER.READY) {
+ tools = [new FetchTool()];
+ } else {
+ tools = [new FetchWorkerTool(), new FetchTool()];
+ }
+
+ /**
+ * Sequence of tools to proxy.
+ * @type {Array.}
+ */
+ this.tools = tools;
+ }
+
+ /**
+ * Is get supported? false if all proxied tool return false.
+ * @returns {boolean} Is get supported?
+ */
+ get isGetSupported (): boolean {
+ return this.tools.some(tool => tool.isGetSupported);
+ }
+
+ /**
+ * Request data from with one of the proxied tools.
+ * @param {Request} reqConfig - Request configuration for data to get.
+ * @returns {Promise.} Resolve to Buffer of data from server.
+ */
+ get (reqConfig: ScratchGetRequest): Promise {
+ let toolIndex = 0;
+ const nextTool = (err?: unknown): Promise => {
+ const tool = this.tools[toolIndex++];
+ if (!tool) {
+ throw err;
+ }
+ if (!tool.isGetSupported) {
+ return nextTool(err);
+ }
+ return tool.get(reqConfig).catch(nextTool);
+ };
+ return nextTool();
+ }
+
+ /**
+ * Is sending supported? false if all proxied tool return false.
+ * @returns {boolean} Is sending supported?
+ */
+ get isSendSupported (): boolean {
+ return this.tools.some(tool => tool.isSendSupported);
+ }
+
+ /**
+ * Send data to a server with one of the proxied tools.
+ * @param {Request} reqConfig - Request configuration for data to send.
+ * @returns {Promise.} Server returned metadata.
+ */
+ send (reqConfig: ScratchSendRequest): Promise {
+ let toolIndex = 0;
+ const nextTool = (err?: unknown): Promise => {
+ const tool = this.tools[toolIndex++];
+ if (!tool) {
+ throw err;
+ }
+ if (!tool.isSendSupported) {
+ return nextTool(err);
+ }
+ return tool.send(reqConfig).catch(nextTool);
+ };
+ return nextTool();
+ }
+}
diff --git a/packages/scratch-storage/src/ScratchStorage.ts b/packages/scratch-storage/src/ScratchStorage.ts
new file mode 100644
index 00000000000..4783185deb7
--- /dev/null
+++ b/packages/scratch-storage/src/ScratchStorage.ts
@@ -0,0 +1,267 @@
+import log from './log';
+
+import BuiltinHelper from './BuiltinHelper';
+import WebHelper, {UrlFunction} from './WebHelper';
+
+import _Asset, {AssetData, AssetId} from './Asset';
+import {AssetType as _AssetType, AssetType} from './AssetType';
+import {DataFormat as _DataFormat, DataFormat} from './DataFormat';
+import * as _scratchFetch from './scratchFetch';
+import Helper from './Helper';
+
+interface HelperWithPriority {
+ helper: Helper,
+ priority: number
+}
+
+export class ScratchStorage {
+ public defaultAssetId: Record;
+ public builtinHelper: BuiltinHelper;
+ public webHelper: WebHelper;
+
+ private _helpers: HelperWithPriority[];
+
+ constructor () {
+ this.defaultAssetId = {};
+
+ this.builtinHelper = new BuiltinHelper(this);
+ this.webHelper = new WebHelper(this);
+ this.builtinHelper.registerDefaultAssets();
+
+ this._helpers = [
+ {
+ helper: this.builtinHelper,
+ priority: 100
+ },
+ {
+ helper: this.webHelper,
+ priority: -100
+ }
+ ];
+ }
+
+ /**
+ * @returns {Asset} - the `Asset` class constructor.
+ * @class
+ */
+ get Asset () {
+ return _Asset;
+ }
+
+ /**
+ * @returns {AssetType} - the list of supported asset types.
+ * @class
+ */
+ get AssetType () {
+ return _AssetType;
+ }
+
+ /**
+ * @returns {DataFormat} - the list of supported data formats.
+ * @class
+ */
+ get DataFormat () {
+ return _DataFormat;
+ }
+
+ /**
+ * Access the `scratchFetch` module within this library.
+ * @returns {module} the scratchFetch module, with properties for `scratchFetch`, `setMetadata`, etc.
+ */
+ get scratchFetch () {
+ return _scratchFetch;
+ }
+
+ /**
+ * @deprecated Please use the `Asset` member of a storage instance instead.
+ * @returns {Asset} - the `Asset` class constructor.
+ * @class
+ */
+ static get Asset () {
+ return _Asset;
+ }
+
+ /**
+ * @deprecated Please use the `AssetType` member of a storage instance instead.
+ * @returns {AssetType} - the list of supported asset types.
+ * @class
+ */
+ static get AssetType () {
+ return _AssetType;
+ }
+
+ /**
+ * Add a storage helper to this manager. Helpers with a higher priority number will be checked first when loading
+ * or storing assets. For comparison, the helper for built-in assets has `priority=100` and the default web helper
+ * has `priority=-100`. The relative order of helpers with equal priorities is undefined.
+ * @param {Helper} helper - the helper to be added.
+ * @param {number} [priority] - the priority for this new helper (default: 0).
+ */
+ addHelper (helper: Helper, priority = 0) {
+ this._helpers.push({helper, priority});
+ this._helpers.sort((a, b) => b.priority - a.priority);
+ }
+
+ /**
+ * Synchronously fetch a cached asset from built-in storage. Assets are cached when they are loaded.
+ * @param {string} assetId - The id of the asset to fetch.
+ * @returns {?Asset} The asset, if it exists.
+ */
+ get (assetId: string): _Asset | null {
+ return this.builtinHelper.get(assetId);
+ }
+
+ /**
+ * Deprecated API for caching built-in assets. Use createAsset.
+ * @param {AssetType} assetType - The type of the asset to cache.
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
+ * @param {Buffer} data - The data for the cached asset.
+ * @param {string} id - The id for the cached asset.
+ * @returns {string} The calculated id of the cached asset, or the supplied id if the asset is mutable.
+ */
+ cache (assetType: AssetType, dataFormat: DataFormat, data: AssetData, id: AssetId): AssetId {
+ log.warn('Deprecation: Storage.cache is deprecated. Use Storage.createAsset, and store assets externally.');
+ return this.builtinHelper._store(assetType, dataFormat, data, id);
+ }
+
+ /**
+ * Construct an Asset, and optionally generate an md5 hash of its data to create an id
+ * @param {AssetType} assetType - The type of the asset to cache.
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
+ * @param {Buffer} data - The data for the cached asset.
+ * @param {string} [id] - The id for the cached asset.
+ * @param {bool} [generateId] - flag to set id to an md5 hash of data if `id` isn't supplied
+ * @returns {Asset} generated Asset with `id` attribute set if not supplied
+ */
+ createAsset (
+ assetType: AssetType,
+ dataFormat: DataFormat,
+ data: AssetData,
+ id: AssetId,
+ generateId: boolean
+ ): _Asset {
+ if (!dataFormat) throw new Error('Tried to create asset without a dataFormat');
+ return new _Asset(assetType, id, dataFormat, data, generateId);
+ }
+
+ /**
+ * Register a web-based source for assets. Sources will be checked in order of registration.
+ * @param {Array.} types - The types of asset provided by this source.
+ * @param {UrlFunction} getFunction - A function which computes a GET URL from an Asset.
+ * @param {UrlFunction} createFunction - A function which computes a POST URL for asset data.
+ * @param {UrlFunction} updateFunction - A function which computes a PUT URL for asset data.
+ */
+ addWebStore (
+ types: AssetType[],
+ getFunction: UrlFunction,
+ createFunction?: UrlFunction,
+ updateFunction?: UrlFunction
+ ): void {
+ this.webHelper.addStore(types, getFunction, createFunction, updateFunction);
+ }
+
+ /**
+ * Register a web-based source for assets. Sources will be checked in order of registration.
+ * @deprecated Please use addWebStore
+ * @param {Array.} types - The types of asset provided by this source.
+ * @param {UrlFunction} urlFunction - A function which computes a GET URL from an Asset.
+ */
+ addWebSource (types: AssetType[], urlFunction: UrlFunction): void {
+ log.warn('Deprecation: Storage.addWebSource has been replaced by addWebStore.');
+ this.addWebStore(types, urlFunction);
+ }
+
+ /**
+ * TODO: Should this be removed in favor of requesting an asset with `null` as the ID?
+ * @param {AssetType} type - Get the default ID for assets of this type.
+ * @returns {?string} The ID of the default asset of the given type, if any.
+ */
+ getDefaultAssetId (type: AssetType): AssetId | undefined {
+ if (Object.prototype.hasOwnProperty.call(this.defaultAssetId, type.name)) {
+ return this.defaultAssetId[type.name];
+ }
+ }
+
+ /**
+ * Set the default ID for a particular type of asset. This default asset will be used if a requested asset cannot
+ * be found and automatic fallback is enabled. Ideally this should be an asset that is available locally or even
+ * one built into this module.
+ * TODO: Should this be removed in favor of requesting an asset with `null` as the ID?
+ * @param {AssetType} type - The type of asset for which the default will be set.
+ * @param {string} id - The default ID to use for this type of asset.
+ */
+ setDefaultAssetId (type: AssetType, id: AssetId): void {
+ this.defaultAssetId[type.name] = id;
+ }
+
+ /**
+ * Fetch an asset by type & ID.
+ * @param {AssetType} assetType - The type of asset to fetch. This also determines which asset store to use.
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
+ * @param {DataFormat} [dataFormat] - Optional: load this format instead of the AssetType's default.
+ * @returns {Promise.} A promise for the requested Asset.
+ * If the promise is resolved with non-null, the value is the requested asset.
+ * If the promise is resolved with null, the desired asset could not be found with the current asset sources.
+ * If the promise is rejected, there was an error on at least one asset source. HTTP 404 does not count as an
+ * error here, but (for example) HTTP 403 does.
+ */
+ load (assetType: AssetType, assetId: AssetId, dataFormat: DataFormat): Promise<_Asset | null> {
+ const helpers = this._helpers.map(x => x.helper);
+ const errors: unknown[] = [];
+ dataFormat = dataFormat || assetType.runtimeFormat;
+
+ let helperIndex = 0;
+ let helper: Helper;
+ const tryNextHelper = (err?: unknown): Promise<_Asset | null> => {
+ if (err) { // Track the error, but continue looking
+ errors.push(err);
+ }
+
+ helper = helpers[helperIndex++];
+
+ if (helper) {
+ const loading = helper.load(assetType, assetId, dataFormat);
+ if (loading === null) {
+ return tryNextHelper();
+ }
+ // Note that other attempts may have logged errors; if this succeeds they will be suppressed.
+ return loading
+ // TODO: maybe some types of error should prevent trying the next helper?
+ .catch(tryNextHelper);
+ } else if (errors.length > 0) {
+ // We looked through all the helpers and couldn't find the asset, AND
+ // at least one thing went wrong while we were looking.
+ return Promise.reject(errors);
+ }
+
+ // Nothing went wrong but we couldn't find the asset.
+ return Promise.resolve(null);
+ };
+
+ return tryNextHelper();
+ }
+
+ /**
+ * Store an asset by type & ID.
+ * @param {AssetType} assetType - The type of asset to fetch. This also determines which asset store to use.
+ * @param {?DataFormat} [dataFormat] - Optional: load this format instead of the AssetType's default.
+ * @param {Buffer} data - Data to store for the asset
+ * @param {?string} [assetId] - The ID of the asset to fetch: a project ID, MD5, etc.
+ * @returns {Promise.} A promise for asset metadata
+ */
+ store (assetType: AssetType, dataFormat: DataFormat | null | undefined, data: AssetData, assetId?: AssetId) {
+ dataFormat = dataFormat || assetType.runtimeFormat;
+
+ return this.webHelper.store(assetType, dataFormat, data, assetId)
+ .then(body => {
+ // The previous logic here ignored that the body can be a string (if it's not a JSON),
+ // so just ignore that case.
+ // Also, having undefined was the previous behavior
+ // eslint-disable-next-line no-undefined
+ const id = typeof body === 'string' ? undefined : body.id;
+
+ this.builtinHelper._store(assetType, dataFormat, data, id);
+ return body;
+ });
+ }
+}
diff --git a/packages/scratch-storage/src/Tool.ts b/packages/scratch-storage/src/Tool.ts
new file mode 100644
index 00000000000..e5cb60f6267
--- /dev/null
+++ b/packages/scratch-storage/src/Tool.ts
@@ -0,0 +1,10 @@
+export type ScratchGetRequest = {url: string} & RequestInit;
+export type ScratchSendRequest = {url: string, withCredentials?: boolean} & RequestInit;
+
+export interface Tool {
+ get isGetSupported (): boolean;
+ get (request: ScratchGetRequest): Promise;
+
+ get isSendSupported (): boolean;
+ send (request: ScratchSendRequest): Promise;
+}
diff --git a/packages/scratch-storage/src/WebHelper.ts b/packages/scratch-storage/src/WebHelper.ts
new file mode 100644
index 00000000000..8a2579afd3a
--- /dev/null
+++ b/packages/scratch-storage/src/WebHelper.ts
@@ -0,0 +1,222 @@
+import log from './log';
+
+import Asset, {AssetData, AssetId} from './Asset';
+import Helper from './Helper';
+import ProxyTool from './ProxyTool';
+import {ScratchGetRequest, ScratchSendRequest, Tool} from './Tool';
+import {AssetType} from './AssetType';
+import {DataFormat} from './DataFormat';
+
+const ensureRequestConfig = reqConfig => {
+ if (typeof reqConfig === 'string') {
+ return {
+ url: reqConfig
+ };
+ }
+ return reqConfig;
+};
+
+/**
+ * @typedef {function} UrlFunction - A function which computes a URL from asset information.
+ * @param {Asset} - The asset for which the URL should be computed.
+ * @returns {(string|object)} - A string representing the URL for the asset request OR an object with configuration for
+ * the underlying fetch call (necessary for configuring e.g. authentication)
+ */
+
+export type UrlFunction = (asset: Asset) => string | ScratchGetRequest | ScratchSendRequest;
+
+interface StoreRecord {
+ types: string[],
+ get: UrlFunction,
+ create?: UrlFunction,
+ update?: UrlFunction
+}
+
+export default class WebHelper extends Helper {
+ public stores: StoreRecord[];
+ public assetTool: Tool;
+ public projectTool: Tool;
+
+ constructor (parent) {
+ super(parent);
+
+ /**
+ * @type {Array.}
+ * @typedef {object} StoreRecord
+ * @property {Array.} types - The types of asset provided by this store, from AssetType's name field.
+ * @property {UrlFunction} getFunction - A function which computes a URL from an Asset.
+ * @property {UrlFunction} createFunction - A function which computes a URL from an Asset.
+ * @property {UrlFunction} updateFunction - A function which computes a URL from an Asset.
+ */
+ this.stores = [];
+
+ /**
+ * Set of tools to best load many assets in parallel. If one tool
+ * cannot be used, it will use the next.
+ * @type {ProxyTool}
+ */
+ this.assetTool = new ProxyTool();
+
+ /**
+ * Set of tools to best load project data in parallel with assets. This
+ * tool set prefers tools that are immediately ready. Some tools have
+ * to initialize before they can load files.
+ * @type {ProxyTool}
+ */
+ this.projectTool = new ProxyTool(ProxyTool.TOOL_FILTER.READY);
+ }
+
+ /**
+ * Register a web-based source for assets. Sources will be checked in order of registration.
+ * @deprecated Please use addStore
+ * @param {Array.} types - The types of asset provided by this source.
+ * @param {UrlFunction} urlFunction - A function which computes a URL from an Asset.
+ */
+ addSource (types: AssetType[], urlFunction: UrlFunction): void {
+ log.warn('Deprecation: WebHelper.addSource has been replaced with WebHelper.addStore.');
+ this.addStore(types, urlFunction);
+ }
+
+ /**
+ * Register a web-based store for assets. Sources will be checked in order of registration.
+ * @param {Array.} types - The types of asset provided by this store.
+ * @param {UrlFunction} getFunction - A function which computes a GET URL for an Asset
+ * @param {UrlFunction} createFunction - A function which computes a POST URL for an Asset
+ * @param {UrlFunction} updateFunction - A function which computes a PUT URL for an Asset
+ */
+ addStore (
+ types: AssetType[],
+ getFunction: UrlFunction,
+ createFunction?: UrlFunction,
+ updateFunction?: UrlFunction
+ ): void {
+ this.stores.push({
+ types: types.map(assetType => assetType.name),
+ get: getFunction,
+ create: createFunction,
+ update: updateFunction
+ });
+ }
+
+ /**
+ * Fetch an asset but don't process dependencies.
+ * @param {AssetType} assetType - The type of asset to fetch.
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
+ * @param {DataFormat} dataFormat - The file format / file extension of the asset to fetch: PNG, JPG, etc.
+ * @returns {Promise.} A promise for the contents of the asset.
+ */
+ load (assetType: AssetType, assetId: AssetId, dataFormat: DataFormat): Promise {
+
+ /** @type {Array.<{url:string, result:*}>} List of URLs attempted & errors encountered. */
+ const errors: unknown[] = [];
+ const stores = this.stores.slice()
+ .filter(store => store.types.indexOf(assetType.name) >= 0);
+
+ // New empty asset but it doesn't have data yet
+ const asset = new Asset(assetType, assetId, dataFormat);
+
+ let tool = this.assetTool;
+ if (assetType.name === 'Project') {
+ tool = this.projectTool;
+ }
+
+ let storeIndex = 0;
+ const tryNextSource = (err?: unknown): Promise => {
+ if (err) {
+ errors.push(err);
+ }
+ const store = stores[storeIndex++];
+
+ /** @type {UrlFunction} */
+ const reqConfigFunction = store && store.get;
+
+ if (reqConfigFunction) {
+ const reqConfig = ensureRequestConfig(reqConfigFunction(asset));
+ if (reqConfig === false) {
+ return tryNextSource();
+ }
+
+ return tool.get(reqConfig)
+ .then(body => {
+ if (body) {
+ asset.setData(body, dataFormat);
+ return asset;
+ }
+ return tryNextSource();
+ })
+ .catch(tryNextSource);
+ } else if (errors.length > 0) {
+ return Promise.reject(errors);
+ }
+
+ // no stores matching asset
+ return Promise.resolve(null);
+ };
+
+ return tryNextSource();
+ }
+
+ /**
+ * Create or update an asset with provided data. The create function is called if no asset id is provided
+ * @param {AssetType} assetType - The type of asset to create or update.
+ * @param {?DataFormat} dataFormat - DataFormat of the data for the stored asset.
+ * @param {Buffer} data - The data for the cached asset.
+ * @param {?string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
+ * @returns {Promise.} A promise for the response from the create or update request
+ */
+ store (
+ assetType: AssetType,
+ dataFormat: DataFormat | undefined,
+ data: AssetData,
+ assetId?: AssetId
+ ): Promise {
+ const asset = new Asset(assetType, assetId, dataFormat);
+ // If we have an asset id, we should update, otherwise create to get an id
+ const create = assetId === '' || assetId === null || typeof assetId === 'undefined';
+
+ // Use the first store with the appropriate asset type and url function
+ const store = this.stores.filter(s =>
+ // Only use stores for the incoming asset type
+ s.types.indexOf(assetType.name) !== -1 && (
+ // Only use stores that have a create function if this is a create request
+ // or an update function if this is an update request
+ (create && s.create) || s.update
+ )
+ )[0];
+
+ const method = create ? 'post' : 'put';
+
+ if (!store) return Promise.reject(new Error('No appropriate stores'));
+
+ let tool = this.assetTool;
+ if (assetType.name === 'Project') {
+ tool = this.projectTool;
+ }
+
+ const reqConfig = ensureRequestConfig(
+ // The non-nullability of this gets checked above while looking up the store.
+ // Making TS understand that is going to require code refactoring which we currently don't
+ // feel safe to do.
+ create ? store.create!(asset) : store.update!(asset)
+ );
+ const reqBodyConfig = Object.assign({body: data, method}, reqConfig);
+ return tool.send(reqBodyConfig)
+ .then(body => {
+ // xhr makes it difficult to both send FormData and
+ // automatically parse a JSON response. So try to parse
+ // everything as JSON.
+ if (typeof body === 'string') {
+ try {
+ body = JSON.parse(body);
+ } catch (parseError) { // eslint-disable-line @typescript-eslint/no-unused-vars
+ // If it's not parseable, then we can't add the id even
+ // if we want to, so stop here
+ return body;
+ }
+ }
+ return Object.assign({
+ id: body['content-name'] || assetId
+ }, body);
+ });
+ }
+}
diff --git a/packages/scratch-storage/src/builtins/defaultBitmap.png b/packages/scratch-storage/src/builtins/defaultBitmap.png
new file mode 100644
index 00000000000..fb550a32b93
Binary files /dev/null and b/packages/scratch-storage/src/builtins/defaultBitmap.png differ
diff --git a/packages/scratch-storage/src/builtins/defaultSound.wav b/packages/scratch-storage/src/builtins/defaultSound.wav
new file mode 100644
index 00000000000..cedc541ce89
Binary files /dev/null and b/packages/scratch-storage/src/builtins/defaultSound.wav differ
diff --git a/packages/scratch-storage/src/builtins/defaultVector.svg b/packages/scratch-storage/src/builtins/defaultVector.svg
new file mode 100644
index 00000000000..ae5eabf93a7
--- /dev/null
+++ b/packages/scratch-storage/src/builtins/defaultVector.svg
@@ -0,0 +1,7 @@
+
+
+
+
+ ?
+
+
diff --git a/packages/scratch-storage/src/index.ts b/packages/scratch-storage/src/index.ts
new file mode 100644
index 00000000000..37a8830b1bf
--- /dev/null
+++ b/packages/scratch-storage/src/index.ts
@@ -0,0 +1,19 @@
+import {ScratchStorage} from './ScratchStorage';
+import Asset, {AssetId} from './Asset';
+import {AssetType} from './AssetType';
+import {DataFormat} from './DataFormat';
+import Helper from './Helper';
+
+export {
+ /**
+ * Export for use with NPM & Node.js.
+ * @type {ScratchStorage}
+ */
+ ScratchStorage,
+
+ Asset,
+ AssetId,
+ AssetType,
+ DataFormat,
+ Helper
+};
diff --git a/packages/scratch-storage/src/log.ts b/packages/scratch-storage/src/log.ts
new file mode 100644
index 00000000000..cb24963725c
--- /dev/null
+++ b/packages/scratch-storage/src/log.ts
@@ -0,0 +1,4 @@
+import minilog from 'minilog';
+minilog.enable();
+
+export default minilog('storage');
diff --git a/packages/scratch-storage/src/memoizedToString.ts b/packages/scratch-storage/src/memoizedToString.ts
new file mode 100644
index 00000000000..e087de7daca
--- /dev/null
+++ b/packages/scratch-storage/src/memoizedToString.ts
@@ -0,0 +1,84 @@
+import {AssetId} from './Asset';
+
+declare function require(name: 'fastestsmallesttextencoderdecoder'): {
+ TextEncoder: typeof TextEncoder,
+ TextDecoder: typeof TextDecoder
+};
+
+declare function require(name: 'base64-js'): {
+ fromByteArray: (data: Uint8Array) => string;
+};
+
+// Use JS implemented TextDecoder and TextEncoder if it is not provided by the
+// browser.
+let _TextDecoder: typeof TextDecoder;
+let _TextEncoder: typeof TextEncoder;
+if (typeof TextDecoder === 'undefined' || typeof TextEncoder === 'undefined') {
+ // Wait to require the text encoding polyfill until we know it's needed.
+ const encoding = require('fastestsmallesttextencoderdecoder');
+ _TextDecoder = encoding.TextDecoder;
+ _TextEncoder = encoding.TextEncoder;
+} else {
+ _TextDecoder = TextDecoder;
+ _TextEncoder = TextEncoder;
+}
+
+const memoizedToString = (function () {
+ /**
+ * The maximum length of a chunk before encoding it into base64.
+ *
+ * 32766 is a multiple of 3 so btoa does not need to use padding characters
+ * except for the final chunk where that is fine. 32766 is also close to
+ * 32768 so it is close to a size an memory allocator would prefer.
+ * @constant {number}
+ */
+ const BTOA_CHUNK_MAX_LENGTH = 32766;
+
+ /**
+ * An array cache of bytes to characters.
+ * @constant {?Array.}
+ */
+ let fromCharCode: string[] | null = null;
+
+ const strings = {};
+ return (assetId: AssetId, data: Uint8Array) => {
+ if (!Object.prototype.hasOwnProperty.call(strings, assetId)) {
+ if (typeof btoa === 'undefined') {
+ // Use a library that does not need btoa to run.
+ const base64js = require('base64-js');
+ strings[assetId] = base64js.fromByteArray(data);
+ } else {
+ // Native btoa is faster than javascript translation. Use js to
+ // create a "binary" string and btoa to encode it.
+ if (fromCharCode === null) {
+ // Cache the first 256 characters for input byte values.
+ fromCharCode = new Array(256);
+ for (let i = 0; i < 256; i++) {
+ fromCharCode[i] = String.fromCharCode(i);
+ }
+ }
+
+ const {length} = data;
+ let s = '';
+ // Iterate over chunks of the binary data.
+ for (let i = 0, e = 0; i < length; i = e) {
+ // Create small chunks to cause more small allocations and
+ // less large allocations.
+ e = Math.min(e + BTOA_CHUNK_MAX_LENGTH, length);
+ let s_ = '';
+ for (let j = i; j < e; j += 1) {
+ s_ += fromCharCode[data[j]];
+ }
+ // Encode the latest chunk so the we create one big output
+ // string instead of creating a big input string and then
+ // one big output string.
+ s += btoa(s_);
+ }
+ strings[assetId] = s;
+ }
+ }
+ return strings[assetId];
+ };
+}());
+
+export {memoizedToString, _TextEncoder, _TextDecoder};
diff --git a/packages/scratch-storage/src/scratchFetch.ts b/packages/scratch-storage/src/scratchFetch.ts
new file mode 100644
index 00000000000..f07d7fea2db
--- /dev/null
+++ b/packages/scratch-storage/src/scratchFetch.ts
@@ -0,0 +1,154 @@
+import {type QueueOptions} from '@scratch/task-herder';
+import {hostQueueManager} from './HostQueues';
+
+export const Headers = globalThis.Headers;
+
+/**
+ * Metadata header names.
+ * The enum value is the name of the associated header.
+ */
+export enum RequestMetadata {
+ /** The ID of the project associated with this request */
+ ProjectId = 'X-Project-ID',
+ /** The ID of the project run associated with this request */
+ RunId = 'X-Run-ID'
+}
+
+export type ScratchFetchOptions = {
+ /**
+ * The name of the queue to use for this request.
+ * If absent, the hostname of the requested URL will be used as the queue name.
+ * This is a Scratch-specific extension to the standard RequestInit type.
+ */
+ queueName?: string;
+
+ /**
+ * The options to use when creating the queue for this request.
+ * Ignored if a queue with the specified name already exists.
+ */
+ queueOptions?: QueueOptions;
+};
+
+/**
+ * Metadata headers for requests.
+ */
+const metadata = new Headers();
+
+/**
+ * Check if there is any metadata to apply.
+ * @returns {boolean} true if `metadata` has contents, or false if it is empty.
+ */
+export const hasMetadata = (): boolean => {
+ const searchParams = (
+ typeof self !== 'undefined' &&
+ self &&
+ self.location &&
+ self.location.search &&
+ self.location.search.split(/[?&]/)
+ ) || [];
+ if (!searchParams.includes('scratchMetadata=1')) {
+ // for now, disable this feature unless scratchMetadata=1
+ // TODO: remove this check once we're sure the feature works correctly in production
+ return false;
+ }
+ for (const _ of metadata) {
+ return true;
+ }
+ return false;
+};
+
+/**
+ * Non-destructively merge any metadata state (if any) with the provided options object (if any).
+ * If there is metadata state but no options object is provided, make a new object.
+ * If there is no metadata state, return the provided options parameter without modification.
+ * If there is metadata and an options object is provided, modify a copy and return it.
+ * Headers in the provided options object may override headers generated from metadata state.
+ * @param {RequestInit} [options] The initial request options. May be null or undefined.
+ * @returns {RequestInit|undefined} the provided options parameter without modification, or a new options object.
+ */
+export const applyMetadata = (options?: globalThis.RequestInit): globalThis.RequestInit | undefined => {
+ if (hasMetadata()) {
+ const augmentedOptions = Object.assign({}, options);
+ augmentedOptions.headers = new Headers(metadata);
+ if (options && options.headers) {
+ // the Fetch spec says options.headers could be:
+ // "A Headers object, an object literal, or an array of two-item arrays to set request's headers."
+ // turn it into a Headers object to be sure of how to interact with it
+ const overrideHeaders = options.headers instanceof Headers ?
+ options.headers : new Headers(options.headers);
+ for (const [name, value] of overrideHeaders.entries()) {
+ augmentedOptions.headers.set(name, value);
+ }
+ }
+ return augmentedOptions;
+ }
+ return options;
+};
+
+/**
+ * Make a network request.
+ * This is a wrapper for the global fetch method, adding some Scratch-specific functionality.
+ * @param {RequestInfo|URL} resource The resource to fetch.
+ * @param {RequestInit} [requestOptions] Optional object containing custom settings for this request.
+ * @param {ScratchFetchOptions} [scratchOptions] Optional Scratch-specific settings for this request.
+ * @see {@link https://developer.mozilla.org/docs/Web/API/fetch} for more about the fetch API.
+ * @returns {Promise} A promise for the response to the request.
+ */
+export const scratchFetch = (
+ resource: RequestInfo | URL,
+ requestOptions?: globalThis.RequestInit,
+ scratchOptions?: ScratchFetchOptions
+): Promise => {
+ requestOptions = applyMetadata(requestOptions);
+
+ let queueName = scratchOptions?.queueName;
+ if (!queueName) {
+ // Normalize resource to a Request object. The `fetch` call will do this anyway, so it's not much extra work,
+ // but it guarantees availability of the URL for queue naming.
+ resource = new Request(resource, requestOptions);
+ queueName = new URL(resource.url).hostname;
+ }
+ const queue = hostQueueManager.getOrCreate(queueName, scratchOptions?.queueOptions);
+ return queue.do(() => fetch(resource, requestOptions));
+};
+
+/**
+ * Create a new fetch queue with the given identifier and option overrides.
+ * If a queue with that identifier already exists, it will be replaced.
+ * Queues are automatically created as needed with default options, so
+ * there's no need to call this unless you need to override the default queue options.
+ * WARNING: If the old queue has is not empty, it may continue to run its tasks in the background.
+ * If you need to cancel fetch tasks in that queue before replacing it, do so manually first.
+ * @param queueName The name of the queue to create.
+ * @param overrides Optional overrides for the default QueueOptions for this specific queue.
+ */
+export const createQueue = (queueName: string, overrides: Partial): void => {
+ hostQueueManager.create(queueName, overrides);
+};
+
+/**
+ * Set the value of a named request metadata item.
+ * Setting the value to `null` or `undefined` will NOT remove the item.
+ * Use `unsetMetadata` for that.
+ * @param {RequestMetadata} name The name of the metadata item to set.
+ * @param {any} value The value to set (will be converted to a string).
+ */
+export const setMetadata = (name: RequestMetadata, value: any): void => {
+ metadata.set(name, value);
+};
+
+/**
+ * Remove a named request metadata item.
+ * @param {RequestMetadata} name The name of the metadata item to remove.
+ */
+export const unsetMetadata = (name: RequestMetadata): void => {
+ metadata.delete(name);
+};
+
+/**
+ * Retrieve a named request metadata item.
+ * Only for use in tests. At the time of writing, used in scratch-vm tests.
+ * @param {RequestMetadata} name The name of the metadata item to retrieve.
+ * @returns {string|null} The value of the metadata item, or `null` if it was not found.
+ */
+export const getMetadata = (name: RequestMetadata): string | null => metadata.get(name);
diff --git a/packages/scratch-storage/src/types.d.ts b/packages/scratch-storage/src/types.d.ts
new file mode 100644
index 00000000000..e88f1bb42b2
--- /dev/null
+++ b/packages/scratch-storage/src/types.d.ts
@@ -0,0 +1,4 @@
+declare module '*?arrayBuffer' {
+ const value: ArrayBuffer;
+ export default value;
+}
diff --git a/packages/scratch-storage/test/build/api.test.js b/packages/scratch-storage/test/build/api.test.js
new file mode 100644
index 00000000000..aa8fb97857a
--- /dev/null
+++ b/packages/scratch-storage/test/build/api.test.js
@@ -0,0 +1,60 @@
+/**
+ * @file Tests the build output to verify the general parts of the public API.
+ */
+
+const ScratchStorageModule = require('../../dist/node/scratch-storage.js');
+
+/** @type {ScratchStorageModule.ScratchStorage} */
+let storage;
+
+beforeEach(() => {
+ const {ScratchStorage} = ScratchStorageModule;
+ storage = new ScratchStorage();
+});
+
+test('constructor', () => {
+ const {ScratchStorage} = ScratchStorageModule;
+ expect(storage).toBeInstanceOf(ScratchStorage);
+});
+
+test('DataFormat', () => {
+ const {DataFormat} = ScratchStorageModule;
+ expect(DataFormat).toBeDefined();
+ expect(DataFormat.JPG).toBe('jpg');
+ expect(DataFormat.JSON).toBe('json');
+ expect(DataFormat.MP3).toBe('mp3');
+ expect(DataFormat.PNG).toBe('png');
+ expect(DataFormat.SB2).toBe('sb2');
+ expect(DataFormat.SB3).toBe('sb3');
+ expect(DataFormat.SVG).toBe('svg');
+ expect(DataFormat.WAV).toBe('wav');
+});
+
+test('AssetType', () => {
+ const {AssetType, DataFormat} = ScratchStorageModule;
+ expect(AssetType).toBeDefined();
+ expect(AssetType.ImageBitmap.contentType).toBe('image/png');
+ expect(AssetType.ImageVector.contentType).toBe('image/svg+xml');
+ expect(AssetType.Project.runtimeFormat).toBe(DataFormat.JSON);
+ expect(AssetType.Sound.immutable).toBe(true);
+ expect(AssetType.Sprite.name).toBe('Sprite');
+});
+
+test('Asset', () => {
+ const {Asset, AssetType} = ScratchStorageModule;
+ expect(Asset).toBeDefined();
+ const asset = new Asset(
+ AssetType.ImageVector,
+ 'some-hash'
+ );
+ expect(asset).toBeInstanceOf(Asset);
+ expect(asset.dataFormat).toBe('svg');
+ expect(asset.assetId).toBe('some-hash');
+});
+
+test('Helper', () => {
+ const {Helper} = ScratchStorageModule;
+ expect(Helper).toBeDefined();
+ const helper = new Helper();
+ expect(helper).toBeInstanceOf(Helper);
+});
diff --git a/packages/scratch-storage/test/build/scratchFetch.test.js b/packages/scratch-storage/test/build/scratchFetch.test.js
new file mode 100644
index 00000000000..d0cc6d447d8
--- /dev/null
+++ b/packages/scratch-storage/test/build/scratchFetch.test.js
@@ -0,0 +1,40 @@
+/**
+ * @file Tests the build output to verify the scratchFetch portion of the public API.
+ */
+
+const ScratchStorageModule = require('../../dist/node/scratch-storage.js');
+
+/** @type {ScratchStorageModule.ScratchStorage} */
+let storage;
+
+beforeEach(() => {
+ const {ScratchStorage} = ScratchStorageModule;
+ storage = new ScratchStorage();
+});
+
+test('scratchFetch accessor', () => {
+ expect(storage.scratchFetch).toBeDefined();
+});
+
+test('Headers', () => {
+ expect(storage.scratchFetch).toBeDefined();
+ const headers = new storage.scratchFetch.Headers();
+ expect(headers).toBeInstanceOf(storage.scratchFetch.Headers);
+});
+
+test('RequestMetadata enum', () => {
+ expect(storage.scratchFetch.RequestMetadata).toBeDefined();
+ expect(typeof storage.scratchFetch.RequestMetadata.ProjectId).toBe('string');
+ expect(typeof storage.scratchFetch.RequestMetadata.RunId).toBe('string');
+});
+
+test('scratchFetch function', () => {
+ expect(typeof storage.scratchFetch.scratchFetch).toBe('function');
+});
+
+test('metadata functions', () => {
+ expect(typeof storage.scratchFetch.applyMetadata).toBe('function');
+ expect(typeof storage.scratchFetch.setMetadata).toBe('function');
+ expect(typeof storage.scratchFetch.unsetMetadata).toBe('function');
+ expect(typeof storage.scratchFetch.getMetadata).toBe('function');
+});
diff --git a/packages/scratch-storage/test/fixtures/.gitattributes b/packages/scratch-storage/test/fixtures/.gitattributes
new file mode 100644
index 00000000000..c1ce0d48072
--- /dev/null
+++ b/packages/scratch-storage/test/fixtures/.gitattributes
@@ -0,0 +1,3 @@
+# Assets in this directory must be preserved exactly
+# to ensure the MD5 hash matches the expected value.
+* binary
diff --git a/packages/scratch-storage/test/fixtures/assets/117504922.json b/packages/scratch-storage/test/fixtures/assets/117504922.json
new file mode 100755
index 00000000000..ca5b96aa180
--- /dev/null
+++ b/packages/scratch-storage/test/fixtures/assets/117504922.json
@@ -0,0 +1,196 @@
+{
+ "objName": "Stage",
+ "costumes": [{
+ "costumeName": "backdrop1",
+ "baseLayerID": -1,
+ "baseLayerMD5": "ba5d7bbc200d7925664a0878421c4ed2.png",
+ "bitmapResolution": 2,
+ "rotationCenterX": 480,
+ "rotationCenterY": 360
+ }],
+ "currentCostumeIndex": 0,
+ "penLayerMD5": "5c81a336fab8be57adc039a8a2b33ca9.png",
+ "penLayerID": -1,
+ "tempoBPM": 60,
+ "videoAlpha": 0.5,
+ "children": [{
+ "objName": "seymour cropped",
+ "scripts": [[89, 102, [["whenGreenFlag"], ["setSizeTo:", 85]]]],
+ "sounds": [{
+ "soundName": "pop",
+ "soundID": -1,
+ "md5": "83a9787d4cb6f3b7632b4ddfebf74367.wav",
+ "sampleCount": 258,
+ "rate": 11025,
+ "format": ""
+ }],
+ "costumes": [{
+ "costumeName": "SeymourPapert001",
+ "baseLayerID": -1,
+ "baseLayerMD5": "2c8559602a79c7ec929636c3a5ea0291.png",
+ "bitmapResolution": 2,
+ "rotationCenterX": 204,
+ "rotationCenterY": 262
+ }],
+ "currentCostumeIndex": 0,
+ "scratchX": 115,
+ "scratchY": -28,
+ "scale": 0.85,
+ "direction": 90,
+ "rotationStyle": "normal",
+ "isDraggable": false,
+ "indexInLibrary": 2,
+ "visible": true,
+ "spriteInfo": {
+ }
+ },
+ {
+ "objName": "Sprite1",
+ "scripts": [[48,
+ 24,
+ [["whenGreenFlag"],
+ ["setSizeTo:", 110],
+ ["wait:elapsed:from:", 1],
+ ["say:", "Hi. I want to introduce you to Seymour Papert."],
+ ["doPlaySoundAndWait", "papert1"],
+ ["say:", "Seymour developed Logo, the first programming language for kids"],
+ ["doPlaySoundAndWait", "papert2"],
+ ["say:", "He believed that kids learn best"],
+ ["doPlaySoundAndWait", "papert3"],
+ ["say:", "when they are given the chance to create things and express themselves"],
+ ["doPlaySoundAndWait", "papert4"],
+ ["say:", "When we developed Scratch, we were very inspired by Seymour's ideas"],
+ ["doPlaySoundAndWait", "papert5"],
+ ["say:", "So you might call Seymour the grandfather of Scratch"],
+ ["doPlaySoundAndWait", "papert6"],
+ ["say:", "Sadly, Seymour passed away last week, on July 31, 2016"],
+ ["doPlaySoundAndWait", "papert7"],
+ ["say:", "But every time you create and share a Scratch project"],
+ ["doPlaySoundAndWait", "papert8"],
+ ["say:", "you're helping to keep Seymour's spirit alive"],
+ ["doPlaySoundAndWait", "papert9"],
+ ["say:", "So Scratch on!"],
+ ["doPlaySoundAndWait", "papert10"],
+ ["say:", "And Papert on!"],
+ ["doPlaySoundAndWait", "papert11"],
+ ["wait:elapsed:from:", 5],
+ ["say:", ""]]]],
+ "sounds": [{
+ "soundName": "papert1",
+ "soundID": -1,
+ "md5": "876c45f175060737364334daed9366a1.wav",
+ "sampleCount": 84993,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert2",
+ "soundID": -1,
+ "md5": "e439ca64ef29692ed611bb769fdbe543.wav",
+ "sampleCount": 103425,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert3",
+ "soundID": -1,
+ "md5": "0bd55bc2b3ff5741bafe981decdaca5b.wav",
+ "sampleCount": 54273,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert4",
+ "soundID": -1,
+ "md5": "123abc35f1934ed471436c59f7b99e2f.wav",
+ "sampleCount": 93185,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert5",
+ "soundID": -1,
+ "md5": "cd9f672266016a0e55152b2a3398c8d9.wav",
+ "sampleCount": 113665,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert6",
+ "soundID": -1,
+ "md5": "d38287334764b7d4cd2c5db59548234d.wav",
+ "sampleCount": 84993,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert7",
+ "soundID": -1,
+ "md5": "fab6bf9923265a999bcfea1e62384a2c.wav",
+ "sampleCount": 144385,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert8",
+ "soundID": -1,
+ "md5": "6826373fa0554c582f920cc65620395e.wav",
+ "sampleCount": 82945,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert9",
+ "soundID": -1,
+ "md5": "c6b907cbfe0081748ae83cb3bb6aa6d8.wav",
+ "sampleCount": 74753,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert10",
+ "soundID": -1,
+ "md5": "f455697888f2e7b36072a2189fc78bbc.wav",
+ "sampleCount": 39937,
+ "rate": 22050,
+ "format": ""
+ },
+ {
+ "soundName": "papert11",
+ "soundID": -1,
+ "md5": "fb58460f1cd8629eae3b3c58148984ad.wav",
+ "sampleCount": 54273,
+ "rate": 22050,
+ "format": ""
+ }],
+ "costumes": [{
+ "costumeName": "-mres-cartoon",
+ "baseLayerID": -1,
+ "baseLayerMD5": "dd88c3596176f24479a8e8ec9b6c8278.png",
+ "bitmapResolution": 2,
+ "rotationCenterX": 122,
+ "rotationCenterY": 204
+ }],
+ "currentCostumeIndex": 0,
+ "scratchX": -137.95,
+ "scratchY": -71,
+ "scale": 1.1,
+ "direction": 90,
+ "rotationStyle": "normal",
+ "isDraggable": false,
+ "indexInLibrary": 1,
+ "visible": true,
+ "spriteInfo": {
+ }
+ }],
+ "info": {
+ "spriteCount": 2,
+ "hasCloudData": false,
+ "projectID": "117504922",
+ "flashVersion": "MAC 22,0,0,209",
+ "swfVersion": "v448",
+ "userAgent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/51.0.2704.103 Safari\/537.36",
+ "scriptCount": 2,
+ "videoOn": false
+ }
+}
\ No newline at end of file
diff --git a/packages/scratch-storage/test/fixtures/assets/66895930177178ea01d9e610917f8acf.png b/packages/scratch-storage/test/fixtures/assets/66895930177178ea01d9e610917f8acf.png
new file mode 100644
index 00000000000..3edf8162a4f
Binary files /dev/null and b/packages/scratch-storage/test/fixtures/assets/66895930177178ea01d9e610917f8acf.png differ
diff --git a/packages/scratch-storage/test/fixtures/assets/6e8bd9ae68fdb02b7e1e3df656a75635.svg b/packages/scratch-storage/test/fixtures/assets/6e8bd9ae68fdb02b7e1e3df656a75635.svg
new file mode 100644
index 00000000000..0ecb2de81d9
--- /dev/null
+++ b/packages/scratch-storage/test/fixtures/assets/6e8bd9ae68fdb02b7e1e3df656a75635.svg
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/packages/scratch-storage/test/fixtures/assets/7e24c99c1b853e52f8e7f9004416fa34.png b/packages/scratch-storage/test/fixtures/assets/7e24c99c1b853e52f8e7f9004416fa34.png
new file mode 100644
index 00000000000..a8f80f19637
Binary files /dev/null and b/packages/scratch-storage/test/fixtures/assets/7e24c99c1b853e52f8e7f9004416fa34.png differ
diff --git a/packages/scratch-storage/test/fixtures/assets/83c36d806dc92327b9e7049a565c6bff.wav b/packages/scratch-storage/test/fixtures/assets/83c36d806dc92327b9e7049a565c6bff.wav
new file mode 100644
index 00000000000..45742d5ef6f
Binary files /dev/null and b/packages/scratch-storage/test/fixtures/assets/83c36d806dc92327b9e7049a565c6bff.wav differ
diff --git a/packages/scratch-storage/test/fixtures/assets/f88bf1935daea28f8ca098462a31dbb0.svg b/packages/scratch-storage/test/fixtures/assets/f88bf1935daea28f8ca098462a31dbb0.svg
new file mode 100644
index 00000000000..9c509b3e2df
--- /dev/null
+++ b/packages/scratch-storage/test/fixtures/assets/f88bf1935daea28f8ca098462a31dbb0.svg
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/packages/scratch-storage/test/fixtures/assets/fe5e3566965f9de793beeffce377d054.jpg b/packages/scratch-storage/test/fixtures/assets/fe5e3566965f9de793beeffce377d054.jpg
new file mode 100644
index 00000000000..bdaf847d45c
Binary files /dev/null and b/packages/scratch-storage/test/fixtures/assets/fe5e3566965f9de793beeffce377d054.jpg differ
diff --git a/packages/scratch-storage/test/fixtures/known-assets.js b/packages/scratch-storage/test/fixtures/known-assets.js
new file mode 100644
index 00000000000..da65940a21e
--- /dev/null
+++ b/packages/scratch-storage/test/fixtures/known-assets.js
@@ -0,0 +1,88 @@
+const fs = require('fs');
+const path = require('path');
+
+const md5 = require('js-md5');
+
+/**
+ * @typedef {object} KnownAsset
+ * @property {Buffer} content - The content of the asset.
+ * @property {string} hash - The MD5 hash of the asset content.
+ */
+
+/**
+ * @typedef {{[id: string]: KnownAsset}} KnownAssetCollection
+ */
+
+const projects = [
+ '117504922'
+];
+const assets = [
+ '66895930177178ea01d9e610917f8acf.png',
+ '6e8bd9ae68fdb02b7e1e3df656a75635.svg',
+ '7e24c99c1b853e52f8e7f9004416fa34.png',
+ '83c36d806dc92327b9e7049a565c6bff.wav',
+ 'f88bf1935daea28f8ca098462a31dbb0.svg',
+ 'fe5e3566965f9de793beeffce377d054.jpg'
+];
+
+/**
+ * Load a file from disk, then return its content and hash.
+ * @param {string} filename - The file to load
+ * @returns {KnownAsset} The loaded asset
+ */
+const loadSomething = filename => {
+ const fullPath = path.join(__dirname, 'assets', filename);
+ const content = fs.readFileSync(fullPath);
+
+ return {
+ content,
+ hash: md5(content)
+ };
+};
+
+/**
+ * Load a project from disk, ensure it's valid JSON, then return its content and hash.
+ * @param {string} id - The project ID
+ * @returns {KnownAsset} The loaded project asset
+ */
+const loadProject = id => {
+ const filename = `${id}.json`;
+ const result = loadSomething(filename);
+
+ // throw if not a valid JSON string
+ JSON.parse(result.content.toString());
+
+ return result;
+};
+
+/**
+ * Load an asset from disk, ensuring its hash matches its filename.
+ * @param {string} filename - The file to load
+ * @returns {KnownAsset} The loaded asset
+ */
+const loadAsset = filename => {
+ const result = loadSomething(filename);
+
+ const expectedHash = filename.split('.', 1)[0];
+ if (expectedHash !== result.hash) {
+ throw new Error(`Asset has wrong hash: ${filename}`);
+ }
+
+ return result;
+};
+
+/**
+ * @type {KnownAssetCollection}
+ */
+const knownAssets = Object.assign({},
+ projects.reduce((bag, id) => {
+ bag[id] = loadProject(id);
+ return bag;
+ }, /** @type {KnownAssetCollection} */ ({})),
+ assets.reduce((bag, filename) => {
+ bag[filename] = loadAsset(filename);
+ return bag;
+ }, /** @type {KnownAssetCollection} */ ({}))
+);
+
+module.exports = knownAssets;
diff --git a/packages/scratch-storage/test/fixtures/mockFetch.js b/packages/scratch-storage/test/fixtures/mockFetch.js
new file mode 100644
index 00000000000..a441924799f
--- /dev/null
+++ b/packages/scratch-storage/test/fixtures/mockFetch.js
@@ -0,0 +1,82 @@
+/**
+ * Mock implementation of the fetch function for testing.
+ * Since `fetch` is a global, Jest will not automatically mock it from `__mocks__`.
+ *
+ * // In your test setup file or at the top of your test files:
+ * global.fetch = require('../mocks/fetch').default;
+ */
+
+const TextEncoder = require('util').TextEncoder;
+const knownAssets = require('../fixtures/known-assets.js');
+
+const Headers = global.Headers;
+const successText = 'successful response';
+
+/**
+ * @typedef MockFetchResponse The Response-like object returned by mockFetch.
+ * @property {boolean} ok True if the simulated request was successful, false otherwise.
+ * @property {number} status The HTTP status code of the simulated request.
+ * @property {() => Promise} [text] A success string if the simulated request succeeded, undefined otherwise.
+ * @property {() => Promise} [arrayBuffer] Same as `text`, but encoded with UTF-8 if present.
+ */
+
+/**
+ * @typedef {RequestInit & {mockFetchTestData: MockFetchTestData}} MockFetchRequestInit
+ */
+
+/**
+ * @typedef MockFetchTestData
+ * @property {Headers} [headers] A Headers object initialized with the header info received by mockFetch.
+ * @property {number} [headersCount] The number of headers in the 'headers' property.
+ */
+
+/**
+ * Mock the 'fetch' method from browsers.
+ * @param {RequestInfo|URL} resource The (mock) resource to fetch, which will determine the response.
+ * @param {MockFetchRequestInit} [options] Optional object containing custom settings for this request.
+ * @returns {Promise} A promise for a Response-like object. Does not fully implement Response.
+ */
+const mockFetch = (resource, options) => {
+ /** @type {MockFetchResponse} */
+ const results = {
+ ok: false,
+ status: 0
+ };
+ if (options?.mockFetchTestData) {
+ options.mockFetchTestData.headers = new Headers(options.headers);
+ options.mockFetchTestData.headersCount = Array.from(options.mockFetchTestData.headers).length;
+ }
+ const request = new Request(resource, options);
+ const path = new URL(request.url).pathname.slice(1); // remove leading '/'
+ const assetInfo = knownAssets[path];
+ if (assetInfo) {
+ results.ok = true;
+ results.status = 200;
+ results.arrayBuffer = () => Promise.resolve(assetInfo.content);
+ } else {
+ switch (path) {
+ case '200':
+ results.ok = true;
+ results.status = 200;
+ results.text = () => Promise.resolve(successText);
+ results.arrayBuffer = () => Promise.resolve(new TextEncoder().encode(successText));
+ break;
+ case '404':
+ results.ok = false;
+ results.status = 404;
+ break;
+ case '500':
+ results.ok = false;
+ results.status = 500;
+ break;
+ default:
+ throw new Error(`mockFetch doesn't know how to download: ${resource}`);
+ }
+ }
+ return Promise.resolve(results);
+};
+
+module.exports = {
+ fetch: mockFetch,
+ successText
+};
diff --git a/packages/scratch-storage/test/integration/download-known-assets.test.js b/packages/scratch-storage/test/integration/download-known-assets.test.js
new file mode 100644
index 00000000000..00687eb99eb
--- /dev/null
+++ b/packages/scratch-storage/test/integration/download-known-assets.test.js
@@ -0,0 +1,142 @@
+const md5 = require('js-md5');
+
+const mockFetch = require('../fixtures/mockFetch.js');
+const ScratchStorage = require('../../src/index').ScratchStorage;
+
+jest.spyOn(global, 'fetch').mockImplementation(mockFetch.fetch);
+
+test('constructor', () => {
+ const storage = new ScratchStorage();
+ expect(storage).toBeInstanceOf(ScratchStorage);
+});
+
+/**
+ * @typedef {object} AssetTestInfo
+ * @property {AssetType} type - The type of the asset.
+ * @property {string} id - The asset's unique ID.
+ * @property {string} md5 - The asset's MD5 hash.
+ * @property {DataFormat} [ext] - Optional: the asset's data format / file extension.
+ */
+
+/**
+ * @param {ScratchStorage} storage The storage module.
+ * @returns {AssetTestInfo[]} an array of asset info objects.
+ */
+const getTestAssets = storage => [
+ // Project
+ {
+ type: storage.AssetType.Project,
+ id: '117504922',
+ md5: '1225460702e149727de28bff4cfd9e23'
+ },
+ // SVG without explicit extension
+ {
+ type: storage.AssetType.ImageVector,
+ id: 'f88bf1935daea28f8ca098462a31dbb0', // cat1-a
+ md5: 'f88bf1935daea28f8ca098462a31dbb0'
+ },
+ // SVG with explicit extension
+ {
+ type: storage.AssetType.ImageVector,
+ id: '6e8bd9ae68fdb02b7e1e3df656a75635', // cat1-b
+ md5: '6e8bd9ae68fdb02b7e1e3df656a75635',
+ ext: storage.DataFormat.SVG
+ },
+ // PNG without explicit extension
+ {
+ type: storage.AssetType.ImageBitmap,
+ id: '7e24c99c1b853e52f8e7f9004416fa34', // squirrel
+ md5: '7e24c99c1b853e52f8e7f9004416fa34'
+ },
+ // PNG with explicit extension
+ {
+ type: storage.AssetType.ImageBitmap,
+ id: '66895930177178ea01d9e610917f8acf', // bus
+ md5: '66895930177178ea01d9e610917f8acf',
+ ext: storage.DataFormat.PNG
+ },
+ // JPG with explicit extension
+ {
+ type: storage.AssetType.ImageBitmap,
+ id: 'fe5e3566965f9de793beeffce377d054', // building at MIT
+ md5: 'fe5e3566965f9de793beeffce377d054',
+ ext: storage.DataFormat.JPG
+ },
+ // WAV without explicit extension
+ {
+ type: storage.AssetType.Sound,
+ id: '83c36d806dc92327b9e7049a565c6bff', // meow
+ md5: '83c36d806dc92327b9e7049a565c6bff' // wat
+ }
+];
+
+const addWebStores = storage => {
+ // these `asset => ...` callbacks generate values specifically for the fetch mock
+ // in the real world they would generate proper URIs
+ storage.addWebStore(
+ [storage.AssetType.Project],
+ asset => `http://example.com/${asset.assetId}`,
+ null, null);
+ storage.addWebStore(
+ [storage.AssetType.ImageVector, storage.AssetType.ImageBitmap, storage.AssetType.Sound],
+ asset => `http://example.com/${asset.assetId}.${asset.dataFormat}`,
+ null, null
+ );
+};
+
+test('addWebStore', () => {
+ const storage = new ScratchStorage();
+ addWebStores(storage);
+ expect(storage.webHelper.stores.length).toBe(2);
+});
+
+test('load', () => {
+ const storage = new ScratchStorage();
+ addWebStores(storage);
+ const testAssets = getTestAssets(storage);
+ const assetChecks = testAssets.map(async assetInfo => {
+ const asset = await storage.load(assetInfo.type, assetInfo.id, assetInfo.ext)
+ .catch(e => {
+ if (e instanceof Array) {
+ // This is storage.load reporting one or more errors from individual tools.
+ e = e.flat();
+
+ if (e.length === 1) {
+ // If we just have one, it'll display well as-is. Don't bother wrapping it.
+ // Note that this still might be either an Error or a status code (see below).
+ e = e[0];
+ }
+ }
+
+ if (e instanceof Array) {
+ // we must have >1 error, so report it as an AggregateError (supported in Node 15+)
+ e = new AggregateError(
+ e.flat(),
+ `failed to load ${assetInfo.type.name} asset with id=${assetInfo.id}`
+ );
+ // Jest doesn't display AggregateError very well on its own
+ console.error(e);
+ } else if (!(e instanceof Error)) {
+ // storage.load can throw a status like 403 or 500 which isn't an Error.
+ // That can look confusing in test output, so wrap it in an Error that will display well.
+ e = new Error(`failed to load ${assetInfo.type.name} asset with id=${assetInfo.id} (e=${e})`);
+ }
+ // else it's an Error that's already suitable for reporting
+
+ throw e;
+ });
+ expect(asset).toBeInstanceOf(storage.Asset);
+ expect(asset.assetId).toBe(assetInfo.id);
+ expect(asset.assetType).toBe(assetInfo.type);
+ expect(asset.data.length).toBeGreaterThan(0);
+
+ // Web assets should come back as clean
+ expect(asset.clean).toBeTruthy();
+
+ if (assetInfo.md5) {
+ expect(md5(asset.data)).toBe(assetInfo.md5);
+ }
+ });
+
+ return Promise.all(assetChecks);
+});
diff --git a/packages/scratch-storage/test/transformers/arraybuffer-loader.js b/packages/scratch-storage/test/transformers/arraybuffer-loader.js
new file mode 100644
index 00000000000..d88be290070
--- /dev/null
+++ b/packages/scratch-storage/test/transformers/arraybuffer-loader.js
@@ -0,0 +1,11 @@
+const fs = require('fs');
+
+module.exports = {
+ process (_sourceText, sourcePath) {
+ const buffer = fs.readFileSync(sourcePath);
+ const array = buffer.toJSON().data;
+ return {
+ code: `module.exports = Buffer.from([${array}]);`
+ };
+ }
+};
diff --git a/packages/scratch-storage/test/unit/add-helper.test.js b/packages/scratch-storage/test/unit/add-helper.test.js
new file mode 100644
index 00000000000..29f21350bb5
--- /dev/null
+++ b/packages/scratch-storage/test/unit/add-helper.test.js
@@ -0,0 +1,81 @@
+const {ScratchStorage} = require('../../src/ScratchStorage');
+
+/**
+ * Simulate a storage helper, adding log messages when "load" is called rather than actually loading anything.
+ */
+class LoggingHelper {
+ /**
+ * Construct a LoggingHelper instance.
+ * @param {Storage} storage - An instance of the storage module.
+ * @param {string} label - A label for this instance.
+ * @param {boolean} shouldSucceed - set to true to make `load` always succeed, or false to make `load` always fail.
+ * @param {Array.} logContainer - an array in which log messages will be stored.
+ * @class
+ */
+ constructor (storage, label, shouldSucceed, logContainer) {
+ this.storage = storage;
+ this.label = label;
+ this.shouldSucceed = shouldSucceed;
+ this.logContainer = logContainer;
+ }
+
+ /**
+ * Pretend to fetch an asset, but instead add a message to the log container.
+ * @param {AssetType} assetType - The type of asset to fetch.
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
+ * @param {DataFormat} dataFormat - The file format / file extension of the asset to fetch: PNG, JPG, etc.
+ * @returns {Promise.} A promise for the contents of the asset.
+ */
+ load (assetType, assetId, dataFormat) {
+ this.logContainer.push(this.label);
+ return this.shouldSucceed ?
+ Promise.resolve(new this.storage.Asset(assetType, assetId, dataFormat, Buffer.from(this.label))) :
+ Promise.reject(new Error(`This is an expected failure from ${this.label}`));
+ }
+}
+
+test('ScratchStorage constructor', () => {
+ const storage = new ScratchStorage();
+ expect(storage).toBeInstanceOf(ScratchStorage);
+});
+
+test('LoggingHelper constructor', () => {
+ const storage = new ScratchStorage();
+ const loggingHelper = new LoggingHelper(storage, 'constructor test', true, []);
+ expect(loggingHelper).toBeInstanceOf(LoggingHelper);
+});
+
+test('addHelper', async () => {
+ const logContainer = [];
+ const storage = new ScratchStorage();
+
+ const initialHelperCount = storage._helpers.length;
+
+ // The first two helpers should fail (shouldSucceed=false) so that the storage module continues through the list.
+ // The third helper should succeed (shouldSucceed=true) so that the overall load succeeds.
+ const loggingHelpers = [
+ new LoggingHelper(storage, 'first', false, logContainer),
+ new LoggingHelper(storage, 'second', false, logContainer),
+ new LoggingHelper(storage, 'third', true, logContainer)
+ ];
+
+ // Add out of order to check that the priority values are respected
+ storage.addHelper(loggingHelpers[2], -50);
+ storage.addHelper(loggingHelpers[0], 50);
+ storage.addHelper(loggingHelpers[1], 0);
+
+ // Did they all get added?
+ expect(storage._helpers.length).toBe(initialHelperCount + loggingHelpers.length);
+
+ // We shouldn't have any log entries yet
+ expect(logContainer).toStrictEqual([]);
+
+ await storage.load(storage.AssetType.Project, '0');
+
+ // Verify that all helpers were consulted, and in the correct order
+ expect(logContainer).toStrictEqual([
+ 'first',
+ 'second',
+ 'third'
+ ]);
+});
diff --git a/packages/scratch-storage/test/unit/fetch-tool.test.js b/packages/scratch-storage/test/unit/fetch-tool.test.js
new file mode 100644
index 00000000000..3964035f443
--- /dev/null
+++ b/packages/scratch-storage/test/unit/fetch-tool.test.js
@@ -0,0 +1,57 @@
+const TextDecoder = require('util').TextDecoder;
+
+const mockFetch = require('../fixtures/mockFetch.js');
+jest.spyOn(global, 'fetch').mockImplementation(mockFetch.fetch);
+
+const {FetchTool} = require('../../src/FetchTool');
+
+test('send success returns response.text()', async () => {
+ const tool = new FetchTool();
+
+ const result = await tool.send({url: 'http://example.com/200'});
+ expect(result).toBe(mockFetch.successText);
+});
+
+test('send failure returns response.status', async () => {
+ const tool = new FetchTool();
+
+ const catcher = jest.fn();
+
+ try {
+ await tool.send({url: 'http://example.com/500'});
+ } catch (e) {
+ catcher(e);
+ }
+
+ expect(catcher).toHaveBeenCalledWith(500);
+});
+
+test('get success returns Uint8Array.body(response.arrayBuffer())', async () => {
+ const encoding = 'utf-8';
+ const decoder = new TextDecoder(encoding);
+
+ const tool = new FetchTool();
+
+ const result = await tool.get({url: 'http://example.com/200'});
+ expect(decoder.decode(result)).toBe(mockFetch.successText);
+});
+
+test('get with 404 response returns null data', async () => {
+ const tool = new FetchTool();
+
+ const result = await tool.get({url: 'http://example.com/404'});
+ expect(result).toBeNull();
+});
+
+test('get failure returns response.status', async () => {
+ const tool = new FetchTool();
+ const catcher = jest.fn();
+
+ try {
+ await tool.get({url: 'http://example.com/500'});
+ } catch (e) {
+ catcher(e);
+ }
+
+ expect(catcher).toHaveBeenCalledWith(500);
+});
diff --git a/packages/scratch-storage/test/unit/load-default-assets.test.js b/packages/scratch-storage/test/unit/load-default-assets.test.js
new file mode 100644
index 00000000000..443c0a94cb4
--- /dev/null
+++ b/packages/scratch-storage/test/unit/load-default-assets.test.js
@@ -0,0 +1,67 @@
+const md5 = require('js-md5');
+
+const {ScratchStorage} = require('../../src/ScratchStorage');
+
+// Hash and file size of each default asset
+const knownSizes = {
+ '8e768a5a5a01891b05c01c9ca15eb6aa': 255,
+ 'b586745b98e94d7574f7f7b48d831e20': 46,
+ 'e5cb3b2aa4e1a9b4c735c3415e507e66': 925
+};
+
+const getDefaultAssetTypes = storage => {
+ const defaultAssetTypes = [storage.AssetType.ImageBitmap, storage.AssetType.ImageVector, storage.AssetType.Sound];
+ return defaultAssetTypes;
+};
+
+const getDefaultAssetIds = (storage, defaultAssetTypes) => {
+ const defaultIds = {};
+ for (const assetType of defaultAssetTypes) {
+ const id = storage.getDefaultAssetId(assetType);
+ defaultIds[assetType.name] = id;
+ }
+ return defaultIds;
+};
+
+test('constructor', () => {
+ const storage = new ScratchStorage();
+ expect(storage).toBeInstanceOf(ScratchStorage);
+});
+
+test('getDefaultAssetId', () => {
+ const storage = new ScratchStorage();
+ const defaultAssetTypes = getDefaultAssetTypes(storage);
+ const defaultIds = getDefaultAssetIds(storage, defaultAssetTypes);
+ for (const assetType of defaultAssetTypes) {
+ const id = defaultIds[assetType.name];
+ expect(typeof id).toBe('string');
+ }
+});
+
+test('load', () => {
+ const storage = new ScratchStorage();
+ const defaultAssetTypes = getDefaultAssetTypes(storage);
+ const defaultIds = getDefaultAssetIds(storage, defaultAssetTypes);
+
+ const promises = [];
+ const checkAsset = (assetType, id, asset) => {
+ expect(asset).toBeInstanceOf(storage.Asset);
+ expect(asset.assetId).toStrictEqual(id);
+ expect(asset.assetType).toStrictEqual(assetType);
+ expect(asset.data.length).toBeTruthy();
+ expect(asset.data.length).toBe(knownSizes[id]);
+ expect(md5(asset.data)).toBe(id);
+ };
+ for (const assetType of defaultAssetTypes) {
+ const id = defaultIds[assetType.name];
+
+ const promise = storage.load(assetType, id);
+ expect(promise).toBeInstanceOf(Promise);
+
+ const checkedPromise = promise.then(asset => checkAsset(assetType, id, asset));
+
+ promises.push(checkedPromise);
+ }
+
+ return Promise.all(promises);
+});
diff --git a/packages/scratch-storage/test/unit/metadata.test.js b/packages/scratch-storage/test/unit/metadata.test.js
new file mode 100644
index 00000000000..a31bdc0f126
--- /dev/null
+++ b/packages/scratch-storage/test/unit/metadata.test.js
@@ -0,0 +1,129 @@
+const mockFetch = require('../fixtures/mockFetch.js');
+jest.spyOn(global, 'fetch').mockImplementation(mockFetch.fetch);
+
+beforeEach(() => {
+ // reset the metadata container to ensure the tests don't interfere with each other
+ // but this also means we need to `require` inside the tests
+ jest.resetModules();
+
+ // temporary: pretend we're running in a browser and the URL has scratchMetadata=1
+ // this is a hack to enable the metadata feature in tests
+ // see also `hasMetadata` in scratchFetch.js
+ global.self = global.self || {};
+ global.self.location = new URL('https://example.com/?scratchMetadata=1');
+});
+
+test('get without metadata', async () => {
+ const {FetchTool} = require('../../src/FetchTool');
+ const tool = new FetchTool();
+
+ const mockFetchTestData = {};
+ const result = await tool.get({url: 'http://example.com/200', mockFetchTestData});
+
+ expect(result).toBeInstanceOf(Uint8Array);
+ expect(mockFetchTestData.headers).toBeTruthy();
+ expect(mockFetchTestData.headersCount).toBe(0);
+});
+
+test('get with metadata', async () => {
+ const {FetchTool} = require('../../src/FetchTool');
+ const ScratchFetch = require('../../src/scratchFetch');
+ const {RequestMetadata, setMetadata} = ScratchFetch;
+
+ const tool = new FetchTool();
+
+ setMetadata(RequestMetadata.ProjectId, 1234);
+ setMetadata(RequestMetadata.RunId, 5678);
+
+ const mockFetchTestData = {};
+ const result = await tool.get({url: 'http://example.com/200', mockFetchTestData});
+
+ expect(result).toBeInstanceOf(Uint8Array);
+ expect(mockFetchTestData.headers).toBeTruthy();
+ expect(mockFetchTestData.headersCount).toBe(2);
+ expect(mockFetchTestData.headers?.get(RequestMetadata.ProjectId)).toBe('1234');
+ expect(mockFetchTestData.headers?.get(RequestMetadata.RunId)).toBe('5678');
+});
+
+test('send without metadata', async () => {
+ const {FetchTool} = require('../../src/FetchTool');
+ const tool = new FetchTool();
+
+ const mockFetchTestData = {};
+ const result = await tool.send({url: 'http://example.com/200', mockFetchTestData});
+
+ expect(typeof result).toBe('string');
+ expect(mockFetchTestData.headers).toBeTruthy();
+ expect(mockFetchTestData.headersCount).toBe(0);
+});
+
+test('send with metadata', async () => {
+ const {FetchTool} = require('../../src/FetchTool');
+ const ScratchFetch = require('../../src/scratchFetch');
+ const {RequestMetadata, setMetadata} = ScratchFetch;
+
+ const tool = new FetchTool();
+
+ setMetadata(RequestMetadata.ProjectId, 4321);
+ setMetadata(RequestMetadata.RunId, 8765);
+
+ const mockFetchTestData = {};
+ const result = await tool.send({url: 'http://example.com/200', mockFetchTestData});
+
+ expect(typeof result).toBe('string');
+ expect(mockFetchTestData.headers).toBeTruthy();
+ expect(mockFetchTestData.headersCount).toBe(2);
+ expect(mockFetchTestData.headers?.get(RequestMetadata.ProjectId)).toBe('4321');
+ expect(mockFetchTestData.headers?.get(RequestMetadata.RunId)).toBe('8765');
+});
+
+test('selectively delete metadata', async () => {
+ const {FetchTool} = require('../../src/FetchTool');
+ const ScratchFetch = require('../../src/scratchFetch');
+ const {RequestMetadata, setMetadata, unsetMetadata} = ScratchFetch;
+
+ // verify that these special values are preserved and not interpreted as "delete"
+ setMetadata(RequestMetadata.ProjectId, null);
+ setMetadata(RequestMetadata.RunId, void 0); // void 0 = undefined
+
+ const tool = new FetchTool();
+
+ const mockFetchTestData = {};
+
+ const result1 = await tool.send({url: 'http://example.com/200', mockFetchTestData});
+ expect(typeof result1).toBe('string');
+ expect(mockFetchTestData.headers).toBeTruthy();
+
+ expect(mockFetchTestData.headersCount).toBe(2);
+ expect(mockFetchTestData.headers?.get(RequestMetadata.ProjectId)).toBe('null'); // string "null" means it's present
+ expect(mockFetchTestData.headers?.get(RequestMetadata.RunId)).toBe('undefined');
+
+ // remove the Project ID from metadata
+ unsetMetadata(RequestMetadata.ProjectId);
+
+ const result2 = await tool.send({url: 'http://example.com/200', mockFetchTestData});
+ expect(typeof result2).toBe('string');
+ expect(mockFetchTestData.headers).toBeTruthy();
+
+ expect(mockFetchTestData.headersCount).toBe(1);
+ expect(mockFetchTestData.headers?.get(RequestMetadata.ProjectId)).toBeNull(); // value `null` means it's present
+ expect(mockFetchTestData.headers?.get(RequestMetadata.RunId)).toBe('undefined');
+});
+
+test('metadata has case-insensitive keys', async () => {
+ const {FetchTool} = require('../../src/FetchTool');
+ const ScratchFetch = require('../../src/scratchFetch');
+ const {setMetadata} = ScratchFetch;
+
+ setMetadata('foo', 1);
+ setMetadata('FOO', 2);
+
+ const tool = new FetchTool();
+
+ const mockFetchTestData = {};
+ await tool.get({url: 'http://example.com/200', mockFetchTestData});
+
+ expect(mockFetchTestData.headers).toBeTruthy();
+ expect(mockFetchTestData.headersCount).toBe(1);
+ expect(mockFetchTestData.headers?.get('foo')).toBe('2');
+});
diff --git a/packages/scratch-storage/tsconfig.json b/packages/scratch-storage/tsconfig.json
new file mode 100644
index 00000000000..7ed522dc679
--- /dev/null
+++ b/packages/scratch-storage/tsconfig.json
@@ -0,0 +1,29 @@
+{
+ "include": ["src"],
+ "compilerOptions": {
+ /* Visit https://aka.ms/tsconfig to read more about this file */
+
+ /* Language and Environment */
+ "target": "ESNext",
+ "allowJs": true,
+
+ /* Modules */
+ "module": "Preserve",
+
+ /* Emit */
+ "declaration": true,
+ "sourceMap": true,
+ "outDir": "./dist/types/",
+
+ /* Interop Constraints */
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+
+ /* Type Checking */
+ "strict": true,
+ "noImplicitAny": false,
+
+ /* Completeness */
+ "skipLibCheck": true
+ }
+}
diff --git a/packages/scratch-storage/tsconfig.test.json b/packages/scratch-storage/tsconfig.test.json
new file mode 100644
index 00000000000..bce5bb1799e
--- /dev/null
+++ b/packages/scratch-storage/tsconfig.test.json
@@ -0,0 +1,12 @@
+{
+ "include": ["test"],
+ "extends": ["./tsconfig.json"],
+ "compilerOptions": {
+ /* Visit https://aka.ms/tsconfig to read more about this file */
+
+ /* Modules */
+ "isolatedModules": true, // for ts-jest
+ "module": "CommonJS",
+ "types": ["jest", "./src/types.d.ts"],
+ }
+}
diff --git a/packages/scratch-storage/webpack.config.js b/packages/scratch-storage/webpack.config.js
new file mode 100644
index 00000000000..73682fc36ee
--- /dev/null
+++ b/packages/scratch-storage/webpack.config.js
@@ -0,0 +1,77 @@
+const path = require('path');
+const webpack = require('webpack');
+
+const ScratchWebpackConfigBuilder = require('scratch-webpack-configuration');
+
+const baseConfig = new ScratchWebpackConfigBuilder(
+ {
+ rootPath: path.resolve(__dirname),
+ enableReact: false,
+ enableTs: true,
+ shouldSplitChunks: false
+ })
+ .setTarget('browserslist')
+ .merge({
+ resolve: {
+ fallback: {
+ Buffer: require.resolve('buffer/')
+ }
+ }
+ });
+
+if (!process.env.CI) {
+ baseConfig.addPlugin(new webpack.ProgressPlugin());
+}
+
+// Web-compatible
+const webConfig = baseConfig.clone()
+ .merge({
+ output: {
+ library: {
+ name: 'ScratchStorage',
+ type: 'umd2'
+ },
+ path: path.resolve(__dirname, 'dist', 'web'),
+ publicPath: 'auto',
+ clean: false
+ }
+ });
+
+const webNonMinConfig = webConfig.clone()
+ .merge({
+ entry: {
+ 'scratch-storage': path.join(__dirname, './src/index.ts')
+ },
+ optimization: {
+ minimize: false
+ }
+ });
+
+const webMinConfig = webConfig.clone()
+ .merge({
+ entry: {
+ 'scratch-storage.min': path.join(__dirname, './src/index.ts')
+ },
+ optimization: {
+ minimize: true
+ }
+ });
+
+// Node-compatible
+const nodeConfig = baseConfig.clone()
+ .merge({
+ entry: {
+ 'scratch-storage': path.join(__dirname, './src/index.ts')
+ },
+ output: {
+ library: {
+ type: 'commonjs2'
+ },
+ chunkFormat: 'commonjs',
+ path: path.resolve(__dirname, 'dist', 'node'),
+ clean: false
+ }
+ })
+ .addExternals(['base64-js', 'js-md5', 'localforage', 'text-encoding']);
+
+module.exports = [webNonMinConfig.get(), webMinConfig.get(), nodeConfig.get()];
diff --git a/packages/scratch-vm/package.json b/packages/scratch-vm/package.json
index 37ae7f98e7e..0ecfa8d8e6b 100644
--- a/packages/scratch-vm/package.json
+++ b/packages/scratch-vm/package.json
@@ -61,6 +61,7 @@
},
"dependencies": {
"@scratch/scratch-render": "12.6.1",
+ "@scratch/scratch-storage": "12.6.1",
"@scratch/scratch-svg-renderer": "12.6.1",
"@vernier/godirect": "1.8.3",
"arraybuffer-loader": "1.0.8",
@@ -76,7 +77,6 @@
"scratch-audio": "2.0.268",
"scratch-parser": "6.0.0",
"scratch-sb1-converter": "2.0.279",
- "scratch-storage": "6.1.3",
"scratch-translate-extension-languages": "1.0.7",
"text-encoding": "0.7.0",
"tslog": "4.10.2",
diff --git a/packages/scratch-vm/src/engine/runtime.js b/packages/scratch-vm/src/engine/runtime.js
index ddcf55b1af8..83ec249ba77 100644
--- a/packages/scratch-vm/src/engine/runtime.js
+++ b/packages/scratch-vm/src/engine/runtime.js
@@ -33,7 +33,7 @@ const StringUtil = require('../util/string-util');
const uid = require('../util/uid');
/**
- * @import {ScratchStorage} from 'scratch-storage'
+ * @import {ScratchStorage} from '@scratch/scratch-storage'
*/
const defaultBlockPackages = {
diff --git a/packages/scratch-vm/src/playground/benchmark.js b/packages/scratch-vm/src/playground/benchmark.js
index ef2e0f25cd5..5cf3542b187 100644
--- a/packages/scratch-vm/src/playground/benchmark.js
+++ b/packages/scratch-vm/src/playground/benchmark.js
@@ -43,7 +43,7 @@ const importLoadSound = require('../import/load-sound');
const soundMiddleware = new LoadingMiddleware();
importLoadSound.loadSound = soundMiddleware.install(importLoadSound, importLoadSound.loadSound);
-const ScratchStorage = require('scratch-storage').ScratchStorage;
+const ScratchStorage = require('@scratch/scratch-storage').ScratchStorage;
const VirtualMachine = require('..');
const Runtime = require('../engine/runtime');
diff --git a/packages/scratch-vm/test/fixtures/make-test-storage.js b/packages/scratch-vm/test/fixtures/make-test-storage.js
index fa24b1b9417..027ab8e4577 100644
--- a/packages/scratch-vm/test/fixtures/make-test-storage.js
+++ b/packages/scratch-vm/test/fixtures/make-test-storage.js
@@ -1,4 +1,4 @@
-const ScratchStorage = require('scratch-storage').ScratchStorage;
+const ScratchStorage = require('@scratch/scratch-storage').ScratchStorage;
const ASSET_SERVER = 'https://cdn.assets.scratch.mit.edu/';
const PROJECT_SERVER = 'https://cdn.projects.scratch.mit.edu/';
diff --git a/packages/scratch-vm/test/integration/offline-custom-assets.js b/packages/scratch-vm/test/integration/offline-custom-assets.js
index 724658642f5..44e17b42699 100644
--- a/packages/scratch-vm/test/integration/offline-custom-assets.js
+++ b/packages/scratch-vm/test/integration/offline-custom-assets.js
@@ -8,7 +8,7 @@ const path = require('path');
const fs = require('fs');
const test = require('tap').test;
const AdmZip = require('adm-zip');
-const ScratchStorage = require('scratch-storage').ScratchStorage;
+const ScratchStorage = require('@scratch/scratch-storage').ScratchStorage;
const VirtualMachine = require('../../src/index');
const {sanitizeByteStream} = require('../../../scratch-svg-renderer/src/sanitize-svg');
diff --git a/packages/scratch-vm/webpack.config.js b/packages/scratch-vm/webpack.config.js
index 90939c40f94..f8cf17d8255 100644
--- a/packages/scratch-vm/webpack.config.js
+++ b/packages/scratch-vm/webpack.config.js
@@ -102,7 +102,7 @@ const playgroundBuilder = webBuilder
}
})
.addModuleRule({
- test: require.resolve('scratch-storage'),
+ test: require.resolve('@scratch/scratch-storage'),
loader: 'expose-loader',
options: {
exposes: 'ScratchStorage ScratchStorage'
@@ -123,7 +123,7 @@ const playgroundBuilder = webBuilder
to: 'media'
},
{
- from: '../../node_modules/scratch-storage/dist/web'
+ from: '../../node_modules/@scratch/scratch-storage/dist/web'
},
{
from: '../../node_modules/@scratch/scratch-render/dist/web'
diff --git a/packages/task-herder/README.md b/packages/task-herder/README.md
index 7be51fa8853..8f8e28b4fb3 100644
--- a/packages/task-herder/README.md
+++ b/packages/task-herder/README.md
@@ -25,7 +25,7 @@ Queue will then resolve or reject based on the outcome of the task.
## Usage
```javascript
-import TaskQueue from 'task-herder'
+import TaskQueue from '@scratch/task-herder'
const queue = new TaskQueue({
// The maximum number of tokens in the bucket controls the burst limit
diff --git a/scripts/add-to-monorepo.sh b/scripts/add-to-monorepo.sh
new file mode 100755
index 00000000000..3a9b5798a10
--- /dev/null
+++ b/scripts/add-to-monorepo.sh
@@ -0,0 +1,358 @@
+#!/usr/bin/env bash
+
+set -e
+
+### Command-line arguments ###
+
+if [ "$#" -ne 1 ]; then
+ echo "Usage: $0 repo_name"
+ echo "Example: $0 scratch-foo"
+ echo ""
+ echo "This script will add the specified repository to the current branch of the monorepo in the current directory."
+ exit 1
+fi
+
+SRC_REPO="$1"
+
+### Configuration ###
+
+# All repositories are assumed to be hosted in this GitHub org
+GITHUB_ORG="scratchfoundation"
+
+# All packages are assumed to be published under this npm organization
+NPM_ORGANIZATION="@scratch"
+
+# This is the directory where you have a copy of all the repositories you want to merge.
+# This script will run `git fetch` on these repos, but otherwise will not modify them.
+BUILD_CACHE="./.."
+
+# Temporary clones will be placed here. If the script completes successfully, this directory will be deleted.
+BUILD_TMP="./monorepo.tmp"
+
+# Use ${BASE_COMMIT} from ${BASE_REPO} as the starting point for the monorepo.
+BASE_COMMIT="$(git rev-parse HEAD)"
+
+# Limit the threads and memory used by git repack & git gc. This script only uses these values in final optimization.
+# If you see "error: pack-objects died of signal 9" or an out-of-memory error, try reducing one or both.
+# In my experiments, the maximum memory used was around 2.2 * GIT_PACK_THREADS * GIT_PACK_WINDOW_MEMORY.
+# Values above 512m did not seem to improve compression in my tests. The cutoff is somewhere between 256m and 512m.
+# See git documentation for pack.threads and pack.windowMemory for more information.
+# Increasing threads speeds up the operation, but uses more CPU and memory.
+# Increasing windowMemory may compress the .git directory better, but takes more time and uses more memory.
+# Setting threads to zero will tell git to detect your CPU count.
+# Setting window memory to zero will remove the limit.
+# WARNING: on some configurations, window memory is stored in a signed 32-bit integer, so the maximum value is ~2047m.
+GIT_PACK_THREADS="8"
+GIT_PACK_WINDOW_MEMORY="512m"
+
+# Options to speed up `npm install` during the fixup phase
+NPM_QUICK_OPTS="--prefer-offline --no-audit --no-fund"
+
+### End configuration ###
+
+### Functions ###
+
+# Thanks to https://stackoverflow.com/a/17841619
+join_args () {
+ local d=${1-} f=${2-}
+ if shift 2; then
+ printf %s "$f" "${@/#/$d}"
+ fi
+}
+
+add_repo_to_monorepo () {
+ REPO_NAME="$1"
+ ORG_AND_REPO_NAME="${GITHUB_ORG}/${REPO_NAME}"
+ echo "Working on $ORG_AND_REPO_NAME"
+
+ clone_repository $REPO_NAME
+
+ move_repository_subdirectory $REPO_NAME "packages/${REPO_NAME}"
+
+ #
+ # Merge branches in
+ #
+
+ REMOTE_NAME="temp-$REPO_NAME"
+ git remote add "$REMOTE_NAME" "$(realpath "${BUILD_TMP}")/${REPO_NAME}"
+ git fetch --no-tags "$REMOTE_NAME"
+
+ SRC_BRANCH="$(default_branch)"
+
+ MERGE_MESSAGE="feat(deps): add ${REPO_NAME}#${SRC_BRANCH} as packages/${REPO_NAME}"
+ git merge --no-ff --allow-unrelated-histories "${REMOTE_NAME}/${SRC_BRANCH}" -m "$MERGE_MESSAGE"
+
+ git remote remove "$REMOTE_NAME"
+ rm -rf "${BUILD_TMP}/${REPO_NAME}"
+}
+
+clone_repository() {
+ REPO_NAME="$1"
+ ORG_AND_REPO_NAME="${GITHUB_ORG}/${REPO_NAME}"
+
+ #
+ # Clone
+ #
+
+ # refresh the cache
+ git -C "${BUILD_CACHE}/${REPO_NAME}" fetch --all
+ # reference = go faster
+ git -C "$BUILD_TMP" clone --bare --dissociate --reference "$(realpath "$BUILD_CACHE")/${REPO_NAME}" "git@github.com:${ORG_AND_REPO_NAME}.git" "${REPO_NAME}"
+ # get ready to disconnect reference repo
+ git -C "${BUILD_TMP}/${REPO_NAME}" repack -a
+ # actually disconnect the reference repo
+ rm -f "${BUILD_TMP}/${REPO_NAME}/.git/objects/info/alternates"
+}
+
+move_repository_subdirectory() {
+ REPO_NAME="$1"
+ SUBDIRECTORY="$2"
+
+ #
+ # Move to subdirectory
+ #
+
+ # make filter-repo accept this as a fresh clone
+ git -C "${BUILD_TMP}/${REPO_NAME}" gc
+
+ HAS_SUBMODULES=$(
+ git -C "${BUILD_TMP}/${REPO_NAME}" branch --format="%(refname:short)" | while read BRANCH; do
+ if git -C "${BUILD_TMP}/${REPO_NAME}" cat-file -e "${BRANCH}:.gitmodules" &> /dev/null; then
+ echo "yep"
+ break;
+ fi
+ done
+ )
+
+ # rewrite history as if all this work happened in a subdirectory
+ # "git mv" is simpler but makes history much less visible
+ if [ "$HAS_SUBMODULES" != "yep" ]; then
+ echo "Repository ${REPO_NAME} does NOT have submodules"
+ # this is significantly faster than the special case below
+ git -C "${BUILD_TMP}/${REPO_NAME}" filter-repo --to-subdirectory-filter $SUBDIRECTORY
+ else
+ echo "Repository ${REPO_NAME} DOES have submodules"
+ # the .gitmodules file must stay in the repository root, but the paths inside it must be rewritten
+ # this is complicated for the reasons described here: https://github.com/newren/git-filter-repo/issues/158
+ # this is also slower, so we only do it for repositories that have submodules
+ # if we have more than one, this will cause merge conflicts
+ git -C "${BUILD_TMP}/${REPO_NAME}" filter-repo \
+ --filename-callback "return filename if filename == b'.gitmodules' else b'${SUBDIRECTORY}'+filename" \
+ --blob-callback "if blob.data.startswith(b'[submodule '): blob.data = blob.data.replace(b'path = ', b'path = ${SUBDIRECTORY}')"
+ fi
+}
+
+default_branch () {
+ BRANCH="develop"
+
+ if [ -z "$(git -C "${BUILD_TMP}/${REPO_NAME}" branch --list "$BRANCH")" ]; then
+ BRANCH="main"
+
+ if [ -z "$(git -C "${BUILD_TMP}/${REPO_NAME}" branch --list "$BRANCH")" ]; then
+ BRANCH="master"
+ fi
+ fi
+
+ echo "$BRANCH"
+}
+
+# Perform monorepo fixups on a package.
+# Mostly: remove "global" files from subdirectories and localize dependencies.
+# $1: the name of the package to fix up
+fixup_package () {
+ PACKAGE="$1"
+
+ if [ ! -r "./packages/"$PACKAGE"/package.json" ]; then
+ # This repository doesn't exist in this branch
+ echo "Warning: Package $PACKAGE does not exist in this branch"
+ return
+ fi
+
+ # remove repository-level configuration and dependencies, like Renovate and Husky
+ # do not remove configuration and dependencies that could vary between packages, like semantic-release
+ # do not remove content like .github/ that may be useful as reference when building the monorepo equivalent
+ # it would be nice to merge all the package-lock.json files into one but it's not clear how to do that
+ # just remove the package-lock.json files for now, and build a new one with "npm i" later
+ rm -rf ./packages/"$PACKAGE"/{.husky,package-lock.json,renovate.json*}
+
+ jq -f \
+ --arg PACKAGE_NAME "$NPM_ORGANIZATION/$PACKAGE" \
+ --arg MONOREPO_AUTHOR "$MONOREPO_AUTHOR" \
+ --arg MONOREPO_LICENSE "$MONOREPO_LICENSE" \
+ --arg MONOREPO_VERSION "$MONOREPO_VERSION" \
+ <(join_args ' | ' \
+ '.name |= $PACKAGE_NAME' \
+ '.version |= $MONOREPO_VERSION' \
+ 'del(.repository.sha)' \
+ '.license |= $MONOREPO_LICENSE' \
+ '.author |= $MONOREPO_AUTHOR' \
+ 'if .scripts.prepare == "husky install" then del(.scripts.prepare) else . end' \
+ 'if .scripts == {} then del(.scripts.prepare) else . end' \
+ 'del(.config.commitizen)' \
+ 'if .config == {} then del(.config) else . end' \
+ 'del(.devDependencies."@commitlint/cli")' \
+ 'del(.devDependencies."@commitlint/config-conventional")' \
+ 'del(.devDependencies."@commitlint/travis-cli")' \
+ 'del(.devDependencies."cz-conventional-changelog")' \
+ 'del(.devDependencies."husky")' \
+ 'if .devDependencies == {} then del(.devDependencies) else . end' \
+ ) "./packages/${PACKAGE}/package.json" | sponge "./packages/${PACKAGE}/package.json"
+
+ npm init -y -w "./packages/${PACKAGE}"
+ sort-package-json "./packages/${PACKAGE}/package.json"
+ npm i --package-lock-only # sometimes this is necessary to get a consistent package-lock.json
+ git add package.json package-lock.json "./packages/${PACKAGE}/"
+
+ git commit -m "fix: update ${PACKAGE} name, deps, etc., for monorepo"
+}
+
+# Replace any dependencies that are within the monorepo with their monorepo version
+fixup_deps () {
+ PACKAGE_DIR="$1"
+
+ echo "Fixing up dependencies for $PACKAGE_DIR"
+ echo "Possible dependencies: ${ALL_PACKAGE_NAMES[@]}"
+
+ REMOVEDEPS=""
+ DEPS=""
+ DEVDEPS=""
+ OPTDEPS=""
+ PEERDEPS=""
+ for DEP in "${ALL_PACKAGE_NAMES[@]}"; do
+ if jq -e .dependencies.\"$DEP\" "./packages/${PACKAGE_DIR}/package.json" > /dev/null; then
+ jq "del(.dependencies.\"$DEP\")" "./packages/${PACKAGE_DIR}/package.json" | sponge "./packages/${PACKAGE_DIR}/package.json"
+ DEPS="$DEPS $DEP@*"
+ fi
+ if jq -e .devDependencies.\"$DEP\" "./packages/${PACKAGE_DIR}/package.json" > /dev/null; then
+ jq "del(.devDependencies.\"$DEP\")" "./packages/${PACKAGE_DIR}/package.json" | sponge "./packages/${PACKAGE_DIR}/package.json"
+ DEVDEPS="$DEVDEPS $DEP@*"
+ fi
+ if jq -e .optionalDependencies.\"$DEP\" "./packages/${PACKAGE_DIR}/package.json" > /dev/null; then
+ jq "del(.optionalDependencies.\"$DEP\")" "./packages/${PACKAGE_DIR}/package.json" | sponge "./packages/${PACKAGE_DIR}/package.json"
+ OPTDEPS="$OPTDEPS $DEP@*"
+ fi
+ if jq -e .peerDependencies.\"$DEP\" "./packages/${PACKAGE_DIR}/package.json" > /dev/null; then
+ jq "del(.peerDependencies.\"$DEP\")" "./packages/${PACKAGE_DIR}/package.json" | sponge "./packages/${PACKAGE_DIR}/package.json"
+ PEERDEPS="$PEERDEPS $DEP@*"
+ fi
+
+ npm uninstall "$DEP"
+ done
+ for DEP in $DEPS; do
+ npm install --force --save --save-exact "$NPM_ORGANIZATION/$DEP" -w "$NPM_ORGANIZATION/$PACKAGE_DIR" || package_replacement_error "$PACKAGE_DIR" "$DEP"
+ done
+ for DEP in $DEVDEPS; do
+ npm install --force --save-dev --save-exact "$NPM_ORGANIZATION/$DEP" -w "$NPM_ORGANIZATION/$PACKAGE_DIR" || package_replacement_error "$PACKAGE_DIR" "$DEP"
+ done
+ for DEP in $OPTDEPS; do
+ npm install --force --save-optional --save-exact "$NPM_ORGANIZATION/$DEP" -w "$NPM_ORGANIZATION/$PACKAGE_DIR" || package_replacement_error "$PACKAGE_DIR" "$DEP"
+ done
+ for DEP in $PEERDEPS; do
+ npm install --force --save-peer --save-exact "$NPM_ORGANIZATION/$DEP" -w "$NPM_ORGANIZATION/$PACKAGE_DIR" || package_replacement_error "$PACKAGE_DIR" "$DEP"
+ done
+
+ # replace the name of the package with the organization prefixed one
+ for DEP in "${ALL_PACKAGE_NAMES[@]}"; do
+ find "./packages/${PACKAGE_DIR}" -type f -exec sed -i -e "s:\(require(\|from\s\|resolve(\|node_modules\)\(['\"/]\)$DEP\(['\"/]\):\1\2$NPM_ORGANIZATION/$DEP\3:g" {} \;
+ done
+
+ sort-package-json "./packages/${PACKAGE_DIR}/package.json"
+}
+
+# Report that replacing a dependency with the local monorepo version failed
+# $1: the name of the repository
+# $2: the dependency that failed to install
+package_replacement_error () {
+ echo "***ERROR***"
+ echo "Could not replace a dependency with the local monorepo version."
+ echo "Failed to replace $2 in $1" | tee -a "monorepo.errors.log"
+ #exit 1 # uncomment this to make it a fatal error
+ echo "Attempting to continue anyway..."
+}
+
+### Pre-flight checks ###
+
+if ! git filter-repo -h &> /dev/null; then
+ echo "Please install git-filter-repo. One of these commands might work:"
+ echo "- brew install git-filter-repo"
+ echo "- sudo apt install git-filter-repo"
+ exit 1
+fi
+
+if ! sponge --help &> /dev/null; then
+ echo "Please install the 'sponge' command."
+ echo "You may want: sudo apt install moreutils"
+ exit 1
+fi
+
+if [ ! -d "$BUILD_CACHE" ]; then
+ echo "Please link $BUILD_CACHE to a directory with a copy of all the repositories you want to merge."
+ echo "For example, if you have ~/GitHub/scratch-audio, ~/GitHub/scratch-blocks, etc., then run:"
+ echo "ln -s ~/GitHub $BUILD_CACHE"
+ exit 1
+fi
+
+if [ -d "$BUILD_TMP" ]; then
+ echo "Please remove $BUILD_TMP before running this script."
+ echo "You may want: rm -rf $BUILD_TMP"
+ exit 1
+fi
+
+if [ -n "$(git status --porcelain)" ]; then
+ echo "Please commit or stash your changes before running this script."
+ exit 1
+fi
+
+### Do the things! ###
+
+echo "This may take a long time! Make sure you have plenty of space on your drive."
+echo "Press Ctrl-C now to cancel!"
+echo "Starting in 15 seconds..."
+sleep 15
+
+mkdir -p "$BUILD_TMP"
+
+set -x
+
+MONOREPO_AUTHOR="$(jq -r .author "./package.json")"
+MONOREPO_LICENSE="$(jq -r .license "./package.json")"
+MONOREPO_VERSION="$(jq -r .version "./package.json")"
+
+add_repo_to_monorepo "$SRC_REPO"
+
+rmdir "$BUILD_TMP"
+
+# Collect package dirs/names AFTER adding the new repo
+# Note that the package names do NOT include the organization prefix
+mapfile -t ALL_PACKAGE_DIRS < <(cd packages/ && for P in */package.json; do echo "${P%/*}"; done)
+mapfile -t ALL_PACKAGE_NAMES < <(for P in "${ALL_PACKAGE_DIRS[@]}"; do node -p "require('./packages/$P/package.json').name.replace('$NPM_ORGANIZATION/', '')"; done)
+
+echo "ALL_PACKAGE_DIRS: ${ALL_PACKAGE_DIRS[@]}"
+echo "ALL_PACKAGE_NAMES: ${ALL_PACKAGE_NAMES[@]}"
+
+fixup_package "$SRC_REPO"
+
+for PKG_DIR in "${ALL_PACKAGE_DIRS[@]}"; do
+ fixup_deps "$PKG_DIR"
+done
+npm i --package-lock-only
+npm i --package-lock-only
+git add .
+git commit -m "fix(deps): use workspace versions of $SRC_REPO and other packages"
+
+cat < /dev/null; then
- echo "Please install git-filter-repo. One of these commands might work:"
- echo "- brew install git-filter-repo"
- echo "- sudo apt install git-filter-repo"
- exit 1
-fi
-
-if ! sponge --help &> /dev/null; then
- echo "Please install the 'sponge' command."
- echo "You may want: sudo apt install moreutils"
- exit 1
-fi
-
-if [ ! -d "$BUILD_CACHE" ]; then
- echo "Please link $BUILD_CACHE to a directory with a copy of all the repositories you want to merge."
- echo "For example, if you have ~/GitHub/scratch-audio, ~/GitHub/scratch-blocks, etc., then run:"
- echo "ln -s ~/GitHub $BUILD_CACHE"
- exit 1
-fi
-
-if [ -d "$BUILD_TMP" ]; then
- echo "Please remove $BUILD_TMP before running this script."
- echo "You may want: rm -rf $BUILD_TMP $BUILD_OUT"
- exit 1
-fi
-
-if [ -d "$BUILD_OUT" ]; then
- echo "Please remove $BUILD_OUT before running this script."
- echo "You may want: rm -rf $BUILD_TMP $BUILD_OUT"
- exit 1
-fi
-
-# Thanks to https://stackoverflow.com/a/17841619
-join_args () {
- local d=${1-} f=${2-}
- if shift 2; then
- printf %s "$f" "${@/#/$d}"
- fi
-}
-
-init_monorepo () {
- git init "$BUILD_OUT"
- git -C "$BUILD_OUT" remote add origin "git@github.com:${GITHUB_ORG}/${BASE_REPO}.git"
- git -C "$BUILD_OUT" fetch --all # to make sure BASE_COMMIT is available
-}
-
-add_repo_to_monorepo () {
- REPO_NAME="$1"
- ORG_AND_REPO_NAME="${GITHUB_ORG}/${REPO_NAME}"
- echo "Working on $ORG_AND_REPO_NAME"
-
- clone_repository $REPO_NAME
-
- move_repository_subdirectory $REPO_NAME "packages/${REPO_NAME}"
-
- #
- # Merge branches in
- #
-
- REMOTE_NAME="temp-$REPO_NAME"
- git -C "$BUILD_OUT" remote add "$REMOTE_NAME" "$(realpath "${BUILD_TMP}")/${REPO_NAME}"
- git -C "$BUILD_OUT" fetch --no-tags "$REMOTE_NAME"
-
- for DEST_BRANCH in $DEST_BRANCHES; do
- BRANCH=""
- case "$DEST_BRANCH" in
- develop|main)
- if [ -z "$(git -C "${BUILD_TMP}/${REPO_NAME}" branch --list "$DEST_BRANCH")" ]; then
- BRANCH=$(default_branch)
- else
- BRANCH="$DEST_BRANCH"
- fi
- ;;
- scratch-android)
- if [ "$REPO_NAME" = "scratch-gui" ]; then
- BRANCH="native"
- elif [ "$(git -C "${BUILD_TMP}/${REPO_NAME}" branch --list "develop")" ]; then
- BRANCH="develop"
- else
- BRANCH=$(default_branch)
- fi
- ;;
- scratch-desktop)
- if [ "$REPO_NAME" = "scratch-gui" ]; then
- BRANCH="$DEST_BRANCH"
- elif [ "$(git -C "${BUILD_TMP}/${REPO_NAME}" branch --list "develop")" ]; then
- BRANCH="develop"
- else
- BRANCH=$(default_branch)
- fi
- ;;
- esac
-
- # checkout needs `-f` to get past CRLF problems
- if [ -z "$(git -C "$BUILD_OUT" branch --list "$DEST_BRANCH")" ]; then
- # create the destination branch if it doesn't exist
- git -C "$BUILD_OUT" checkout -f --no-guess -b "$DEST_BRANCH" "$BASE_COMMIT"
- else
- # switch to existing branch
- git -C "$BUILD_OUT" checkout -f --no-guess "$DEST_BRANCH"
- fi
-
- MERGE_MESSAGE="chore(deps): add ${REPO_NAME}#${BRANCH} as packages/${REPO_NAME}"
- git -C "$BUILD_OUT" merge --no-ff --allow-unrelated-histories "${REMOTE_NAME}/${BRANCH}" -m "$MERGE_MESSAGE"
- done
-
- git -C "$BUILD_OUT" remote remove "$REMOTE_NAME"
- rm -rf "${BUILD_TMP}/${REPO_NAME}"
-}
-
-add_gh_pages () {
- REPO_NAME="$1"
- ORG_AND_REPO_NAME="${GITHUB_ORG}/${REPO_NAME}"
- echo "Working on $ORG_AND_REPO_NAME"
-
- GH_PAGES_BRANCH="gh-pages"
-
- clone_repository $REPO_NAME
-
- move_repository_subdirectory $REPO_NAME "${REPO_NAME}/"
-
- #
- # Merge branches in
- #
-
- REMOTE_NAME="temp-$REPO_NAME"
- git -C "$BUILD_OUT" remote add "$REMOTE_NAME" "$(realpath "${BUILD_TMP}")/${REPO_NAME}"
- git -C "$BUILD_OUT" fetch --no-tags "$REMOTE_NAME"
-
- if [ -z "$(git -C "$BUILD_OUT" branch --list "$GH_PAGES_BRANCH")" ]; then
- # create the destination branch if it doesn't exist
- git -C "$BUILD_OUT" symbolic-ref HEAD "refs/heads/${GH_PAGES_BRANCH}"
- rm -rf "${BUILD_OUT}/.git/index"
- git -C "$BUILD_OUT" clean -fdx
- git -C "$BUILD_OUT" checkout develop .gitignore
- git -C "$BUILD_OUT" add .
- git -C "$BUILD_OUT" commit --allow-empty -m "Initial commit for github pages"
- else
- # switch to existing branch
- git -C "$BUILD_OUT" checkout -f --no-guess "$GH_PAGES_BRANCH"
- fi
-
- MERGE_MESSAGE="chore(deps): add ${REPO_NAME}#${GH_PAGES_BRANCH} as ${REPO_NAME}"
- git -C "$BUILD_OUT" merge --no-ff --allow-unrelated-histories "${REMOTE_NAME}/${GH_PAGES_BRANCH}" -m "$MERGE_MESSAGE"
-
- git -C "$BUILD_OUT" remote remove "$REMOTE_NAME"
- rm -rf "${BUILD_TMP}/${REPO_NAME}"
-}
-
-# Repack the local git repository to save space, for example 4.4 GB -> 3.1GB.
-# This does not affect the remote repository, so if local size is not a major concern, you can skip this step.
-optimize_git_repo () {
- du -sh "$BUILD_OUT"
- #git -C "$BUILD_OUT" -c pack.threads="$GIT_PACK_THREADS" -c pack.windowMemory="$GIT_PACK_WINDOW_MEMORY" gc --prune=now --aggressive
- #du -sh "$BUILD_OUT"
-}
-
-clone_repository() {
- REPO_NAME="$1"
- ORG_AND_REPO_NAME="${GITHUB_ORG}/${REPO_NAME}"
-
- #
- # Clone
- #
-
- # refresh the cache
- git -C "${BUILD_CACHE}/${REPO_NAME}" fetch --all
- # reference = go faster
- git -C "$BUILD_TMP" clone --bare --dissociate --reference "$(realpath "$BUILD_CACHE")/${REPO_NAME}" "git@github.com:${ORG_AND_REPO_NAME}.git" "${REPO_NAME}"
- # get ready to disconnect reference repo
- git -C "${BUILD_TMP}/${REPO_NAME}" repack -a
- # actually disconnect the reference repo
- rm -f "${BUILD_TMP}/${REPO_NAME}/.git/objects/info/alternates"
-}
-
-move_repository_subdirectory() {
- REPO_NAME="$1"
- SUBDIRECTORY="$2"
-
- #
- # Move to subdirectory
- #
-
- # make filter-repo accept this as a fresh clone
- git -C "${BUILD_TMP}/${REPO_NAME}" gc
-
- HAS_SUBMODULES=$(
- git -C "${BUILD_TMP}/${REPO_NAME}" branch --format="%(refname:short)" | while read BRANCH; do
- if git -C "${BUILD_TMP}/${REPO_NAME}" cat-file -e "${BRANCH}:.gitmodules" &> /dev/null; then
- echo "yep"
- break;
- fi
- done
- )
-
- # rewrite history as if all this work happened in a subdirectory
- # "git mv" is simpler but makes history much less visible
- if [ "$HAS_SUBMODULES" != "yep" ]; then
- echo "Repository ${REPO_NAME} does NOT have submodules"
- # this is significantly faster than the special case below
- git -C "${BUILD_TMP}/${REPO_NAME}" filter-repo --to-subdirectory-filter $SUBDIRECTORY
- else
- echo "Repository ${REPO_NAME} DOES have submodules"
- # the .gitmodules file must stay in the repository root, but the paths inside it must be rewritten
- # this is complicated for the reasons described here: https://github.com/newren/git-filter-repo/issues/158
- # this is also slower, so we only do it for repositories that have submodules
- # if we have more than one, this will cause merge conflicts
- git -C "${BUILD_TMP}/${REPO_NAME}" filter-repo \
- --filename-callback "return filename if filename == b'.gitmodules' else b'${SUBDIRECTORY}'+filename" \
- --blob-callback "if blob.data.startswith(b'[submodule '): blob.data = blob.data.replace(b'path = ', b'path = ${SUBDIRECTORY}')"
- fi
-}
-
-default_branch () {
- BRANCH="master"
-
- if [ -z "$(git -C "${BUILD_TMP}/${REPO_NAME}" branch --list "$BRANCH")" ]; then
- BRANCH="main"
-
- if [ -z "$(git -C "${BUILD_TMP}/${REPO_NAME}" branch --list "$BRANCH")" ]; then
- BRANCH="develop"
- fi
- fi
-
- echo "$BRANCH"
-}
-
-# Perform monorepo fixups on a branch.
-# Mostly: remove "global" files from subdirectories and localize dependencies.
-# $1: the name of the branch to fix up
-fixup_branch () {
- BRANCH="$1"
- NPM_ORGANIZATION="@scratch"
-
- git -C "$BUILD_OUT" checkout -f --no-guess "$BRANCH"
-
- # submodules could be necessary for build/test scripts
- git -C "$BUILD_OUT" submodule update --init --recursive
-
- # remove repository-level configuration and dependencies, like Renovate and Husky
- # do not remove configuration and dependencies that could vary between packages, like semantic-release
- # do not remove content like .github/ that may be useful as reference when building the monorepo equivalent
- # it would be nice to merge all the package-lock.json files into one but it's not clear how to do that
- # just remove the package-lock.json files for now, and build a new one with "npm i" later
- rm -rf "$BUILD_OUT"/packages/*/{.husky,package-lock.json,renovate.json*}
- for REPO in $ALL_REPOS; do
- if [ ! -r "${BUILD_OUT}/packages/${REPO}/package.json" ]; then
- # This repository doesn't exist in this branch
- continue
- fi
-
- jq -f --arg PACKAGE_NAME "$NPM_ORGANIZATION/$REPO" --arg MONOREPO_URL "$MONOREPO_URL" <(join_args ' | ' \
- '.name |= $PACKAGE_NAME' \
- '.repository.url |= $MONOREPO_URL' \
- 'if .scripts.prepare == "husky install" then del(.scripts.prepare) else . end' \
- 'if .scripts == {} then del(.scripts.prepare) else . end' \
- 'del(.config.commitizen)' \
- 'if .config == {} then del(.config) else . end' \
- 'del(.devDependencies."@commitlint/cli")' \
- 'del(.devDependencies."@commitlint/config-conventional")' \
- 'del(.devDependencies."@commitlint/travis-cli")' \
- 'del(.devDependencies."cz-conventional-changelog")' \
- 'del(.devDependencies."husky")' \
- 'if .devDependencies == {} then del(.devDependencies) else . end' \
- ) "${BUILD_OUT}/packages/${REPO}/package.json" | sponge "${BUILD_OUT}/packages/${REPO}/package.json"
- done
- git -C "$BUILD_OUT" commit -m "chore: remove repo-level configuration and deps from packages/*" \
- packages
-
- npm -C "$BUILD_OUT" i
-
- for REPO in $ALL_REPOS; do
- if [ ! -r "${BUILD_OUT}/packages/${REPO}/package.json" ]; then
- # This repository doesn't exist in this branch
- continue
- fi
-
- REMOVEDEPS=""
- DEPS=""
- DEVDEPS=""
- OPTDEPS=""
- PEERDEPS=""
- for DEP in $ALL_REPOS; do
- if jq -e .dependencies.\"$DEP\" "${BUILD_OUT}/packages/${REPO}/package.json" > /dev/null; then
- jq "del(.dependencies.\"$DEP\")" "${BUILD_OUT}/packages/${REPO}/package.json" | sponge "${BUILD_OUT}/packages/${REPO}/package.json"
- DEPS="$DEPS $DEP@*"
- fi
- if jq -e .devDependencies.\"$DEP\" "${BUILD_OUT}/packages/${REPO}/package.json" > /dev/null; then
- jq "del(.devDependencies.\"$DEP\")" "${BUILD_OUT}/packages/${REPO}/package.json" | sponge "${BUILD_OUT}/packages/${REPO}/package.json"
- DEVDEPS="$DEVDEPS $DEP@*"
- fi
- if jq -e .optionalDependencies.\"$DEP\" "${BUILD_OUT}/packages/${REPO}/package.json" > /dev/null; then
- jq "del(.optionalDependencies.\"$DEP\")" "${BUILD_OUT}/packages/${REPO}/package.json" | sponge "${BUILD_OUT}/packages/${REPO}/package.json"
- OPTDEPS="$OPTDEPS $DEP@*"
- fi
- if jq -e .peerDependencies.\"$DEP\" "${BUILD_OUT}/packages/${REPO}/package.json" > /dev/null; then
- jq "del(.peerDependencies.\"$DEP\")" "${BUILD_OUT}/packages/${REPO}/package.json" | sponge "${BUILD_OUT}/packages/${REPO}/package.json"
- PEERDEPS="$PEERDEPS $DEP@*"
- fi
-
- npm -C "$BUILD_OUT" uninstall "$DEP"
- done
- for DEP in $DEPS; do
- npm -C "$BUILD_OUT" install --force --save --save-exact "$NPM_ORGANIZATION/$DEP" -w "$NPM_ORGANIZATION/$REPO" || package_replacement_error "$REPO" "$BRANCH" "$DEP"
- done
- for DEP in $DEVDEPS; do
- npm -C "$BUILD_OUT" install --force --save-dev --save-exact "$NPM_ORGANIZATION/$DEP" -w "$NPM_ORGANIZATION/$REPO" || package_replacement_error "$REPO" "$BRANCH" "$DEVDEPS"
- done
- for DEP in $OPTDEPS; do
- npm -C "$BUILD_OUT" install --force --save-optional --save-exact "$NPM_ORGANIZATION/$DEP" -w "$NPM_ORGANIZATION/$REPO" || package_replacement_error "$REPO" "$BRANCH" "$OPTDEPS"
- done
- for DEP in $PEERDEPS; do
- npm -C "$BUILD_OUT" install --force --save-peer --save-exact "$NPM_ORGANIZATION/$DEP" -w "$NPM_ORGANIZATION/$REPO" || package_replacement_error "$REPO" "$BRANCH" "$PEERDEPS"
- done
-
- # replace the name of the package with the organization prefixed one
- find "$BUILD_OUT" -type f -exec sed -i -e "s:\(require(\|from\s\|resolve(\|node_modules\)\(['\"/]\)$REPO\(['\"/]\):\1\2$NPM_ORGANIZATION/$REPO\3:g" {} \;
- done
-
- npm -C "$BUILD_OUT" i --package-lock-only # sometimes this is necessary to get a consistent package-lock.json
-
- if ! git -C "$BUILD_OUT" diff --quiet package.json package-lock.json packages/*/package.json; then
- git -C "$BUILD_OUT" commit -m "chore(deps): use workspace versions of all local packages" \
- package.json package-lock.json packages/*/package.json
- fi
-}
-
-# Report that replacing a dependency with the local monorepo version failed
-# $1: the name of the repository
-# $2: the branch that was being built
-# $3: the dependency that failed to install
-package_replacement_error () {
- echo "***ERROR***"
- echo "Could not replace a dependency with the local monorepo version."
- echo "Failed to replace $3 in $1#$2" | tee -a "monorepo.errors.log"
- #exit 1 # uncomment this to make it a fatal error
- echo "Attempting to continue anyway..."
-}
-
-setup_github_actions () {
- cp -a .github/actions "$BUILD_OUT/.github/"
- npm -C "$BUILD_OUT" run refresh-gh-workflow
-
- git -C "$BUILD_OUT" add .github/
- git -C "$BUILD_OUT" commit -m "ci: populate workspace workflows"
-}
-
-build_scratch_svg_renderer () {
- echo "Attempting to generate all prerequisite files and to build scratch-svg-renderer"
-
- cd ./monorepo.out/packages/scratch-svg-renderer
- use_node_version_from_nvmrc
- process_workspace_webpack_config "." "webpack.config.js"
- npm run build
- cd -
-}
-
-build_scratch_render () {
- echo "Attempting to generate all prerequisite files and to build scratch-render"
-
- cd ./monorepo.out/packages/scratch-render
- use_node_version_from_nvmrc
- process_workspace_webpack_config "." ".jsdoc.json"
- process_workspace_webpack_config "./test/integration" "cpu-render.html"
- process_workspace_webpack_config "./test/integration" "index.html"
- process_workspace_webpack_config "." "webpack.config.js"
- npm run build
- cd -
-}
-
-build_scratch_vm () {
- echo "Attempting to generate all prerequisite files and to build scratch-scratch-vm"
-
- cd ./monorepo.out/packages/scratch-vm
- use_node_version_from_nvmrc
- process_workspace_webpack_config "." "webpack.config.js"
- npm run build
- cd -
-}
-
-build_scratch_gui () {
- echo "Attempting to generate all prerequisite files and to build scratch-scratch-gui"
-
- cd ./monorepo.out/packages/scratch-gui
- use_node_version_from_nvmrc
- process_workspace_webpack_config "." "webpack.config.js"
- npm run build
- cd -
-}
-
-process_workspace_webpack_config () {
- FILE_PATH="$1"
- FILE_NAME="$2"
-
- PACKAGE_PATHS="$(egrep -o "[\.\/]*node_modules\/[^\"']*" "${FILE_PATH}/${FILE_NAME}" | uniq)"
-
- for PACKAGE_PATH in $PACKAGE_PATHS; do
- PATH_FROM_CURRENT_DIR="${FILE_PATH}/${PACKAGE_PATH}"
-
- if [ ! -d $PATH_FROM_CURRENT_DIR ] && [ ! -f $PATH_FROM_CURRENT_DIR ]; then
- sed -i -e "s:$PACKAGE_PATH:../../${PACKAGE_PATH}:g" "${FILE_PATH}/${FILE_NAME}"
- fi
- done
-}
-
-use_node_version_from_nvmrc () {
- source ~/.nvm/nvm.sh
- nvm install
- nvm use
-}
-
-### Do the things! ###
-
-echo "Depending on your CPU, RAM, drives, and network, this may take about an hour."
-echo "Make sure you have at least 10GB or so free on your drive."
-echo "Press Ctrl-C now to cancel!"
-echo "Starting in 15 seconds..."
-sleep 15
-
-mkdir -p "$BUILD_TMP"
-
-#set -x
-
-init_monorepo
-
-for REPO in $ALL_REPOS; do
- add_repo_to_monorepo "$REPO"
- add_gh_pages "$REPO"
-done
-
-git -C "$BUILD_OUT" checkout -f --no-guess develop
-
-if [ ! -f "$BUILD_OUT/package.json" ]; then
- echo "Something went wrong: $BUILD_OUT/package.json does not exist!"
- exit 1
-fi
-
-rmdir "$BUILD_TMP"
-
-for BRANCH in $DEST_BRANCHES; do
- fixup_branch "$BRANCH"
-
- build_scratch_svg_renderer
- build_scratch_render
- build_scratch_vm
- build_scratch_gui
-
- git -C "$BUILD_OUT" add .
- git -C "$BUILD_OUT" commit -m "refactor: fixed paths to work with new project structure"
-done
-
-setup_github_actions # TODO: should we do this on every branch?
-
-optimize_git_repo
-
-echo "All done!"
-echo "You'll need to manually fix up any CI/CD workflows."
-echo "The monorepo is in: $BUILD_OUT"