@aws-blocks/bb-file-bucket 0.1.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 (87) hide show
  1. package/LICENSE +174 -0
  2. package/README.md +197 -0
  3. package/dist/bucket-name.d.ts +9 -0
  4. package/dist/bucket-name.d.ts.map +1 -0
  5. package/dist/bucket-name.js +62 -0
  6. package/dist/bucket-name.test.d.ts +2 -0
  7. package/dist/bucket-name.test.d.ts.map +1 -0
  8. package/dist/bucket-name.test.js +61 -0
  9. package/dist/errors.d.ts +20 -0
  10. package/dist/errors.d.ts.map +1 -0
  11. package/dist/errors.js +21 -0
  12. package/dist/file-server.d.ts +14 -0
  13. package/dist/file-server.d.ts.map +1 -0
  14. package/dist/file-server.js +169 -0
  15. package/dist/file-server.test.d.ts +2 -0
  16. package/dist/file-server.test.d.ts.map +1 -0
  17. package/dist/file-server.test.js +307 -0
  18. package/dist/index.aws.d.ts +47 -0
  19. package/dist/index.aws.d.ts.map +1 -0
  20. package/dist/index.aws.js +183 -0
  21. package/dist/index.browser.d.ts +4 -0
  22. package/dist/index.browser.d.ts.map +1 -0
  23. package/dist/index.browser.js +6 -0
  24. package/dist/index.cdk.d.ts +16 -0
  25. package/dist/index.cdk.d.ts.map +1 -0
  26. package/dist/index.cdk.js +75 -0
  27. package/dist/index.cdk.test.d.ts +2 -0
  28. package/dist/index.cdk.test.d.ts.map +1 -0
  29. package/dist/index.cdk.test.js +69 -0
  30. package/dist/index.mock.d.ts +246 -0
  31. package/dist/index.mock.d.ts.map +1 -0
  32. package/dist/index.mock.js +502 -0
  33. package/dist/index.test.d.ts +2 -0
  34. package/dist/index.test.d.ts.map +1 -0
  35. package/dist/index.test.js +318 -0
  36. package/dist/middleware.d.ts +3 -0
  37. package/dist/middleware.d.ts.map +1 -0
  38. package/dist/middleware.js +62 -0
  39. package/dist/mock-middleware.d.ts +3 -0
  40. package/dist/mock-middleware.d.ts.map +1 -0
  41. package/dist/mock-middleware.js +62 -0
  42. package/dist/mock-utils.d.ts +11 -0
  43. package/dist/mock-utils.d.ts.map +1 -0
  44. package/dist/mock-utils.js +28 -0
  45. package/dist/path-containment.test.d.ts +2 -0
  46. package/dist/path-containment.test.d.ts.map +1 -0
  47. package/dist/path-containment.test.js +91 -0
  48. package/dist/paths.d.ts +25 -0
  49. package/dist/paths.d.ts.map +1 -0
  50. package/dist/paths.js +67 -0
  51. package/dist/scan.test.d.ts +2 -0
  52. package/dist/scan.test.d.ts.map +1 -0
  53. package/dist/scan.test.js +107 -0
  54. package/dist/tokens.d.ts +12 -0
  55. package/dist/tokens.d.ts.map +1 -0
  56. package/dist/tokens.js +42 -0
  57. package/dist/types.d.ts +170 -0
  58. package/dist/types.d.ts.map +1 -0
  59. package/dist/types.js +3 -0
  60. package/dist/url-encoding.test.d.ts +2 -0
  61. package/dist/url-encoding.test.d.ts.map +1 -0
  62. package/dist/url-encoding.test.js +88 -0
  63. package/dist/version.d.ts +3 -0
  64. package/dist/version.d.ts.map +1 -0
  65. package/dist/version.js +3 -0
  66. package/package.json +57 -0
  67. package/src/bucket-name.test.ts +103 -0
  68. package/src/bucket-name.ts +83 -0
  69. package/src/errors.ts +22 -0
  70. package/src/file-server.test.ts +381 -0
  71. package/src/file-server.ts +203 -0
  72. package/src/index.aws.ts +219 -0
  73. package/src/index.browser.ts +7 -0
  74. package/src/index.cdk.test.ts +84 -0
  75. package/src/index.cdk.ts +89 -0
  76. package/src/index.mock.ts +531 -0
  77. package/src/index.test.ts +366 -0
  78. package/src/middleware.ts +66 -0
  79. package/src/mock-middleware.ts +66 -0
  80. package/src/mock-utils.ts +31 -0
  81. package/src/path-containment.test.ts +122 -0
  82. package/src/paths.ts +78 -0
  83. package/src/scan.test.ts +137 -0
  84. package/src/tokens.ts +61 -0
  85. package/src/types.ts +206 -0
  86. package/src/url-encoding.test.ts +120 -0
  87. package/src/version.ts +3 -0
