scratch-storage 2.3.284 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/.browserslistrc +7 -0
  2. package/CHANGELOG.md +11 -0
  3. package/dist/{web/f6240eab828e6d415177.worker.js → node/chunks/fetch-worker.eefe62e3c8ee125d3436.js} +105 -180
  4. package/dist/node/chunks/fetch-worker.eefe62e3c8ee125d3436.js.map +1 -0
  5. package/dist/node/scratch-storage.js +3898 -6304
  6. package/dist/node/scratch-storage.js.map +1 -1
  7. package/dist/types/Asset.d.ts +38 -0
  8. package/dist/types/AssetType.d.ts +49 -0
  9. package/dist/types/BuiltinHelper.d.ts +69 -0
  10. package/dist/types/DataFormat.d.ts +15 -0
  11. package/dist/types/FetchTool.d.ts +33 -0
  12. package/dist/types/FetchWorkerTool.d.ts +29 -0
  13. package/dist/types/Helper.d.ts +20 -0
  14. package/dist/types/ProxyTool.d.ts +53 -0
  15. package/dist/types/ScratchStorage.d.ts +202 -0
  16. package/dist/types/Tool.d.ts +13 -0
  17. package/dist/types/WebHelper.d.ts +59 -0
  18. package/dist/types/index.d.ts +11 -0
  19. package/dist/types/log.d.ts +2 -0
  20. package/dist/types/memoizedToString.d.ts +5 -0
  21. package/dist/web/chunks/fetch-worker.85da71862ab8ee15f1cd.js +2 -0
  22. package/dist/web/chunks/fetch-worker.85da71862ab8ee15f1cd.js.map +1 -0
  23. package/dist/web/chunks/fetch-worker.ba5eddd48c8ae259073b.js +676 -0
  24. package/dist/web/chunks/fetch-worker.ba5eddd48c8ae259073b.js.map +1 -0
  25. package/dist/web/scratch-storage.js +2002 -2758
  26. package/dist/web/scratch-storage.js.map +1 -1
  27. package/dist/web/scratch-storage.min.js +2 -6398
  28. package/dist/web/scratch-storage.min.js.LICENSE.txt +18 -0
  29. package/dist/web/scratch-storage.min.js.map +1 -1
  30. package/jest.config.js +32 -0
  31. package/package.json +18 -13
  32. package/src/.eslintrc.js +13 -1
  33. package/src/Asset.ts +100 -0
  34. package/src/{AssetType.js → AssetType.ts} +10 -5
  35. package/src/{BuiltinHelper.js → BuiltinHelper.ts} +44 -35
  36. package/src/{DataFormat.js → DataFormat.ts} +3 -3
  37. package/src/{FetchTool.js → FetchTool.ts} +8 -9
  38. package/src/{FetchWorkerTool.js → FetchWorkerTool.ts} +47 -22
  39. package/src/{Helper.js → Helper.ts} +10 -5
  40. package/src/{ProxyTool.js → ProxyTool.ts} +32 -29
  41. package/src/{ScratchStorage.js → ScratchStorage.ts} +57 -34
  42. package/src/Tool.ts +10 -0
  43. package/src/{WebHelper.js → WebHelper.ts} +42 -15
  44. package/src/index.ts +19 -0
  45. package/src/log.ts +4 -0
  46. package/src/{Asset.js → memoizedToString.ts} +16 -76
  47. package/src/scratchFetch.js +0 -2
  48. package/src/types.d.ts +3 -0
  49. package/test/integration/download-known-assets.test.js +1 -1
  50. package/test/unit/add-helper.test.js +1 -1
  51. package/test/unit/fetch-tool.test.js +1 -1
  52. package/test/unit/load-default-assets.test.js +1 -1
  53. package/test/unit/metadata.test.js +6 -6
  54. package/tsconfig.json +29 -0
  55. package/tsconfig.test.json +11 -0
  56. package/webpack.config.js +58 -65
  57. package/dist/node/ce8a01e629587e4f90e4.worker.js +0 -4274
  58. package/dist/node/ce8a01e629587e4f90e4.worker.js.map +0 -1
  59. package/dist/web/f6240eab828e6d415177.worker.js.map +0 -1
  60. package/src/index.js +0 -7
  61. package/src/log.js +0 -4
