@nuasite/cms-core 0.64.2 → 0.65.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 (187) hide show
  1. package/dist/asset-paths.d.ts.map +1 -0
  2. package/dist/asset-paths.js +55 -0
  3. package/dist/astro-source-analysis.d.ts.map +1 -0
  4. package/dist/astro-source-analysis.js +503 -0
  5. package/dist/byte-range.d.ts.map +1 -0
  6. package/dist/byte-range.js +31 -0
  7. package/dist/{types/check-entries.d.ts → check-entries.d.ts} +3 -3
  8. package/dist/check-entries.d.ts.map +1 -0
  9. package/dist/check-entries.js +98 -0
  10. package/dist/{types/check-live.d.ts → check-live.d.ts} +4 -4
  11. package/dist/check-live.d.ts.map +1 -0
  12. package/dist/check-live.js +49 -0
  13. package/dist/{types/check-shape.d.ts → check-shape.d.ts} +4 -4
  14. package/dist/check-shape.d.ts.map +1 -0
  15. package/dist/check-shape.js +119 -0
  16. package/dist/{types/check-write.d.ts → check-write.d.ts} +4 -4
  17. package/dist/check-write.d.ts.map +1 -0
  18. package/dist/check-write.js +273 -0
  19. package/dist/{types/check.d.ts → check.d.ts} +2 -2
  20. package/dist/check.d.ts.map +1 -0
  21. package/dist/check.js +366 -0
  22. package/dist/{types/collection-scanner.d.ts → collection-scanner.d.ts} +2 -2
  23. package/dist/collection-scanner.d.ts.map +1 -0
  24. package/dist/collection-scanner.js +1483 -0
  25. package/dist/{types/component-registry.d.ts → component-registry.d.ts} +1 -1
  26. package/dist/component-registry.d.ts.map +1 -0
  27. package/dist/component-registry.js +271 -0
  28. package/dist/{types/content-config-ast.d.ts → content-config-ast.d.ts} +1 -1
  29. package/dist/content-config-ast.d.ts.map +1 -0
  30. package/dist/content-config-ast.js +1614 -0
  31. package/dist/{types/core.d.ts → core.d.ts} +3 -3
  32. package/dist/core.d.ts.map +1 -0
  33. package/dist/core.js +94 -0
  34. package/dist/editor-write-model.d.ts.map +1 -0
  35. package/dist/editor-write-model.js +101 -0
  36. package/dist/fs/glob.d.ts.map +1 -0
  37. package/dist/fs/glob.js +79 -0
  38. package/dist/{types/fs → fs}/node-fs.d.ts +1 -1
  39. package/dist/fs/node-fs.d.ts.map +1 -0
  40. package/dist/fs/node-fs.js +199 -0
  41. package/dist/{types/fs → fs}/staged.d.ts +1 -1
  42. package/dist/fs/staged.d.ts.map +1 -0
  43. package/dist/fs/staged.js +203 -0
  44. package/dist/fs/types.d.ts.map +1 -0
  45. package/dist/fs/types.js +0 -0
  46. package/dist/{types/handlers → handlers}/entry-ops.d.ts +2 -2
  47. package/dist/handlers/entry-ops.d.ts.map +1 -0
  48. package/dist/handlers/entry-ops.js +846 -0
  49. package/dist/{types/handlers → handlers}/page-ops.d.ts +1 -1
  50. package/dist/handlers/page-ops.d.ts.map +1 -0
  51. package/dist/handlers/page-ops.js +165 -0
  52. package/dist/{types/handlers → handlers}/redirect-ops.d.ts +1 -1
  53. package/dist/handlers/redirect-ops.d.ts.map +1 -0
  54. package/dist/handlers/redirect-ops.js +111 -0
  55. package/dist/index.d.ts +5 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +4 -0
  58. package/dist/media/contember.d.ts.map +1 -0
  59. package/dist/media/contember.js +79 -0
  60. package/dist/media/errors.d.ts.map +1 -0
  61. package/dist/media/errors.js +22 -0
  62. package/dist/{types/media → media}/file-system.d.ts +1 -1
  63. package/dist/media/file-system.d.ts.map +1 -0
  64. package/dist/media/file-system.js +124 -0
  65. package/dist/{types/media → media}/index.d.ts +8 -8
  66. package/dist/media/index.d.ts.map +1 -0
  67. package/dist/media/index.js +8 -0
  68. package/dist/media/local.d.ts.map +1 -0
  69. package/dist/media/local.js +209 -0
  70. package/dist/media/mime.d.ts.map +1 -0
  71. package/dist/media/mime.js +21 -0
  72. package/dist/media/names.d.ts.map +1 -0
  73. package/dist/media/names.js +23 -0
  74. package/dist/{types/media → media}/project-images.d.ts +1 -1
  75. package/dist/media/project-images.d.ts.map +1 -0
  76. package/dist/media/project-images.js +99 -0
  77. package/dist/media/s3.d.ts.map +1 -0
  78. package/dist/media/s3.js +160 -0
  79. package/dist/media/type-filter.d.ts.map +1 -0
  80. package/dist/media/type-filter.js +164 -0
  81. package/dist/{types/portable.d.ts → portable.d.ts} +25 -25
  82. package/dist/portable.d.ts.map +1 -0
  83. package/dist/portable.js +27 -0
  84. package/dist/{types/project-config-ast.d.ts → project-config-ast.d.ts} +1 -1
  85. package/dist/project-config-ast.d.ts.map +1 -0
  86. package/dist/project-config-ast.js +324 -0
  87. package/dist/public-static-file.d.ts.map +1 -0
  88. package/dist/public-static-file.js +40 -0
  89. package/dist/redirects.d.ts.map +1 -0
  90. package/dist/redirects.js +185 -0
  91. package/dist/route-scan.d.ts.map +1 -0
  92. package/dist/route-scan.js +23 -0
  93. package/dist/schema-port.d.ts.map +1 -0
  94. package/dist/schema-port.js +30 -0
  95. package/dist/{types/schema-probe.d.ts → schema-probe.d.ts} +2 -2
  96. package/dist/schema-probe.d.ts.map +1 -0
  97. package/dist/schema-probe.js +119 -0
  98. package/dist/shared.d.ts.map +1 -0
  99. package/dist/shared.js +163 -0
  100. package/dist/tsconfig.tsbuildinfo +1 -0
  101. package/package.json +12 -12
  102. package/src/check-entries.ts +4 -4
  103. package/src/check-live.ts +4 -4
  104. package/src/check-shape.ts +5 -5
  105. package/src/check-write.ts +6 -6
  106. package/src/check.ts +15 -9
  107. package/src/collection-scanner.ts +3 -3
  108. package/src/component-registry.ts +1 -1
  109. package/src/content-config-ast.ts +1 -1
  110. package/src/core.ts +8 -8
  111. package/src/editor-write-model.ts +1 -1
  112. package/src/fs/node-fs.ts +2 -2
  113. package/src/fs/staged.ts +6 -3
  114. package/src/handlers/entry-ops.ts +7 -7
  115. package/src/handlers/page-ops.ts +2 -2
  116. package/src/handlers/redirect-ops.ts +2 -2
  117. package/src/index.ts +4 -4
  118. package/src/media/contember.ts +1 -1
  119. package/src/media/file-system.ts +4 -4
  120. package/src/media/index.ts +8 -8
  121. package/src/media/local.ts +3 -3
  122. package/src/media/project-images.ts +2 -2
  123. package/src/media/s3.ts +3 -3
  124. package/src/portable.ts +25 -25
  125. package/src/project-config-ast.ts +1 -1
  126. package/src/route-scan.ts +1 -1
  127. package/src/schema-probe.ts +2 -2
  128. package/src/tsconfig.json +5 -1
  129. package/dist/types/asset-paths.d.ts.map +0 -1
  130. package/dist/types/astro-source-analysis.d.ts.map +0 -1
  131. package/dist/types/byte-range.d.ts.map +0 -1
  132. package/dist/types/check-entries.d.ts.map +0 -1
  133. package/dist/types/check-live.d.ts.map +0 -1
  134. package/dist/types/check-shape.d.ts.map +0 -1
  135. package/dist/types/check-write.d.ts.map +0 -1
  136. package/dist/types/check.d.ts.map +0 -1
  137. package/dist/types/collection-scanner.d.ts.map +0 -1
  138. package/dist/types/component-registry.d.ts.map +0 -1
  139. package/dist/types/content-config-ast.d.ts.map +0 -1
  140. package/dist/types/core.d.ts.map +0 -1
  141. package/dist/types/editor-write-model.d.ts.map +0 -1
  142. package/dist/types/fs/glob.d.ts.map +0 -1
  143. package/dist/types/fs/node-fs.d.ts.map +0 -1
  144. package/dist/types/fs/staged.d.ts.map +0 -1
  145. package/dist/types/fs/types.d.ts.map +0 -1
  146. package/dist/types/handlers/entry-ops.d.ts.map +0 -1
  147. package/dist/types/handlers/page-ops.d.ts.map +0 -1
  148. package/dist/types/handlers/redirect-ops.d.ts.map +0 -1
  149. package/dist/types/index.d.ts +0 -5
  150. package/dist/types/index.d.ts.map +0 -1
  151. package/dist/types/media/contember.d.ts.map +0 -1
  152. package/dist/types/media/errors.d.ts.map +0 -1
  153. package/dist/types/media/file-system.d.ts.map +0 -1
  154. package/dist/types/media/index.d.ts.map +0 -1
  155. package/dist/types/media/local.d.ts.map +0 -1
  156. package/dist/types/media/mime.d.ts.map +0 -1
  157. package/dist/types/media/names.d.ts.map +0 -1
  158. package/dist/types/media/project-images.d.ts.map +0 -1
  159. package/dist/types/media/s3.d.ts.map +0 -1
  160. package/dist/types/media/type-filter.d.ts.map +0 -1
  161. package/dist/types/portable.d.ts.map +0 -1
  162. package/dist/types/project-config-ast.d.ts.map +0 -1
  163. package/dist/types/public-static-file.d.ts.map +0 -1
  164. package/dist/types/redirects.d.ts.map +0 -1
  165. package/dist/types/route-scan.d.ts.map +0 -1
  166. package/dist/types/schema-port.d.ts.map +0 -1
  167. package/dist/types/schema-probe.d.ts.map +0 -1
  168. package/dist/types/shared.d.ts.map +0 -1
  169. package/dist/types/tsconfig.tsbuildinfo +0 -1
  170. /package/dist/{types/asset-paths.d.ts → asset-paths.d.ts} +0 -0
  171. /package/dist/{types/astro-source-analysis.d.ts → astro-source-analysis.d.ts} +0 -0
  172. /package/dist/{types/byte-range.d.ts → byte-range.d.ts} +0 -0
  173. /package/dist/{types/editor-write-model.d.ts → editor-write-model.d.ts} +0 -0
  174. /package/dist/{types/fs → fs}/glob.d.ts +0 -0
  175. /package/dist/{types/fs → fs}/types.d.ts +0 -0
  176. /package/dist/{types/media → media}/contember.d.ts +0 -0
  177. /package/dist/{types/media → media}/errors.d.ts +0 -0
  178. /package/dist/{types/media → media}/local.d.ts +0 -0
  179. /package/dist/{types/media → media}/mime.d.ts +0 -0
  180. /package/dist/{types/media → media}/names.d.ts +0 -0
  181. /package/dist/{types/media → media}/s3.d.ts +0 -0
  182. /package/dist/{types/media → media}/type-filter.d.ts +0 -0
  183. /package/dist/{types/public-static-file.d.ts → public-static-file.d.ts} +0 -0
  184. /package/dist/{types/redirects.d.ts → redirects.d.ts} +0 -0
  185. /package/dist/{types/route-scan.d.ts → route-scan.d.ts} +0 -0
  186. /package/dist/{types/schema-port.d.ts → schema-port.d.ts} +0 -0
  187. /package/dist/{types/shared.d.ts → shared.d.ts} +0 -0