package/LICENSE ADDED
@@ -0,0 +1,174 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
package/README.md ADDED
@@ -0,0 +1,197 @@
1
+ # FileBucket
2
+
3
+ File storage backed by Amazon S3.
4
+
5
+ **When to use:** You need to store, retrieve, or serve binary files — user uploads, generated reports, images, videos, or static assets.
6
+
7
+ **When NOT to use:** If you need structured key-value data with conditional writes, use `KVStore`. If you need queryable records with indexes, use `DistributedTable`.
8
+
9
+ ## API
10
+
11
+ ```typescript
12
+ const bucket = new FileBucket(scope, id, options?)
13
+ ```
14
+
15
+ | Method | Returns | Description |
16
+ |--------|---------|-------------|
17
+ | `put(path, body, options?)` | `Promise<void>` | Upload a file. Overwrites any existing file at the path. |
18
+ | `get(path, options?)` | `Promise<FileContent \| null>` | Download a file. Returns `null` if absent. Pass `{ versionId }` on versioned buckets. |
19
+ | `delete(path, options?)` | `Promise<void>` | Delete a file. No-op if absent. Pass `{ versionId }` on versioned buckets to permanently delete a version. |
20
+ | `deleteBatch(paths)` | `Promise<void>` | Delete multiple files. Chunks internally at 1,000 keys. |
21
+ | `getUrl(path, options?)` | `Promise<string>` | Generate a presigned download URL. Accepts `versionId` on versioned buckets. |
22
+ | `putUrl(path, options?)` | `Promise<string>` | Generate a presigned upload URL. |
23
+ | `getFileHandle(path, options?)` | `Promise<FileDownloadClient>` | Get a download handle for browser-side use. Accepts `versionId` on versioned buckets. |
24
+ | `createUploadHandle(path, options?)` | `Promise<FileUploadClient>` | Get an upload handle for browser-side use. |
25
+ | `scan(options?)` | `AsyncIterable<FileInfo>` | List files. Use `prefix` to scope. |
26
+ | `listVersions(path)` | `Promise<FileVersionInfo[]>` | List all versions of a file (versioned buckets only). Newest first. |
27
+ | `restoreVersion(path, versionId)` | `Promise<void>` | Restore a previous version as the current version. |
28
+ | `FileBucket.fromExisting(bucketName)` | `ExternalBucketRef` | Wrap a pre-existing S3 bucket. |
29
+
30
+ ### Options
31
+
32
+ | Option | Type | Description |
33
+ |--------|------|-------------|
34
+ | `versioned` | `boolean` | Enable S3 object versioning. Default: `false`. |
35
+ | `corsRules` | `CorsRule[]` | CORS rules for browser-based access. |
36
+ | `lifecycleRules` | `LifecycleRule[]` | Lifecycle rules for automatic expiration or storage class transitions. |
37
+ | `bucket` | `ExternalBucketRef` | Wrap an existing S3 bucket instead of creating one. |
38
+
39
+ ### PutOptions
40
+
41
+ | Option | Type | Description |
42
+ |--------|------|-------------|
43
+ | `contentType` | `string` | MIME type (e.g., `image/png`). Default: `application/octet-stream`. |
44
+ | `metadata` | `Record<string, string>` | Custom metadata key-value pairs. |
45
+ | `cacheControl` | `string` | Cache-Control header value. |
46
+
47
+ ### Error Handling
48
+
49
+ `get()` returns `null` for a missing file — it does **not** throw `FileNotFound`. Check for null:
50
+
51
+ ```typescript
52
+ const file = await bucket.get('missing.txt');
53
+ if (!file) {
54
+ // file does not exist
55
+ }
56
+ ```
57
+
58
+ `FileBucketErrors` are thrown by other operations and matched with `isBlocksError`:
59
+
60
+ | Constant | `error.name` | Thrown when |
61
+ |----------|--------------|-------------|
62
+ | `FileBucketErrors.FileNotFound` | `NoSuchKey` | Surfaced by presigned-URL 404s etc. **Not** thrown by `get()`, which returns `null`. |
63
+ | `FileBucketErrors.FileTooLarge` | `EntityTooLarge` | File exceeds size limits. |
64
+
65
+ ```typescript
66
+ import { isBlocksError } from '@aws-blocks/core';
67
+ import { FileBucketErrors } from '@aws-blocks/bb-file-bucket';
68
+
69
+ try {
70
+ await bucket.restoreVersion('report.pdf', 'non-existent-version');
71
+ } catch (e: unknown) {
72
+ if (isBlocksError(e, FileBucketErrors.FileNotFound)) {
73
+ // source version does not exist
74
+ }
75
+ throw e;
76
+ }
77
+ ```
78
+
79
+ ## Examples
80
+
81
+ ### Basic Put/Get
82
+
83
+ ```typescript
84
+ const bucket = new FileBucket(scope, 'uploads');
85
+
86
+ export const api = new ApiNamespace(scope, 'api', (context) => ({
87
+ async uploadFile(name: string, content: string) {
88
+ await bucket.put(name, content, { contentType: 'text/plain' });
89
+ },
90
+ async getFile(name: string) {
91
+ const file = await bucket.get(name);
92
+ if (!file) return null;
93
+ return { contentType: file.contentType, size: file.size };
94
+ },
95
+ }));
96
+ ```
97
+
98
+ ### Presigned Upload URL
99
+
100
+ ```typescript
101
+ const bucket = new FileBucket(scope, 'media');
102
+
103
+ export const api = new ApiNamespace(scope, 'api', (context) => ({
104
+ async getUploadUrl(path: string) {
105
+ const url = await bucket.putUrl(path, {
106
+ expiresIn: 600,
107
+ contentType: 'image/jpeg',
108
+ });
109
+ return { uploadUrl: url };
110
+ },
111
+ }));
112
+ ```
113
+
114
+ ### Listing Files with Scan
115
+
116
+ ```typescript
117
+ const bucket = new FileBucket(scope, 'reports');
118
+
119
+ export const api = new ApiNamespace(scope, 'api', (context) => ({
120
+ async listReports(yearMonth: string) {
121
+ const files: FileInfo[] = [];
122
+ for await (const file of bucket.scan({ prefix: `reports/${yearMonth}/` })) {
123
+ files.push(file);
124
+ }
125
+ return files;
126
+ },
127
+ }));
128
+ ```
129
+
130
+ ### Batch Delete
131
+
132
+ ```typescript
133
+ const bucket = new FileBucket(scope, 'tmp');
134
+
135
+ export const api = new ApiNamespace(scope, 'api', (context) => ({
136
+ async cleanupTemp(paths: string[]) {
137
+ await bucket.deleteBatch(paths);
138
+ },
139
+ }));
140
+ ```
141
+
142
+ ### Wrapping an Existing Bucket
143
+
144
+ ```typescript
145
+ const bucket = new FileBucket(scope, 'legacy', {
146
+ bucket: FileBucket.fromExisting('my-existing-bucket'),
147
+ });
148
+ ```
149
+
150
+ ### Versioned Bucket
151
+
152
+ ```typescript
153
+ const bucket = new FileBucket(scope, 'docs', { versioned: true });
154
+
155
+ export const api = new ApiNamespace(scope, 'api', (context) => ({
156
+ async upload(name: string, content: string) {
157
+ await bucket.put(name, content);
158
+ },
159
+ async getVersion(name: string, versionId?: string) {
160
+ return await bucket.get(name, versionId ? { versionId } : undefined);
161
+ },
162
+ async listVersions(name: string) {
163
+ return await bucket.listVersions(name);
164
+ },
165
+ async restore(name: string, versionId: string) {
166
+ await bucket.restoreVersion(name, versionId);
167
+ },
168
+ }));
169
+ ```
170
+
171
+ ## Best Practices
172
+
173
+ - Use path prefixes to organize files (e.g., `uploads/{userId}/`, `reports/`). If a segment can contain URL-shaped or special characters (e.g. an OIDC `userId` of `${iss}:${sub}` like `https://issuer:sub`), wrap it in `encodeURIComponent()` first — the local mock normalizes `//` in keys via the filesystem, so an un-encoded `//` makes `scan({ prefix })` miss the file locally even though it works against S3.
174
+ - Set `contentType` on `put()` to ensure correct MIME handling on download
175
+ - Use presigned URLs (`getUrl` / `putUrl`) for direct browser upload/download
176
+ - Prefer `scan({ prefix })` over unscoped `scan()` to limit enumeration cost
177
+ - For browser uploads/downloads returned from API methods, prefer `createUploadHandle`/`getFileHandle` over raw presigned URLs — they encode the fetch protocol into typed methods so the client can't misuse them
178
+ - Use `deleteBatch()` instead of looping `delete()` for bulk operations
179
+
180
+ ## Scaling & Cost (AWS)
181
+
182
+ - **Billing:** Per-request plus storage — no provisioned throughput
183
+ - **Latency:** First-byte latency typically 100–200 ms
184
+ - **Throughput:** Scales automatically, 5,500 GET and 3,500 PUT requests/second per prefix
185
+ - **Object size limit:** 5 TB per object
186
+ - **Cost:** ~$0.005 per 1,000 PUT requests, ~$0.0004 per 1,000 GET requests, ~$0.023/GB/month storage
187
+ - **Durability:** 99.999999999% (11 nines) across 3+ AZs
188
+
189
+ ## Local Development
190
+
191
+ Mock data persists to disk at `.bb-data/{fullId}/` across dev server restarts. Internal data is segregated into sibling roots so it never collides with your keys: file bodies live under `content/`, metadata under `meta/`, and version history under `versions/`. Wipe with `rm -rf .bb-data`. Presigned URLs are served by the dev server at `/.bb-file-bucket/{fullId}/{path}?token=...`. Versioning is fully supported locally. Lifecycle rules and CORS have no effect locally.
192
+
193
+
194
+
195
+ ## See Also
196
+
197
+ - [DESIGN.md](./DESIGN.md) — Infrastructure details, mock parity gaps, and interface decisions
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Validate an auto-derived S3 bucket name. Throws a `ValidationFailed` error
3
+ * with an actionable message when the name violates an S3 naming rule.
4
+ *
5
+ * @param name - The bucket name (the scope's `fullId`).
6
+ * @throws {Error} With name `ValidationFailed` if the name is invalid.
7
+ */
8
+ export declare function validateBucketName(name: string): void;
9
+ //# sourceMappingURL=bucket-name.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bucket-name.d.ts","sourceRoot":"","sources":["../src/bucket-name.ts"],"names":[],"mappings":"AAiCA;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CA0CrD"}
@@ -0,0 +1,62 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * S3 bucket-name validation, shared by the CDK (synth) and mock (local dev)
5
+ * entry points so a name that would be rejected by CloudFormation fails the
6
+ * same way during `bb dev` — long before a deploy is attempted.
7
+ *
8
+ * Bucket names are derived from the scope chain (`scope.fullId`). Because S3
9
+ * bucket names are globally unique and immutable, we deliberately error rather
10
+ * than silently truncate/hash: a truncated name could collide, and a name that
11
+ * shifts between deploys would orphan or replace the customer's data. The fix
12
+ * belongs in the developer's hands — shorten a scope id once and the name is
13
+ * stable forever.
14
+ *
15
+ * Rules enforced (AWS general-purpose bucket naming):
16
+ * - 3–63 characters
17
+ * - lowercase letters, numbers, dots (`.`), and hyphens (`-`) only
18
+ * - must begin and end with a letter or number
19
+ * - must not contain two adjacent dots
20
+ *
21
+ * @see https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html
22
+ */
23
+ const MIN_LEN = 3;
24
+ const MAX_LEN = 63;
25
+ function blocksError(name, message) {
26
+ const err = new Error(`${name}: ${message}`);
27
+ err.name = name;
28
+ return err;
29
+ }
30
+ /**
31
+ * Validate an auto-derived S3 bucket name. Throws a `ValidationFailed` error
32
+ * with an actionable message when the name violates an S3 naming rule.
33
+ *
34
+ * @param name - The bucket name (the scope's `fullId`).
35
+ * @throws {Error} With name `ValidationFailed` if the name is invalid.
36
+ */
37
+ export function validateBucketName(name) {
38
+ const hint = `FileBucket names are derived from the scope chain (id of the bucket ` +
39
+ `plus its parent scopes, joined with "-"). Shorten the FileBucket id ` +
40
+ `or a parent scope id, or pass an existing bucket via ` +
41
+ `FileBucket.fromExisting(...).`;
42
+ if (name.length > MAX_LEN) {
43
+ throw blocksError('ValidationFailed', `Derived bucket name "${name}" is ${name.length} characters, ` +
44
+ `exceeding S3's ${MAX_LEN}-character limit. ${hint}`);
45
+ }
46
+ if (name.length < MIN_LEN) {
47
+ throw blocksError('ValidationFailed', `Derived bucket name "${name}" is ${name.length} characters; ` +
48
+ `S3 requires at least ${MIN_LEN}. ${hint}`);
49
+ }
50
+ if (!/^[a-z0-9.-]+$/.test(name)) {
51
+ throw blocksError('ValidationFailed', `Derived bucket name "${name}" contains characters that are invalid ` +
52
+ `for an S3 bucket. Use only lowercase letters, numbers, dots (.), ` +
53
+ `and hyphens (-). ${hint}`);
54
+ }
55
+ if (!/^[a-z0-9]/.test(name) || !/[a-z0-9]$/.test(name)) {
56
+ throw blocksError('ValidationFailed', `Derived bucket name "${name}" must begin and end with a lowercase ` +
57
+ `letter or number. ${hint}`);
58
+ }
59
+ if (name.includes('..')) {
60
+ throw blocksError('ValidationFailed', `Derived bucket name "${name}" must not contain two adjacent dots. ${hint}`);
61
+ }
62
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=bucket-name.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bucket-name.test.d.ts","sourceRoot":"","sources":["../src/bucket-name.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,61 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * Tests for the shared S3 bucket-name validator and its enforcement in the
5
+ * mock entry point. The CDK side is covered in index.cdk.test.ts; this file
6
+ * pins the validator rules and the local-dev (mock) parity behavior.
7
+ */
8
+ import { test } from 'node:test';
9
+ import assert from 'node:assert';
10
+ import { Scope, isBlocksError } from '@aws-blocks/core';
11
+ import { validateBucketName } from './bucket-name.js';
12
+ import { FileBucket } from './index.mock.js';
13
+ // ── Validator unit tests ─────────────────────────────────────────────────────
14
+ test('accepts a valid lowercase hyphenated name', () => {
15
+ assert.doesNotThrow(() => validateBucketName('myapp-uploads'));
16
+ });
17
+ test('accepts a name at exactly 63 characters', () => {
18
+ const name = 'a'.repeat(63);
19
+ assert.doesNotThrow(() => validateBucketName(name));
20
+ });
21
+ test('rejects a name over 63 characters with an actionable message', () => {
22
+ const name = 'a'.repeat(64);
23
+ assert.throws(() => validateBucketName(name), (err) => isBlocksError(err, 'ValidationFailed') &&
24
+ /64 characters/.test(err.message) &&
25
+ /63-character limit/.test(err.message) &&
26
+ /Shorten/.test(err.message));
27
+ });
28
+ test('rejects a name under 3 characters', () => {
29
+ assert.throws(() => validateBucketName('ab'), (err) => isBlocksError(err, 'ValidationFailed') && /at least 3/.test(err.message));
30
+ });
31
+ test('rejects uppercase characters', () => {
32
+ assert.throws(() => validateBucketName('MyApp-Uploads'), (err) => isBlocksError(err, 'ValidationFailed') && /lowercase/.test(err.message));
33
+ });
34
+ test('rejects underscores', () => {
35
+ assert.throws(() => validateBucketName('my_app_uploads'), (err) => isBlocksError(err, 'ValidationFailed'));
36
+ });
37
+ test('rejects a name not starting with a letter or number', () => {
38
+ assert.throws(() => validateBucketName('-myapp'), (err) => isBlocksError(err, 'ValidationFailed') && /begin and end/.test(err.message));
39
+ });
40
+ test('rejects a name not ending with a letter or number', () => {
41
+ assert.throws(() => validateBucketName('myapp-'), (err) => isBlocksError(err, 'ValidationFailed') && /begin and end/.test(err.message));
42
+ });
43
+ test('rejects adjacent dots', () => {
44
+ assert.throws(() => validateBucketName('my..app'), (err) => isBlocksError(err, 'ValidationFailed') && /adjacent dots/.test(err.message));
45
+ });
46
+ // ── Mock parity: construction enforces the same rules ────────────────────────
47
+ test('mock: constructing a FileBucket with a too-long derived name throws', () => {
48
+ // Parent id + child id joined with "-" must exceed 63 chars.
49
+ const longParent = new Scope('p'.repeat(60));
50
+ assert.throws(() => new FileBucket(longParent, 'uploads'), (err) => isBlocksError(err, 'ValidationFailed') && /63-character limit/.test(err.message));
51
+ });
52
+ test('mock: constructing a FileBucket with a valid derived name succeeds', () => {
53
+ const parent = new Scope('shortapp');
54
+ assert.doesNotThrow(() => new FileBucket(parent, 'uploads'));
55
+ });
56
+ test('mock: fromExisting bypasses derived-name validation', () => {
57
+ // An over-long scope chain would normally fail, but fromExisting wraps an
58
+ // externally-named bucket so the derived name is not used.
59
+ const longParent = new Scope('p'.repeat(60));
60
+ assert.doesNotThrow(() => new FileBucket(longParent, 'uploads', { bucket: FileBucket.fromExisting('preexisting-bucket-123') }));
61
+ });
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Typed error constants for FileBucket. Use with `isBlocksError()` in catch blocks.
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * try {
7
+ * const file = await bucket.get('missing.txt');
8
+ * } catch (e: unknown) {
9
+ * if (isBlocksError(e, FileBucketErrors.FileNotFound)) {
10
+ * // file does not exist
11
+ * }
12
+ * throw e;
13
+ * }
14
+ * ```
15
+ */
16
+ export declare const FileBucketErrors: {
17
+ readonly FileNotFound: "NoSuchKey";
18
+ readonly FileTooLarge: "EntityTooLarge";
19
+ };
20
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,gBAAgB;;;CAGnB,CAAC"}
package/dist/errors.js ADDED
@@ -0,0 +1,21 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * Typed error constants for FileBucket. Use with `isBlocksError()` in catch blocks.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * try {
9
+ * const file = await bucket.get('missing.txt');
10
+ * } catch (e: unknown) {
11
+ * if (isBlocksError(e, FileBucketErrors.FileNotFound)) {
12
+ * // file does not exist
13
+ * }
14
+ * throw e;
15
+ * }
16
+ * ```
17
+ */
18
+ export const FileBucketErrors = {
19
+ FileNotFound: 'NoSuchKey',
20
+ FileTooLarge: 'EntityTooLarge',
21
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Dev server attachment for FileBucket.
3
+ * Serves token-gated GET/PUT requests at /.bb-file-bucket/{fullId}/{path}?token=...
4
+ * Mirrors S3 presigned URL behavior: method-scoped, time-limited, path-specific.
5
+ *
6
+ * Storage layout mirrors `index.mock.ts` via the shared `paths.ts` helpers, so
7
+ * user content (under `content/`) is never confused with internal metadata or
8
+ * version bookkeeping. PUT always delegates to the registered FileBucket
9
+ * instance so uploads get versioning, key validation, and metadata handling —
10
+ * there is no direct-write fallback.
11
+ */
12
+ import type { Server } from 'node:http';
13
+ export declare function attach(httpServer: Server): void;
14
+ //# sourceMappingURL=file-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-server.d.ts","sourceRoot":"","sources":["../src/file-server.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAmC,MAAM,WAAW,CAAC;AAyCzE,wBAAgB,MAAM,CAAC,UAAU,EAAE,MAAM,QAkJxC"}