@@ -0,0 +1,38 @@
1
+ import { AssetType } from './AssetType';
2
+ import { DataFormat } from './DataFormat';
3
+ export type AssetId = string | number;
4
+ export type AssetData = string | Uint8Array;
5
+ export default class Asset {
6
+ assetType: AssetType;
7
+ assetId?: AssetId;
8
+ data?: AssetData;
9
+ dataFormat?: DataFormat;
10
+ dependencies: Asset[];
11
+ clean?: boolean;
12
+ /**
13
+ * Construct an Asset.
14
+ * @param {AssetType} assetType - The type of this asset (sound, image, etc.)
15
+ * @param {string} assetId - The ID of this asset.
16
+ * @param {DataFormat} [dataFormat] - The format of the data (WAV, PNG, etc.); required iff `data` is present.
17
+ * @param {Buffer} [data] - The in-memory data for this asset; optional.
18
+ * @param {bool} [generateId] - Whether to create id from an md5 hash of data
19
+ */
20
+ constructor(assetType: AssetType, assetId?: AssetId, dataFormat?: DataFormat, data?: AssetData, generateId?: boolean);
21
+ setData(data: AssetData | undefined, dataFormat: DataFormat | undefined, generateId?: boolean): void;
22
+ /**
23
+ * @returns {string} - This asset's data, decoded as text.
24
+ */
25
+ decodeText(): string;
26
+ /**
27
+ * Same as `setData` but encodes text first.
28
+ * @param {string} data - the text data to encode and store.
29
+ * @param {DataFormat} dataFormat - the format of the data (DataFormat.SVG for example).
30
+ * @param {bool} generateId - after setting data, set the id to an md5 of the data?
31
+ */
32
+ encodeTextData(data: string, dataFormat: DataFormat, generateId: boolean): void;
33
+ /**
34
+ * @param {string} [contentType] - Optionally override the content type to be included in the data URI.
35
+ * @returns {string} - A data URI representing the asset's data.
36
+ */
37
+ encodeDataURI(contentType: string): string;
38
+ }
@@ -0,0 +1,49 @@
1
+ import { DataFormat } from './DataFormat';
2
+ export interface AssetType {
3
+ contentType: string;
4
+ name: string;
5
+ runtimeFormat: DataFormat;
6
+ immutable: boolean;
7
+ }
8
+ /**
9
+ * Enumeration of the supported asset types.
10
+ * @type {Object.<String,AssetType>}
11
+ * @typedef {Object} AssetType - Information about a supported asset type.
12
+ * @property {string} contentType - the MIME type associated with this kind of data. Useful for data URIs, etc.
13
+ * @property {string} name - The human-readable name of this asset type.
14
+ * @property {DataFormat} runtimeFormat - The default format used for runtime, in-memory storage of this asset. For
15
+ * example, a project stored in SB2 format on disk will be returned as JSON when loaded into memory.
16
+ * @property {boolean} immutable - Indicates if the asset id is determined by the asset content.
17
+ */
18
+ export declare const AssetType: {
19
+ readonly ImageBitmap: {
20
+ readonly contentType: "image/png";
21
+ readonly name: "ImageBitmap";
22
+ readonly runtimeFormat: "png";
23
+ readonly immutable: true;
24
+ };
25
+ readonly ImageVector: {
26
+ readonly contentType: "image/svg+xml";
27
+ readonly name: "ImageVector";
28
+ readonly runtimeFormat: "svg";
29
+ readonly immutable: true;
30
+ };
31
+ readonly Project: {
32
+ readonly contentType: "application/json";
33
+ readonly name: "Project";
34
+ readonly runtimeFormat: "json";
35
+ readonly immutable: false;
36
+ };
37
+ readonly Sound: {
38
+ readonly contentType: "audio/x-wav";
39
+ readonly name: "Sound";
40
+ readonly runtimeFormat: "wav";
41
+ readonly immutable: true;
42
+ };
43
+ readonly Sprite: {
44
+ readonly contentType: "application/json";
45
+ readonly name: "Sprite";
46
+ readonly runtimeFormat: "json";
47
+ readonly immutable: true;
48
+ };
49
+ };
@@ -0,0 +1,69 @@
1
+ import Asset, { AssetData, AssetId } from './Asset';
2
+ import { AssetType } from './AssetType';
3
+ import { DataFormat } from './DataFormat';
4
+ import Helper from './Helper';
5
+ import { ScratchStorage } from './ScratchStorage';
6
+ /**
7
+ * @typedef {object} BuiltinAssetRecord
8
+ * @property {AssetType} type - The type of the asset.
9
+ * @property {DataFormat} format - The format of the asset's data.
10
+ * @property {?string} id - The asset's unique ID.
11
+ * @property {Buffer} data - The asset's data.
12
+ */
13
+ interface BuiltinAssetRecord {
14
+ type: AssetType;
15
+ format: DataFormat;
16
+ id: AssetId | null;
17
+ data: AssetData;
18
+ }
19
+ export default class BuiltinHelper extends Helper {
20
+ assets: Record<string, BuiltinAssetRecord>;
21
+ constructor(parent: ScratchStorage);
22
+ /**
23
+ * Call `setDefaultAssetId` on the parent `ScratchStorage` instance to register all built-in default assets.
24
+ */
25
+ registerDefaultAssets(): void;
26
+ /**
27
+ * Synchronously fetch a cached asset for a given asset id. Returns null if not found.
28
+ * @param {string} assetId - The id for the asset to fetch.
29
+ * @returns {?Asset} The asset for assetId, if it exists.
30
+ */
31
+ get(assetId: AssetId): Asset | null;
32
+ /**
33
+ * Alias for store (old name of store)
34
+ * @deprecated Use BuiltinHelper.store
35
+ * @param {AssetType} assetType - The type of the asset to cache.
36
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
37
+ * @param {Buffer} data - The data for the cached asset.
38
+ * @param {string} id - The id for the cached asset.
39
+ * @returns {string} The calculated id of the cached asset, or the supplied id if the asset is mutable.
40
+ */
41
+ cache(assetType: AssetType, dataFormat: DataFormat, data: AssetData, id: AssetId): AssetId;
42
+ /**
43
+ * Deprecated external API for _store
44
+ * @deprecated Not for external use. Create assets and keep track of them outside of the storage instance.
45
+ * @param {AssetType} assetType - The type of the asset to cache.
46
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
47
+ * @param {Buffer} data - The data for the cached asset.
48
+ * @param {(string|number)} id - The id for the cached asset.
49
+ * @returns {string} The calculated id of the cached asset, or the supplied id if the asset is mutable.
50
+ */
51
+ store(assetType: AssetType, dataFormat: DataFormat, data: AssetData, id: AssetId): AssetId;
52
+ /**
53
+ * Cache an asset for future lookups by ID.
54
+ * @param {AssetType} assetType - The type of the asset to cache.
55
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
56
+ * @param {Buffer} data - The data for the cached asset.
57
+ * @param {(string|number)} id - The id for the cached asset.
58
+ * @returns {string} The calculated id of the cached asset, or the supplied id if the asset is mutable.
59
+ */
60
+ _store(assetType: AssetType, dataFormat: DataFormat, data: AssetData, id?: AssetId | null): AssetId;
61
+ /**
62
+ * Fetch an asset but don't process dependencies.
63
+ * @param {AssetType} assetType - The type of asset to fetch.
64
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
65
+ * @return {?Promise.<Asset>} A promise for the contents of the asset.
66
+ */
67
+ load(assetType: AssetType, assetId: AssetId): Promise<Asset | null> | null;
68
+ }
69
+ export {};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Enumeration of the supported data formats.
3
+ * @enum {string}
4
+ */
5
+ export declare const DataFormat: {
6
+ readonly JPG: "jpg";
7
+ readonly JSON: "json";
8
+ readonly MP3: "mp3";
9
+ readonly PNG: "png";
10
+ readonly SB2: "sb2";
11
+ readonly SB3: "sb3";
12
+ readonly SVG: "svg";
13
+ readonly WAV: "wav";
14
+ };
15
+ export type DataFormat = typeof DataFormat[keyof typeof DataFormat];
@@ -0,0 +1,33 @@
1
+ import { ScratchGetRequest, ScratchSendRequest, Tool } from './Tool';
2
+ /**
3
+ * @typedef {Request & {withCredentials: boolean}} ScratchSendRequest
4
+ */
5
+ /**
6
+ * Get and send assets with the fetch standard web api.
7
+ */
8
+ export declare class FetchTool implements Tool {
9
+ /**
10
+ * Is get supported?
11
+ * Always true for `FetchTool` because `scratchFetch` ponyfills `fetch` if necessary.
12
+ * @returns {boolean} Is get supported?
13
+ */
14
+ get isGetSupported(): boolean;
15
+ /**
16
+ * Request data from a server with fetch.
17
+ * @param {Request} reqConfig - Request configuration for data to get.
18
+ * @returns {Promise.<Uint8Array?>} Resolve to Buffer of data from server.
19
+ */
20
+ get({ url, ...options }: ScratchGetRequest): Promise<Uint8Array | null>;
21
+ /**
22
+ * Is sending supported?
23
+ * Always true for `FetchTool` because `scratchFetch` ponyfills `fetch` if necessary.
24
+ * @returns {boolean} Is sending supported?
25
+ */
26
+ get isSendSupported(): boolean;
27
+ /**
28
+ * Send data to a server with fetch.
29
+ * @param {ScratchSendRequest} reqConfig - Request configuration for data to send.
30
+ * @returns {Promise.<string>} Server returned metadata.
31
+ */
32
+ send({ url, withCredentials, ...options }: ScratchSendRequest): Promise<string>;
33
+ }
@@ -0,0 +1,29 @@
1
+ import { ScratchGetRequest } from './Tool';
2
+ /**
3
+ * Get and send assets with a worker that uses fetch.
4
+ */
5
+ export default class PublicFetchWorkerTool {
6
+ private inner;
7
+ constructor();
8
+ /**
9
+ * Is get supported?
10
+ * @returns {boolean} Is get supported?
11
+ */
12
+ get isGetSupported(): boolean;
13
+ /**
14
+ * Request data from a server with a worker that uses fetch.
15
+ * @param {{url:string}} reqConfig - Request configuration for data to get.
16
+ * @returns {Promise.<Buffer|Uint8Array|null>} Resolve to Buffer of data from server.
17
+ */
18
+ get(reqConfig: ScratchGetRequest): Promise<Uint8Array | null>;
19
+ /**
20
+ * Is sending supported?
21
+ * @returns {boolean} Is sending supported?
22
+ */
23
+ get isSendSupported(): boolean;
24
+ /**
25
+ * Send data to a server with a worker that uses fetch.
26
+ * @throws {Error} A not implemented error.
27
+ */
28
+ send(): never;
29
+ }
@@ -0,0 +1,20 @@
1
+ import Asset, { AssetId } from './Asset';
2
+ import { AssetType } from './AssetType';
3
+ import { DataFormat } from './DataFormat';
4
+ import { ScratchStorage } from './ScratchStorage';
5
+ /**
6
+ * Base class for asset load/save helpers.
7
+ * @abstract
8
+ */
9
+ export default class Helper {
10
+ parent: ScratchStorage;
11
+ constructor(parent: ScratchStorage);
12
+ /**
13
+ * Fetch an asset but don't process dependencies.
14
+ * @param {AssetType} assetType - The type of asset to fetch.
15
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
16
+ * @param {DataFormat} dataFormat - The file format / file extension of the asset to fetch: PNG, JPG, etc.
17
+ * @return {Promise.<Asset>} A promise for the contents of the asset.
18
+ */
19
+ load(assetType: AssetType, assetId: AssetId, dataFormat: DataFormat): Promise<Asset | null> | null;
20
+ }
@@ -0,0 +1,53 @@
1
+ import { ScratchGetRequest, ScratchSendRequest, Tool } from './Tool';
2
+ /**
3
+ * @typedef {object} Request
4
+ * @property {string} url
5
+ * @property {*} body
6
+ * @property {string} method
7
+ * @property {boolean} withCredentials
8
+ */
9
+ type ToolFilter = typeof ProxyTool.TOOL_FILTER[keyof typeof ProxyTool.TOOL_FILTER];
10
+ /**
11
+ * Get and send assets with other tools in sequence.
12
+ */
13
+ export default class ProxyTool implements Tool {
14
+ tools: Tool[];
15
+ /**
16
+ * Constant values that filter the set of tools in a ProxyTool instance.
17
+ * @enum {string}
18
+ */
19
+ static TOOL_FILTER: {
20
+ /**
21
+ * Use all tools.
22
+ */
23
+ readonly ALL: "all";
24
+ /**
25
+ * Use tools that are ready right now.
26
+ */
27
+ readonly READY: "ready";
28
+ };
29
+ constructor(filter?: ToolFilter);
30
+ /**
31
+ * Is get supported? false if all proxied tool return false.
32
+ * @returns {boolean} Is get supported?
33
+ */
34
+ get isGetSupported(): boolean;
35
+ /**
36
+ * Request data from with one of the proxied tools.
37
+ * @param {Request} reqConfig - Request configuration for data to get.
38
+ * @returns {Promise.<Buffer>} Resolve to Buffer of data from server.
39
+ */
40
+ get(reqConfig: ScratchGetRequest): Promise<Uint8Array | null>;
41
+ /**
42
+ * Is sending supported? false if all proxied tool return false.
43
+ * @returns {boolean} Is sending supported?
44
+ */
45
+ get isSendSupported(): boolean;
46
+ /**
47
+ * Send data to a server with one of the proxied tools.
48
+ * @param {Request} reqConfig - Request configuration for data to send.
49
+ * @returns {Promise.<Buffer|string|object>} Server returned metadata.
50
+ */
51
+ send(reqConfig: ScratchSendRequest): Promise<string>;
52
+ }
53
+ export {};
@@ -0,0 +1,202 @@
1
+ import BuiltinHelper from './BuiltinHelper';
2
+ import WebHelper, { UrlFunction } from './WebHelper';
3
+ import _Asset, { AssetData, AssetId } from './Asset';
4
+ import { AssetType } from './AssetType';
5
+ import { DataFormat } from './DataFormat';
6
+ import Helper from './Helper';
7
+ export declare class ScratchStorage {
8
+ defaultAssetId: Record<AssetType['name'], AssetId>;
9
+ builtinHelper: BuiltinHelper;
10
+ webHelper: WebHelper;
11
+ private _helpers;
12
+ constructor();
13
+ /**
14
+ * @return {Asset} - the `Asset` class constructor.
15
+ * @constructor
16
+ */
17
+ get Asset(): typeof _Asset;
18
+ /**
19
+ * @return {AssetType} - the list of supported asset types.
20
+ * @constructor
21
+ */
22
+ get AssetType(): {
23
+ readonly ImageBitmap: {
24
+ readonly contentType: "image/png";
25
+ readonly name: "ImageBitmap";
26
+ readonly runtimeFormat: "png";
27
+ readonly immutable: true;
28
+ };
29
+ readonly ImageVector: {
30
+ readonly contentType: "image/svg+xml";
31
+ readonly name: "ImageVector";
32
+ readonly runtimeFormat: "svg";
33
+ readonly immutable: true;
34
+ };
35
+ readonly Project: {
36
+ readonly contentType: "application/json";
37
+ readonly name: "Project";
38
+ readonly runtimeFormat: "json";
39
+ readonly immutable: false;
40
+ };
41
+ readonly Sound: {
42
+ readonly contentType: "audio/x-wav";
43
+ readonly name: "Sound";
44
+ readonly runtimeFormat: "wav";
45
+ readonly immutable: true;
46
+ };
47
+ readonly Sprite: {
48
+ readonly contentType: "application/json";
49
+ readonly name: "Sprite";
50
+ readonly runtimeFormat: "json";
51
+ readonly immutable: true;
52
+ };
53
+ };
54
+ /**
55
+ * @return {DataFormat} - the list of supported data formats.
56
+ * @constructor
57
+ */
58
+ get DataFormat(): {
59
+ readonly JPG: "jpg";
60
+ readonly JSON: "json";
61
+ readonly MP3: "mp3";
62
+ readonly PNG: "png";
63
+ readonly SB2: "sb2";
64
+ readonly SB3: "sb3";
65
+ readonly SVG: "svg";
66
+ readonly WAV: "wav";
67
+ };
68
+ /**
69
+ * Access the `scratchFetch` module within this library.
70
+ * @return {module} the scratchFetch module, with properties for `scratchFetch`, `setMetadata`, etc.
71
+ */
72
+ get scratchFetch(): any;
73
+ /**
74
+ * @deprecated Please use the `Asset` member of a storage instance instead.
75
+ * @return {Asset} - the `Asset` class constructor.
76
+ * @constructor
77
+ */
78
+ static get Asset(): typeof _Asset;
79
+ /**
80
+ * @deprecated Please use the `AssetType` member of a storage instance instead.
81
+ * @return {AssetType} - the list of supported asset types.
82
+ * @constructor
83
+ */
84
+ static get AssetType(): {
85
+ readonly ImageBitmap: {
86
+ readonly contentType: "image/png";
87
+ readonly name: "ImageBitmap";
88
+ readonly runtimeFormat: "png";
89
+ readonly immutable: true;
90
+ };
91
+ readonly ImageVector: {
92
+ readonly contentType: "image/svg+xml";
93
+ readonly name: "ImageVector";
94
+ readonly runtimeFormat: "svg";
95
+ readonly immutable: true;
96
+ };
97
+ readonly Project: {
98
+ readonly contentType: "application/json";
99
+ readonly name: "Project";
100
+ readonly runtimeFormat: "json";
101
+ readonly immutable: false;
102
+ };
103
+ readonly Sound: {
104
+ readonly contentType: "audio/x-wav";
105
+ readonly name: "Sound";
106
+ readonly runtimeFormat: "wav";
107
+ readonly immutable: true;
108
+ };
109
+ readonly Sprite: {
110
+ readonly contentType: "application/json";
111
+ readonly name: "Sprite";
112
+ readonly runtimeFormat: "json";
113
+ readonly immutable: true;
114
+ };
115
+ };
116
+ /**
117
+ * Add a storage helper to this manager. Helpers with a higher priority number will be checked first when loading
118
+ * or storing assets. For comparison, the helper for built-in assets has `priority=100` and the default web helper
119
+ * has `priority=-100`. The relative order of helpers with equal priorities is undefined.
120
+ * @param {Helper} helper - the helper to be added.
121
+ * @param {number} [priority] - the priority for this new helper (default: 0).
122
+ */
123
+ addHelper(helper: Helper, priority?: number): void;
124
+ /**
125
+ * Synchronously fetch a cached asset from built-in storage. Assets are cached when they are loaded.
126
+ * @param {string} assetId - The id of the asset to fetch.
127
+ * @returns {?Asset} The asset, if it exists.
128
+ */
129
+ get(assetId: string): _Asset | null;
130
+ /**
131
+ * Deprecated API for caching built-in assets. Use createAsset.
132
+ * @param {AssetType} assetType - The type of the asset to cache.
133
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
134
+ * @param {Buffer} data - The data for the cached asset.
135
+ * @param {string} id - The id for the cached asset.
136
+ * @returns {string} The calculated id of the cached asset, or the supplied id if the asset is mutable.
137
+ */
138
+ cache(assetType: AssetType, dataFormat: DataFormat, data: AssetData, id: AssetId): AssetId;
139
+ /**
140
+ * Construct an Asset, and optionally generate an md5 hash of its data to create an id
141
+ * @param {AssetType} assetType - The type of the asset to cache.
142
+ * @param {DataFormat} dataFormat - The dataFormat of the data for the cached asset.
143
+ * @param {Buffer} data - The data for the cached asset.
144
+ * @param {string} [id] - The id for the cached asset.
145
+ * @param {bool} [generateId] - flag to set id to an md5 hash of data if `id` isn't supplied
146
+ * @returns {Asset} generated Asset with `id` attribute set if not supplied
147
+ */
148
+ createAsset(assetType: AssetType, dataFormat: DataFormat, data: AssetData, id: AssetId, generateId: boolean): _Asset;
149
+ /**
150
+ * Register a web-based source for assets. Sources will be checked in order of registration.
151
+ * @param {Array.<AssetType>} types - The types of asset provided by this source.
152
+ * @param {UrlFunction} getFunction - A function which computes a GET URL from an Asset.
153
+ * @param {UrlFunction} createFunction - A function which computes a POST URL for asset data.
154
+ * @param {UrlFunction} updateFunction - A function which computes a PUT URL for asset data.
155
+ */
156
+ addWebStore(types: AssetType[], getFunction: UrlFunction, createFunction?: UrlFunction, updateFunction?: UrlFunction): void;
157
+ /**
158
+ * Register a web-based source for assets. Sources will be checked in order of registration.
159
+ * @deprecated Please use addWebStore
160
+ * @param {Array.<AssetType>} types - The types of asset provided by this source.
161
+ * @param {UrlFunction} urlFunction - A function which computes a GET URL from an Asset.
162
+ */
163
+ addWebSource(types: AssetType[], urlFunction: UrlFunction): void;
164
+ /**
165
+ * TODO: Should this be removed in favor of requesting an asset with `null` as the ID?
166
+ * @param {AssetType} type - Get the default ID for assets of this type.
167
+ * @return {?string} The ID of the default asset of the given type, if any.
168
+ */
169
+ getDefaultAssetId(type: AssetType): AssetId | undefined;
170
+ /**
171
+ * Set the default ID for a particular type of asset. This default asset will be used if a requested asset cannot
172
+ * be found and automatic fallback is enabled. Ideally this should be an asset that is available locally or even
173
+ * one built into this module.
174
+ * TODO: Should this be removed in favor of requesting an asset with `null` as the ID?
175
+ * @param {AssetType} type - The type of asset for which the default will be set.
176
+ * @param {string} id - The default ID to use for this type of asset.
177
+ */
178
+ setDefaultAssetId(type: AssetType, id: AssetId): void;
179
+ /**
180
+ * Fetch an asset by type & ID.
181
+ * @param {AssetType} assetType - The type of asset to fetch. This also determines which asset store to use.
182
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
183
+ * @param {DataFormat} [dataFormat] - Optional: load this format instead of the AssetType's default.
184
+ * @return {Promise.<Asset>} A promise for the requested Asset.
185
+ * If the promise is resolved with non-null, the value is the requested asset.
186
+ * If the promise is resolved with null, the desired asset could not be found with the current asset sources.
187
+ * If the promise is rejected, there was an error on at least one asset source. HTTP 404 does not count as an
188
+ * error here, but (for example) HTTP 403 does.
189
+ */
190
+ load(assetType: AssetType, assetId: AssetId, dataFormat: DataFormat): Promise<_Asset | null>;
191
+ /**
192
+ * Store an asset by type & ID.
193
+ * @param {AssetType} assetType - The type of asset to fetch. This also determines which asset store to use.
194
+ * @param {?DataFormat} [dataFormat] - Optional: load this format instead of the AssetType's default.
195
+ * @param {Buffer} data - Data to store for the asset
196
+ * @param {?string} [assetId] - The ID of the asset to fetch: a project ID, MD5, etc.
197
+ * @return {Promise.<object>} A promise for asset metadata
198
+ */
199
+ store(assetType: AssetType, dataFormat: DataFormat | null | undefined, data: AssetData, assetId?: AssetId): Promise<string | {
200
+ id: string;
201
+ }>;
202
+ }
@@ -0,0 +1,13 @@
1
+ export type ScratchGetRequest = {
2
+ url: string;
3
+ } & RequestInit;
4
+ export type ScratchSendRequest = {
5
+ url: string;
6
+ withCredentials?: boolean;
7
+ } & RequestInit;
8
+ export interface Tool {
9
+ get isGetSupported(): boolean;
10
+ get(request: ScratchGetRequest): Promise<Uint8Array | null>;
11
+ get isSendSupported(): boolean;
12
+ send(request: ScratchSendRequest): Promise<string>;
13
+ }
@@ -0,0 +1,59 @@
1
+ import Asset, { AssetData, AssetId } from './Asset';
2
+ import Helper from './Helper';
3
+ import { ScratchGetRequest, ScratchSendRequest, Tool } from './Tool';
4
+ import { AssetType } from './AssetType';
5
+ import { DataFormat } from './DataFormat';
6
+ /**
7
+ * @typedef {function} UrlFunction - A function which computes a URL from asset information.
8
+ * @param {Asset} - The asset for which the URL should be computed.
9
+ * @returns {(string|object)} - A string representing the URL for the asset request OR an object with configuration for
10
+ * the underlying fetch call (necessary for configuring e.g. authentication)
11
+ */
12
+ export type UrlFunction = (asset: Asset) => string | ScratchGetRequest | ScratchSendRequest;
13
+ interface StoreRecord {
14
+ types: string[];
15
+ get: UrlFunction;
16
+ create?: UrlFunction;
17
+ update?: UrlFunction;
18
+ }
19
+ export default class WebHelper extends Helper {
20
+ stores: StoreRecord[];
21
+ assetTool: Tool;
22
+ projectTool: Tool;
23
+ constructor(parent: any);
24
+ /**
25
+ * Register a web-based source for assets. Sources will be checked in order of registration.
26
+ * @deprecated Please use addStore
27
+ * @param {Array.<AssetType>} types - The types of asset provided by this source.
28
+ * @param {UrlFunction} urlFunction - A function which computes a URL from an Asset.
29
+ */
30
+ addSource(types: AssetType[], urlFunction: UrlFunction): void;
31
+ /**
32
+ * Register a web-based store for assets. Sources will be checked in order of registration.
33
+ * @param {Array.<AssetType>} types - The types of asset provided by this store.
34
+ * @param {UrlFunction} getFunction - A function which computes a GET URL for an Asset
35
+ * @param {UrlFunction} createFunction - A function which computes a POST URL for an Asset
36
+ * @param {UrlFunction} updateFunction - A function which computes a PUT URL for an Asset
37
+ */
38
+ addStore(types: AssetType[], getFunction: UrlFunction, createFunction?: UrlFunction, updateFunction?: UrlFunction): void;
39
+ /**
40
+ * Fetch an asset but don't process dependencies.
41
+ * @param {AssetType} assetType - The type of asset to fetch.
42
+ * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
43
+ * @param {DataFormat} dataFormat - The file format / file extension of the asset to fetch: PNG, JPG, etc.
44
+ * @return {Promise.<Asset>} A promise for the contents of the asset.
45
+ */
46
+ load(assetType: AssetType, assetId: AssetId, dataFormat: DataFormat): Promise<Asset | null>;
47
+ /**
48
+ * Create or update an asset with provided data. The create function is called if no asset id is provided
49
+ * @param {AssetType} assetType - The type of asset to create or update.
50
+ * @param {?DataFormat} dataFormat - DataFormat of the data for the stored asset.
51
+ * @param {Buffer} data - The data for the cached asset.
52
+ * @param {?string} assetId - The ID of the asset to fetch: a project ID, MD5, etc.
53
+ * @return {Promise.<object>} A promise for the response from the create or update request
54
+ */
55
+ store(assetType: AssetType, dataFormat: DataFormat | undefined, data: AssetData, assetId?: AssetId): Promise<string | {
56
+ id: string;
57
+ }>;
58
+ }
59
+ export {};
@@ -0,0 +1,11 @@
1
+ import { ScratchStorage } from './ScratchStorage';
2
+ import Asset, { AssetId } from './Asset';
3
+ import { AssetType } from './AssetType';
4
+ import { DataFormat } from './DataFormat';
5
+ import Helper from './Helper';
6
+ export {
7
+ /**
8
+ * Export for use with NPM & Node.js.
9
+ * @type {ScratchStorage}
10
+ */
11
+ ScratchStorage, Asset, AssetId, AssetType, DataFormat, Helper };
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,5 @@
1
+ import { AssetId } from './Asset';
2
+ declare let _TextDecoder: typeof TextDecoder;
3
+ declare let _TextEncoder: typeof TextEncoder;
4
+ declare const memoizedToString: (assetId: AssetId, data: Uint8Array) => any;
5
+ export { memoizedToString, _TextEncoder, _TextDecoder };
@@ -0,0 +1,2 @@
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ScratchStorage=e():t.ScratchStorage=e()}(self,(()=>(()=>{var t={945:function(t,e){var r="undefined"!=typeof self?self:this,o=function(){function t(){this.fetch=!1,this.DOMException=r.DOMException}return t.prototype=r,new t}();!function(t){!function(e){var r="URLSearchParams"in t,o="Symbol"in t&&"iterator"in Symbol,n="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),i="FormData"in t,s="ArrayBuffer"in t;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(t){return t&&a.indexOf(Object.prototype.toString.call(t))>-1};function u(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function f(t){return"string"!=typeof t&&(t=String(t)),t}function c(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return o&&(e[Symbol.iterator]=function(){return e}),e}function d(t){this.map={},t instanceof d?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function p(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function l(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function y(t){var e=new FileReader,r=l(e);return e.readAsArrayBuffer(t),r}function b(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:n&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:i&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:r&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s&&n&&((e=t)&&DataView.prototype.isPrototypeOf(e))?(this._bodyArrayBuffer=b(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(t)||h(t))?this._bodyArrayBuffer=b(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},n&&(this.blob=function(){var t=p(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(y)}),this.text=function(){var t,e,r,o=p(this);if(o)return o;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,r=l(e),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),o=0;o<e.length;o++)r[o]=String.fromCharCode(e[o]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},i&&(this.formData=function(){return this.text().then(x)}),this.json=function(){return this.text().then(JSON.parse)},this}d.prototype.append=function(t,e){t=u(t),e=f(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},d.prototype.delete=function(t){delete this.map[u(t)]},d.prototype.get=function(t){return t=u(t),this.has(t)?this.map[t]:null},d.prototype.has=function(t){return this.map.hasOwnProperty(u(t))},d.prototype.set=function(t,e){this.map[u(t)]=f(e)},d.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},d.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),c(t)},d.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),c(t)},d.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),c(t)},o&&(d.prototype[Symbol.iterator]=d.prototype.entries);var w=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function v(t,e){var r,o,n=(e=e||{}).body;if(t instanceof v){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new d(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,n||null==t._bodyInit||(n=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new d(e.headers)),this.method=(r=e.method||this.method||"GET",o=r.toUpperCase(),w.indexOf(o)>-1?o:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n)}function x(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),o=r.shift().replace(/\+/g," "),n=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(n))}})),e}function E(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new d(e.headers),this.url=e.url||"",this._initBody(t)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},m.call(v.prototype),m.call(E.prototype),E.prototype.clone=function(){return new E(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},E.error=function(){var t=new E(null,{status:0,statusText:""});return t.type="error",t};var g=[301,302,303,307,308];E.redirect=function(t,e){if(-1===g.indexOf(e))throw new RangeError("Invalid status code");return new E(null,{status:e,headers:{location:t}})},e.DOMException=t.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function A(t,r){return new Promise((function(o,i){var s=new v(t,r);if(s.signal&&s.signal.aborted)return i(new e.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function h(){a.abort()}a.onload=function(){var t,e,r={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new d,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),o=r.shift().trim();if(o){var n=r.join(":").trim();e.append(o,n)}})),e)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var n="response"in a?a.response:a.responseText;o(new E(n,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new e.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&n&&(a.responseType="blob"),s.headers.forEach((function(t,e){a.setRequestHeader(e,t)})),s.signal&&(s.signal.addEventListener("abort",h),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",h)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}A.polyfill=!0,t.fetch||(t.fetch=A,t.Headers=d,t.Request=v,t.Response=E),e.Headers=d,e.Request=v,e.Response=E,e.fetch=A,Object.defineProperty(e,"__esModule",{value:!0})}({})}(o),o.fetch.ponyfill=!0,delete o.fetch.polyfill;var n=o;(e=n.fetch).default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,t.exports=e}},e={};const r=function r(o){var n=e[o];if(void 0!==n)return n.exports;var i=e[o]={exports:{}};return t[o].call(i.exports,i,i.exports,r),i.exports}(945).default;let o=0;const n=[];let i=null;return postMessage({support:{fetch:!0}}),self.addEventListener("message",(t=>{let{data:e}=t;0!==o||i||(i=setInterval((()=>{n.length&&(postMessage(n.slice(),n.map((t=>t.buffer)).filter(Boolean)),n.length=0),0===o&&(clearInterval(i),i=null)}),1)),o++,r(e.url,e.options).then((t=>t.ok?t.arrayBuffer():404===t.status?null:Promise.reject(t.status))).then((t=>n.push({id:e.id,buffer:t}))).catch((t=>n.push({id:e.id,error:t&&t.message||"Failed request: ".concat(e.url)}))).then((()=>o--))})),{}})()));
2
+ //# sourceMappingURL=fetch-worker.85da71862ab8ee15f1cd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chunks/fetch-worker.85da71862ab8ee15f1cd.js","mappings":"AAAA","sources":["webpack://ScratchStorage/webpack/universalModuleDefinition"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ScratchStorage\"] = factory();\n\telse\n\t\troot[\"ScratchStorage\"] = factory();\n})(self, () => {\nreturn "],"names":[],"sourceRoot":""}