@@ -0,0 +1,209 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID, MEDIA_NOT_FOUND } from "./errors.js";
5
+ import { getFileExtension, mimeFromExt } from "./mime.js";
6
+ import { isUnsafeFolder } from "./names.js";
7
+ /** `error.code` of a filesystem error, when it has one. */
8
+ function errorCode(error) {
9
+ return error instanceof Error && 'code' in error && typeof error.code === 'string' ? error.code : undefined;
10
+ }
11
+ /**
12
+ * A filesystem failure as a message: what was attempted and the error code. Never the
13
+ * runtime's own text, which spells out the absolute path.
14
+ */
15
+ function failure(action, error) {
16
+ const code = errorCode(error);
17
+ return code ? `Failed to ${action} (${code})` : `Failed to ${action}`;
18
+ }
19
+ /**
20
+ * Whether one of `names`, each taken below the one before it starting in `from`, is a
21
+ * symbolic link. Nothing here follows a link: every name is looked at with `lstat`,
22
+ * and the walk ends at the first one that is not there, since nothing below it can be
23
+ * either. Any other failure is thrown, so a name that cannot be inspected is never
24
+ * taken for a plain one.
25
+ */
26
+ async function hasSymlink(from, names) {
27
+ let current = from;
28
+ for (const name of names) {
29
+ current += path.sep + name;
30
+ try {
31
+ if ((await fs.lstat(current)).isSymbolicLink())
32
+ return true;
33
+ }
34
+ catch (error) {
35
+ const code = errorCode(error);
36
+ if (code === 'ENOENT' || code === 'ENOTDIR')
37
+ return false;
38
+ throw error;
39
+ }
40
+ }
41
+ return false;
42
+ }
43
+ export function createLocalStorageAdapter(options = {}) {
44
+ const dir = path.resolve(options.dir ?? 'public/uploads');
45
+ /** `dir` as the start of every path below it: without the separator a filesystem root ends in. */
46
+ const base = dir.endsWith(path.sep) ? dir.slice(0, -path.sep.length) : dir;
47
+ const urlPrefix = (options.urlPrefix ?? '/uploads').replace(/\/$/, '');
48
+ /**
49
+ * Resolve a caller-supplied id or folder to the path it names inside the uploads
50
+ * directory, or `null` when it names none. Every operation goes through here before
51
+ * it touches the filesystem.
52
+ *
53
+ * The spelling is the one `list` and `upload` hand out: names joined by `/`, none of
54
+ * them empty, `.` or `..`, and no NUL in any. Where the backslash separates paths,
55
+ * three more things make a name something other than what it spells and are refused:
56
+ * a backslash, a `:` (a drive or a stream), and a trailing dot or space (dropped by
57
+ * the system). Resolving such a path must change nothing: it is the directory
58
+ * followed by exactly these names, so it is below the directory.
59
+ *
60
+ * None of the names may be a symbolic link, wherever it points, because a link is
61
+ * the one thing that leads a path below the directory out of it. The exception is
62
+ * the last name of a file: `unlink` removes a link itself and never what it points
63
+ * to. The uploads directory and what is above it are the operator's and not looked
64
+ * at. The check is not atomic with the operation that follows it.
65
+ */
66
+ async function resolveInside(relative, kind) {
67
+ const segments = relative.split('/');
68
+ if (relative.includes('\0') || segments.some((s) => s === '' || s === '.' || s === '..'))
69
+ return null;
70
+ if (path.sep === '\\' && segments.some((s) => /[\\:]|[. ]$/.test(s)))
71
+ return null;
72
+ const resolved = path.resolve(dir, ...segments);
73
+ if (resolved !== [base, ...segments].join(path.sep))
74
+ return null;
75
+ if (await hasSymlink(base, kind === 'file' ? segments.slice(0, -1) : segments))
76
+ return null;
77
+ return resolved;
78
+ }
79
+ /**
80
+ * A `folder` option as the `a/b` spelling ids are built from, plus the directory it
81
+ * names: the uploads directory itself when empty, `null` when it is not inside it.
82
+ * Stray slashes are dropped (`/a//b/` is `a/b`), as `createFolder` always did.
83
+ *
84
+ * A folder to `write` into must also spell the same path once it is part of a URL
85
+ * (`isUnsafeFolder`), or the URL handed out for a file in it would address another
86
+ * one. A folder that already exists under such a name is still listed, so whatever
87
+ * is in it can be found and deleted.
88
+ */
89
+ async function resolveFolder(input, use) {
90
+ const folder = (input ?? '').split('/').filter(Boolean).join('/');
91
+ if (!folder)
92
+ return { folder, targetDir: dir };
93
+ if (use === 'write' && isUnsafeFolder(folder))
94
+ return null;
95
+ const targetDir = await resolveInside(folder, 'folder');
96
+ return targetDir ? { folder, targetDir } : null;
97
+ }
98
+ return {
99
+ staticFiles: { urlPrefix, dir },
100
+ async list(opts) {
101
+ const limit = opts?.limit ?? 50;
102
+ const offset = opts?.cursor ? parseInt(opts.cursor, 10) : 0;
103
+ const nothing = { items: [], folders: [], hasMore: false };
104
+ try {
105
+ const target = await resolveFolder(opts?.folder, 'read');
106
+ if (!target)
107
+ return nothing;
108
+ const { folder, targetDir } = target;
109
+ await fs.mkdir(targetDir, { recursive: true });
110
+ const entries = await fs.readdir(targetDir, { withFileTypes: true });
111
+ const folders = entries
112
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
113
+ .map((e) => ({
114
+ name: e.name,
115
+ path: folder ? `${folder}/${e.name}` : e.name,
116
+ }))
117
+ .sort((a, b) => a.name.localeCompare(b.name));
118
+ const files = entries.filter((e) => e.isFile() && !e.name.startsWith('.'));
119
+ const withStats = await Promise.all(files.map(async (f) => {
120
+ const filePath = path.join(targetDir, f.name);
121
+ const stat = await fs.stat(filePath);
122
+ return { name: f.name, stat };
123
+ }));
124
+ withStats.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
125
+ const slice = withStats.slice(offset, offset + limit);
126
+ const hasMore = offset + limit < withStats.length;
127
+ const urlFolder = folder ? `/${folder}` : '';
128
+ const items = slice.map((f) => {
129
+ const ext = path.extname(f.name).toLowerCase();
130
+ const contentType = mimeFromExt(ext);
131
+ return {
132
+ id: folder ? `${folder}/${f.name}` : f.name,
133
+ url: `${urlPrefix}${urlFolder}/${f.name}`,
134
+ filename: f.name,
135
+ contentType,
136
+ uploadedAt: f.stat.mtime.toISOString(),
137
+ folder: folder || undefined,
138
+ };
139
+ });
140
+ return {
141
+ items,
142
+ folders,
143
+ hasMore,
144
+ cursor: hasMore ? String(offset + limit) : undefined,
145
+ };
146
+ }
147
+ catch (error) {
148
+ // A name that belongs to a file, or is too long to be one, holds nothing to list.
149
+ const code = errorCode(error);
150
+ if (opts?.folder && (code === 'ENOTDIR' || code === 'EEXIST' || code === 'ENAMETOOLONG'))
151
+ return nothing;
152
+ // Deliberately without `cause`: whatever renders this error must not get the path back.
153
+ // oxlint-disable-next-line preserve-caught-error
154
+ throw new Error(failure('list media', error));
155
+ }
156
+ },
157
+ async upload(file, filename, contentType, uploadOpts) {
158
+ try {
159
+ const target = await resolveFolder(uploadOpts?.folder, 'write');
160
+ if (!target)
161
+ return { success: false, error: MEDIA_INVALID_FOLDER };
162
+ const { folder, targetDir } = target;
163
+ await fs.mkdir(targetDir, { recursive: true });
164
+ const ext = getFileExtension(filename);
165
+ const uuid = randomUUID();
166
+ const newFilename = `${uuid}${ext ? `.${ext}` : ''}`;
167
+ const filePath = path.join(targetDir, newFilename);
168
+ await fs.writeFile(filePath, file);
169
+ const urlFolder = folder ? `/${folder}` : '';
170
+ const id = folder ? `${folder}/${newFilename}` : newFilename;
171
+ return {
172
+ success: true,
173
+ url: `${urlPrefix}${urlFolder}/${newFilename}`,
174
+ filename: newFilename,
175
+ id,
176
+ };
177
+ }
178
+ catch (error) {
179
+ return { success: false, error: failure('store media file', error) };
180
+ }
181
+ },
182
+ async delete(id) {
183
+ try {
184
+ const filePath = await resolveInside(id, 'file');
185
+ if (!filePath)
186
+ return { success: false, error: MEDIA_INVALID_ID };
187
+ await fs.unlink(filePath);
188
+ return { success: true };
189
+ }
190
+ catch (error) {
191
+ if (errorCode(error) === 'ENOENT')
192
+ return { success: false, error: MEDIA_NOT_FOUND };
193
+ return { success: false, error: failure('delete media file', error) };
194
+ }
195
+ },
196
+ async createFolder(folder) {
197
+ try {
198
+ const target = await resolveFolder(folder, 'write');
199
+ if (!target)
200
+ return { success: false, error: MEDIA_INVALID_FOLDER };
201
+ await fs.mkdir(target.targetDir, { recursive: true });
202
+ return { success: true };
203
+ }
204
+ catch (error) {
205
+ return { success: false, error: failure('create folder', error) };
206
+ }
207
+ },
208
+ };
209
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mime.d.ts","sourceRoot":"","sources":["../../src/media/mime.ts"],"names":[],"mappings":"AAAA,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAIzD;AAED,eAAO,MAAM,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAY9C,CAAA;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE/C"}
@@ -0,0 +1,21 @@
1
+ export function getFileExtension(filename) {
2
+ const parts = filename.split('.');
3
+ const ext = parts.length > 1 ? (parts.pop()?.toLowerCase() ?? '') : '';
4
+ return /^[a-z0-9]+$/.test(ext) ? ext : '';
5
+ }
6
+ export const MIME_BY_EXT = {
7
+ '.jpg': 'image/jpeg',
8
+ '.jpeg': 'image/jpeg',
9
+ '.png': 'image/png',
10
+ '.gif': 'image/gif',
11
+ '.webp': 'image/webp',
12
+ '.avif': 'image/avif',
13
+ '.svg': 'image/svg+xml',
14
+ '.ico': 'image/x-icon',
15
+ '.mp4': 'video/mp4',
16
+ '.webm': 'video/webm',
17
+ '.pdf': 'application/pdf',
18
+ };
19
+ export function mimeFromExt(ext) {
20
+ return MIME_BY_EXT[ext] ?? 'application/octet-stream';
21
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"names.d.ts","sourceRoot":"","sources":["../../src/media/names.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAKtD"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Whether a `/`-separated name holds a `.` or `..` segment as it is spelled. These are
3
+ * the segments a path resolves away.
4
+ */
5
+ export function hasDotSegment(value) {
6
+ return value.split('/').some((s) => s === '.' || s === '..');
7
+ }
8
+ /**
9
+ * Whether a folder a caller asks to create or upload into would turn into something
10
+ * else once it is part of a URL. A URL parser reads a segment spelled `%2e`, `.%2e`,
11
+ * `%2e.` or `%2e%2e` (in any case) as `.` or `..`, and a backslash as `/`, so the URL
12
+ * built for a file in such a folder would address a different path than the one the
13
+ * file was stored at. Literal `.` and `..` segments count too.
14
+ *
15
+ * Only new folders are held to this: an id or folder that already exists in storage is
16
+ * still listed and deleted as it is spelled.
17
+ */
18
+ export function isUnsafeFolder(folder) {
19
+ return folder.includes('\\') || folder.split('/').some((s) => {
20
+ const decoded = s.replace(/%2e/gi, '.');
21
+ return decoded === '.' || decoded === '..';
22
+ });
23
+ }
@@ -1,5 +1,5 @@
1
1
  import type { MediaItem } from '@nuasite/cms-types';
2
- import type { CmsFileSystem } from '../fs/types';
2
+ import type { CmsFileSystem } from '../fs/types.ts';
3
3
  export interface ListProjectImagesOptions {
4
4
  /**
5
5
  * The media uploads directory, which the scan must not list a second time.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-images.d.ts","sourceRoot":"","sources":["../../src/media/project-images.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAKnD,MAAM,WAAW,wBAAwB;IACxC;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAA;IACxC;;;;;;;;;OASG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;CACnB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOlG;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,iBAAiB,CAAC,EAAE,EAAE,aAAa,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CA6BnH"}
@@ -0,0 +1,99 @@
1
+ import { MIME_BY_EXT, mimeFromExt } from "./mime.js";
2
+ const IMAGE_EXTENSIONS = new Set(Object.entries(MIME_BY_EXT).filter(([, mime]) => mime.startsWith('image/')).map(([ext]) => ext));
3
+ /**
4
+ * An uploads directory as a root-relative path, in the spelling the scan below walks.
5
+ *
6
+ * Accepts every spelling `MediaStorageAdapter.staticFiles.dir` documents: an absolute
7
+ * path under the root, a root-relative path with or without a leading slash, an optional
8
+ * `./` prefix and a trailing slash. A leading slash only means "absolute filesystem path"
9
+ * when the path actually starts with the root — otherwise it is root-relative, exactly
10
+ * the rule the {@link CmsFileSystem} port uses.
11
+ *
12
+ * `undefined` when there is no local directory at all (S3/Contember adapters); `''` (no
13
+ * exclusion) when it claims the whole project root.
14
+ */
15
+ export function uploadsDirRelativeToRoot(dir, root) {
16
+ if (dir === undefined)
17
+ return undefined;
18
+ const base = root.replace(/\/+$/, '');
19
+ const trimmed = dir.replace(/\/+$/, '');
20
+ if (trimmed === base)
21
+ return '';
22
+ if (trimmed.startsWith(`${base}/`))
23
+ return trimmed.slice(base.length + 1);
24
+ return trimmed.replace(/^\.\//, '').replace(/^\/+/, '');
25
+ }
26
+ /**
27
+ * Scan the project for image files in `public/` and `src/` directories,
28
+ * excluding the media uploads directory, over the FileSystem port.
29
+ *
30
+ * - `public/` files are served from `/<path-relative-to-public>`.
31
+ * - `src/` files are served from `/<path-relative-to-project-root>`.
32
+ *
33
+ * The result is ordered by filename, then by URL — a *total* order, so repeated
34
+ * calls over an unchanged tree return the exact same sequence. Callers paginate
35
+ * this list by offset (the sidecar's media cursor), which a partial order would
36
+ * silently break: the walk pushes into one array from concurrent recursive
37
+ * `Promise.all` branches, so the input order alone is not reproducible.
38
+ */
39
+ export async function listProjectImages(fs, options) {
40
+ // Normalised here rather than by the caller: the scan walks root-relative paths, so only
41
+ // this function knows what an exclusion has to look like to match one.
42
+ // The deprecated `excludeDir` keeps its own, weaker normalisation — it has no root to
43
+ // resolve against — so callers written against it behave exactly as before.
44
+ const normalized = options?.exclude
45
+ ? uploadsDirRelativeToRoot(options.exclude.dir, options.exclude.root)
46
+ : options?.excludeDir?.replace(/^\/+/, '').replace(/\/+$/, '');
47
+ // `''` — the uploads dir *is* the project root — excludes nothing, like no exclusion at all.
48
+ const excludeDir = normalized ? normalized : null;
49
+ const scanDirs = [
50
+ { dir: 'public', relativeToRoot: false },
51
+ { dir: 'src', relativeToRoot: true },
52
+ ];
53
+ const results = await Promise.all(scanDirs.map(async ({ dir, relativeToRoot }) => {
54
+ const items = [];
55
+ await scanDirectory(fs, dir, dir, relativeToRoot, excludeDir, items);
56
+ return items;
57
+ }));
58
+ const items = results.flat();
59
+ // Filename first (that is what the media grid shows), then the URL to break ties:
60
+ // two `hero.png` in different directories compare equal on the filename alone.
61
+ items.sort((a, b) => a.filename.localeCompare(b.filename) || compareCodeUnits(a.url, b.url));
62
+ return items;
63
+ }
64
+ /** Code-unit comparison: a total order on distinct strings, which `localeCompare` is not. */
65
+ function compareCodeUnits(a, b) {
66
+ return a < b ? -1 : a > b ? 1 : 0;
67
+ }
68
+ async function scanDirectory(fs, currentDir, baseDir, relativeToRoot, excludeDir, items) {
69
+ // `currentDir` is built from `public`/`src` downwards, so it is already in the
70
+ // normalised spelling `uploadsDirRelativeToRoot` produces.
71
+ if (excludeDir !== null && currentDir === excludeDir)
72
+ return;
73
+ const entries = await fs.list(currentDir);
74
+ const subdirs = [];
75
+ for (const entry of entries) {
76
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
77
+ continue;
78
+ const fullPath = `${currentDir}/${entry.name}`;
79
+ if (entry.isDirectory) {
80
+ subdirs.push(scanDirectory(fs, fullPath, baseDir, relativeToRoot, excludeDir, items));
81
+ }
82
+ else {
83
+ const dotIdx = entry.name.lastIndexOf('.');
84
+ const ext = dotIdx >= 0 ? entry.name.slice(dotIdx).toLowerCase() : '';
85
+ if (!IMAGE_EXTENSIONS.has(ext))
86
+ continue;
87
+ const url = relativeToRoot
88
+ ? `/${fullPath}`
89
+ : `/${fullPath.slice(baseDir.length + 1)}`;
90
+ items.push({
91
+ id: `project:${url}`,
92
+ url,
93
+ filename: entry.name,
94
+ contentType: mimeFromExt(ext),
95
+ });
96
+ }
97
+ }
98
+ await Promise.all(subdirs);
99
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"s3.d.ts","sourceRoot":"","sources":["../../src/media/s3.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoC,mBAAmB,EAAqB,MAAM,oBAAoB,CAAA;AAwBlH,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAA;CACf;AAQD,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,gBAAgB,GAAG,mBAAmB,CA4IrF"}
@@ -0,0 +1,160 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { randomUUID } from 'node:crypto';
10
+ import path from 'node:path';
11
+ import { MEDIA_INVALID_FOLDER, MEDIA_INVALID_ID } from "./errors.js";
12
+ import { getFileExtension, mimeFromExt } from "./mime.js";
13
+ import { hasDotSegment, isUnsafeFolder } from "./names.js";
14
+ /*
15
+ * S3 keys are literal, so `.` and `..` name nothing special there. Whatever sits in
16
+ * front of the bucket (a CDN, a proxy, the URL built from the key) may still resolve
17
+ * them, so the adapter neither builds nor accepts one in what a caller supplies: a
18
+ * folder (spelled out, percent-encoded or with a backslash, see `isUnsafeFolder`), or
19
+ * the part of a key after the configured prefix.
20
+ */
21
+ /**
22
+ * A `folder` option as the `a/b` spelling keys are built from. Stray slashes are dropped
23
+ * (`/a//b/` is `a/b`), as the local adapter does, so no key `upload` hands out holds an
24
+ * empty segment that `delete` would refuse.
25
+ */
26
+ function normalizeFolder(folder) {
27
+ return (folder ?? '').split('/').filter(Boolean).join('/');
28
+ }
29
+ // Dynamic import helper to avoid TS2307 for the optional `@aws-sdk/client-s3` peer dependency.
30
+ const s3Module = '@aws-sdk/client-s3';
31
+ async function loadS3() {
32
+ return import(__rewriteRelativeImportExtension(/* @vite-ignore */ s3Module));
33
+ }
34
+ export function createS3StorageAdapter(options) {
35
+ const { bucket, region, accessKeyId, secretAccessKey, endpoint, cdnPrefix, prefix = 'uploads' } = options;
36
+ let s3Client = null;
37
+ async function getClient() {
38
+ if (s3Client)
39
+ return s3Client;
40
+ const { S3Client } = await loadS3();
41
+ s3Client = new S3Client({
42
+ region,
43
+ ...(endpoint ? { endpoint } : {}),
44
+ ...(accessKeyId && secretAccessKey
45
+ ? { credentials: { accessKeyId, secretAccessKey } }
46
+ : {}),
47
+ });
48
+ return s3Client;
49
+ }
50
+ function getUrl(key) {
51
+ if (cdnPrefix) {
52
+ return `${cdnPrefix.replace(/\/$/, '')}/${key}`;
53
+ }
54
+ if (endpoint) {
55
+ return `${endpoint.replace(/\/$/, '')}/${bucket}/${key}`;
56
+ }
57
+ return `https://${bucket}.s3.${region}.amazonaws.com/${key}`;
58
+ }
59
+ return {
60
+ async list(opts) {
61
+ const { ListObjectsV2Command } = await loadS3();
62
+ const client = await getClient();
63
+ const limit = opts?.limit ?? 50;
64
+ const folder = normalizeFolder(opts?.folder);
65
+ if (isUnsafeFolder(folder))
66
+ return { items: [], folders: [], hasMore: false };
67
+ const listPrefix = [prefix, folder].filter(Boolean).join('/');
68
+ const delimiterPrefix = listPrefix ? `${listPrefix}/` : '';
69
+ const command = new ListObjectsV2Command({
70
+ Bucket: bucket,
71
+ Prefix: delimiterPrefix,
72
+ Delimiter: '/',
73
+ MaxKeys: limit + 1,
74
+ ...(opts?.cursor ? { ContinuationToken: opts.cursor } : {}),
75
+ });
76
+ const result = await client.send(command);
77
+ const folders = (result.CommonPrefixes ?? []).map((cp) => {
78
+ const fullPrefix = String(cp.Prefix).replace(/\/$/, '');
79
+ const name = fullPrefix.split('/').pop() ?? fullPrefix;
80
+ const relativePath = prefix ? fullPrefix.slice(prefix.length + 1) : fullPrefix;
81
+ return { name, path: relativePath };
82
+ });
83
+ const contents = (result.Contents ?? []).filter((obj) => {
84
+ const key = obj.Key;
85
+ return key !== delimiterPrefix;
86
+ });
87
+ const hasMore = contents.length > limit;
88
+ const items = contents.slice(0, limit).map((obj) => {
89
+ const key = obj.Key;
90
+ const filename = key.split('/').pop() ?? key;
91
+ return {
92
+ id: key,
93
+ url: getUrl(key),
94
+ filename,
95
+ contentType: mimeFromExt(path.extname(key).toLowerCase()),
96
+ uploadedAt: obj.LastModified?.toISOString(),
97
+ folder: folder || undefined,
98
+ };
99
+ });
100
+ return {
101
+ items,
102
+ folders,
103
+ hasMore,
104
+ cursor: hasMore ? result.NextContinuationToken : undefined,
105
+ };
106
+ },
107
+ async upload(file, filename, contentType, uploadOpts) {
108
+ const folder = normalizeFolder(uploadOpts?.folder);
109
+ if (isUnsafeFolder(folder))
110
+ return { success: false, error: MEDIA_INVALID_FOLDER };
111
+ const { PutObjectCommand } = await loadS3();
112
+ const client = await getClient();
113
+ const ext = getFileExtension(filename);
114
+ const uuid = randomUUID();
115
+ const newFilename = `${uuid}${ext ? `.${ext}` : ''}`;
116
+ const keyParts = [prefix, folder, newFilename].filter(Boolean);
117
+ const key = keyParts.join('/');
118
+ const command = new PutObjectCommand({
119
+ Bucket: bucket,
120
+ Key: key,
121
+ Body: file,
122
+ ContentType: contentType,
123
+ });
124
+ await client.send(command);
125
+ return {
126
+ success: true,
127
+ url: getUrl(key),
128
+ filename: newFilename,
129
+ id: key,
130
+ };
131
+ },
132
+ async delete(id) {
133
+ // An id is the object key `list` and `upload` hand out, so it always sits under the
134
+ // configured prefix. Anything else in the bucket is not this adapter's to remove.
135
+ // The prefix is the operator's and taken as configured; only what follows it is checked.
136
+ // What follows it names an object: not empty, and no empty, `.` or `..` segment in it.
137
+ if (prefix && !id.startsWith(`${prefix}/`))
138
+ return { success: false, error: MEDIA_INVALID_ID };
139
+ const rest = prefix ? id.slice(prefix.length + 1) : id;
140
+ if (rest.split('/').includes('') || hasDotSegment(rest))
141
+ return { success: false, error: MEDIA_INVALID_ID };
142
+ try {
143
+ const { DeleteObjectCommand } = await loadS3();
144
+ const client = await getClient();
145
+ const command = new DeleteObjectCommand({
146
+ Bucket: bucket,
147
+ Key: id,
148
+ });
149
+ await client.send(command);
150
+ return { success: true };
151
+ }
152
+ catch (error) {
153
+ // Prefixed, so no text the SDK or the service comes up with can pass for one of the
154
+ // adapter's own refusals.
155
+ const message = error instanceof Error ? error.message : String(error);
156
+ return { success: false, error: `Delete failed: ${message}` };
157
+ }
158
+ },
159
+ };
160
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type-filter.d.ts","sourceRoot":"","sources":["../../src/media/type-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,MAAM,oBAAoB,CAAA;AAE3B,iFAAiF;AACjF,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,eAAe,GAAG,IAAI,CAG3F;AAED;;;GAGG;AACH,qBAAa,gBAAiB,SAAQ,KAAK;IACjC,IAAI,SAAqB;CAClC;AAED,eAAO,MAAM,oBAAoB,yBAAyB,CAAA;AAC1D,eAAO,MAAM,0BAA0B,oHAC2E,CAAA;AAElH;;;;;GAKG;AACH,UAAU,gBAAgB;IACzB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACZ;AAoBD;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,gBAAgB,GAAG;IAAE,IAAI,EAAE,eAAe,CAAA;CAAE,CAAC,GAAG,IAAI,CAoB5G;AASD;;;GAGG;AACH,eAAO,MAAM,wBAAwB,OAAO,CAAA;AAe5C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,iBAAiB,CACtC,IAAI,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,OAAO,CAAC,eAAe,CAAC,EAC7D,OAAO,EAAE,gBAAgB,GAAG;IAAE,IAAI,CAAC,EAAE,eAAe,CAAA;CAAE;AACtD;;;;GAIG;AACH,UAAU,SAAc,GACtB,OAAO,CAAC,eAAe,CAAC,CA8C1B"}