@venizia/ignis 0.4.8-11 → 0.4.8-12

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 (93) hide show
  1. package/dist/esm/components/mail/common/types/queue.d.ts +8 -4
  2. package/dist/esm/components/mail/common/types/queue.js.map +1 -1
  3. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.d.ts +1 -1
  4. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +2 -16
  5. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
  6. package/dist/esm/components/static-asset/common/constants.d.ts +18 -11
  7. package/dist/esm/components/static-asset/common/constants.js +35 -20
  8. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  9. package/dist/esm/components/static-asset/common/errors.d.ts +11 -43
  10. package/dist/esm/components/static-asset/common/errors.js +11 -40
  11. package/dist/esm/components/static-asset/common/errors.js.map +1 -1
  12. package/dist/esm/components/static-asset/common/index.d.ts +1 -0
  13. package/dist/esm/components/static-asset/common/index.js +1 -0
  14. package/dist/esm/components/static-asset/common/index.js.map +1 -1
  15. package/dist/esm/components/static-asset/common/keys.d.ts +1 -1
  16. package/dist/esm/components/static-asset/common/keys.js +1 -1
  17. package/dist/esm/components/static-asset/common/keys.js.map +1 -1
  18. package/dist/esm/components/static-asset/common/types.d.ts +189 -140
  19. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  20. package/dist/esm/components/static-asset/common/validation.d.ts +10 -0
  21. package/dist/esm/components/static-asset/common/validation.js +8 -0
  22. package/dist/esm/components/static-asset/common/validation.js.map +1 -0
  23. package/dist/esm/components/static-asset/component.d.ts +1 -1
  24. package/dist/esm/components/static-asset/component.js +13 -55
  25. package/dist/esm/components/static-asset/component.js.map +1 -1
  26. package/dist/esm/components/static-asset/controller/factory.d.ts +185 -67
  27. package/dist/esm/components/static-asset/controller/factory.js +32 -821
  28. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  29. package/dist/esm/components/static-asset/controller/routes/context.d.ts +61 -0
  30. package/dist/esm/components/static-asset/controller/routes/context.js +45 -0
  31. package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -0
  32. package/dist/esm/components/static-asset/controller/routes/definition.d.ts +40 -0
  33. package/dist/esm/components/static-asset/controller/routes/definition.js +74 -0
  34. package/dist/esm/components/static-asset/controller/routes/definition.js.map +1 -0
  35. package/dist/esm/components/static-asset/controller/routes/direct-upload.d.ts +3 -0
  36. package/dist/esm/components/static-asset/controller/routes/direct-upload.js +125 -0
  37. package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -0
  38. package/dist/esm/components/static-asset/controller/routes/labels.d.ts +16 -0
  39. package/dist/esm/components/static-asset/controller/routes/labels.js +19 -0
  40. package/dist/esm/components/static-asset/controller/routes/labels.js.map +1 -0
  41. package/dist/esm/components/static-asset/controller/routes/objects.d.ts +7 -0
  42. package/dist/esm/components/static-asset/controller/routes/objects.js +193 -0
  43. package/dist/esm/components/static-asset/controller/routes/objects.js.map +1 -0
  44. package/dist/esm/components/static-asset/controller/routes/serve.d.ts +17 -0
  45. package/dist/esm/components/static-asset/controller/routes/serve.js +127 -0
  46. package/dist/esm/components/static-asset/controller/routes/serve.js.map +1 -0
  47. package/dist/esm/components/static-asset/controller/routes/table.d.ts +12 -0
  48. package/dist/esm/components/static-asset/controller/routes/table.js +52 -0
  49. package/dist/esm/components/static-asset/controller/routes/table.js.map +1 -0
  50. package/dist/esm/components/static-asset/controller/routes/upload.d.ts +10 -0
  51. package/dist/esm/components/static-asset/controller/routes/upload.js +174 -0
  52. package/dist/esm/components/static-asset/controller/routes/upload.js.map +1 -0
  53. package/dist/esm/components/static-asset/models/base.model.d.ts +4 -4
  54. package/dist/esm/components/static-asset/models/base.model.js.map +1 -1
  55. package/dist/esm/components/static-asset/services/commitment.service.d.ts +41 -15
  56. package/dist/esm/components/static-asset/services/commitment.service.js +59 -29
  57. package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -1
  58. package/dist/esm/components/static-asset/services/policy.service.d.ts +7 -3
  59. package/dist/esm/components/static-asset/services/policy.service.js +27 -6
  60. package/dist/esm/components/static-asset/services/policy.service.js.map +1 -1
  61. package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +4 -1
  62. package/dist/esm/components/static-asset/utilities/commit-token.utility.js +33 -2
  63. package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -1
  64. package/dist/esm/components/static-asset/utilities/entry.utility.d.ts +69 -0
  65. package/dist/esm/components/static-asset/utilities/entry.utility.js +153 -0
  66. package/dist/esm/components/static-asset/utilities/entry.utility.js.map +1 -0
  67. package/dist/esm/components/static-asset/utilities/index.d.ts +2 -0
  68. package/dist/esm/components/static-asset/utilities/index.js +2 -0
  69. package/dist/esm/components/static-asset/utilities/index.js.map +1 -1
  70. package/dist/esm/components/static-asset/utilities/ingest.utility.js +2 -4
  71. package/dist/esm/components/static-asset/utilities/ingest.utility.js.map +1 -1
  72. package/dist/esm/components/static-asset/utilities/key-scope.utility.d.ts +6 -2
  73. package/dist/esm/components/static-asset/utilities/key-scope.utility.js +24 -6
  74. package/dist/esm/components/static-asset/utilities/key-scope.utility.js.map +1 -1
  75. package/dist/esm/components/static-asset/utilities/meta-link.utility.d.ts +2 -2
  76. package/dist/esm/components/static-asset/utilities/meta-link.utility.js +6 -6
  77. package/dist/esm/components/static-asset/utilities/meta-link.utility.js.map +1 -1
  78. package/dist/esm/components/static-asset/utilities/object-link.utility.d.ts +2 -2
  79. package/dist/esm/components/static-asset/utilities/object-link.utility.js +4 -5
  80. package/dist/esm/components/static-asset/utilities/object-link.utility.js.map +1 -1
  81. package/dist/esm/components/static-asset/utilities/route-options.utility.d.ts +20 -5
  82. package/dist/esm/components/static-asset/utilities/route-options.utility.js +44 -6
  83. package/dist/esm/components/static-asset/utilities/route-options.utility.js.map +1 -1
  84. package/dist/esm/components/static-asset/utilities/toggle.utility.d.ts +13 -0
  85. package/dist/esm/components/static-asset/utilities/toggle.utility.js +16 -0
  86. package/dist/esm/components/static-asset/utilities/toggle.utility.js.map +1 -0
  87. package/dist/presets/app/preset.json +4 -4
  88. package/dist/presets/lib/preset.json +3 -3
  89. package/dist/presets/shared/preset.json +1 -1
  90. package/package.json +6 -6
  91. package/dist/esm/components/static-asset/controller/base.definition.d.ts +0 -30
  92. package/dist/esm/components/static-asset/controller/base.definition.js +0 -307
  93. package/dist/esm/components/static-asset/controller/base.definition.js.map +0 -1
@@ -0,0 +1,174 @@
1
+ import { z } from '@hono/zod-openapi';
2
+ import { BaseStorageHelper, RequestUtility, } from '@venizia/ignis-helpers';
3
+ import { HTTP } from '@venizia/ignis-helpers/common';
4
+ import { getError } from '@venizia/ignis-helpers/core';
5
+ import { StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetRouteKeys, } from '../../common/index.js';
6
+ import { StaticAssetKeyScopeUtility } from '../../utilities/key-scope.utility.js';
7
+ import { StaticAssetMetaLinkUtility } from '../../utilities/meta-link.utility.js';
8
+ import { StaticAssetRouteOptionsUtility } from '../../utilities/route-options.utility.js';
9
+ import { StaticAssetFeatures, StaticAssetRouteUtility, } from './context.js';
10
+ import { StaticAssetDefinition } from './definition.js';
11
+ import { StaticAssetLabelsUtility, UploadLabelsSchema } from './labels.js';
12
+ import { MetaLinkRowSchema } from './objects.js';
13
+ const MultipartBodySchema = z.object({
14
+ files: z.union([z.instanceof(File), z.array(z.instanceof(File))]).openapi({
15
+ type: 'array',
16
+ items: { type: 'string', format: 'binary' },
17
+ }),
18
+ ...UploadLabelsSchema.shape,
19
+ folderPath: z.string().optional().openapi({
20
+ description: 'Target folder path for uploaded files (e.g., "photos/2024")',
21
+ example: 'photos/2024',
22
+ }),
23
+ });
24
+ /** What an upload or a commit says about the MetaLink row: the row, or a code when only the row failed. */
25
+ export const MetaLinkOutcomeSchema = z
26
+ .union([z.object({ data: MetaLinkRowSchema }), z.object({ error: z.string() })])
27
+ .optional();
28
+ class StaticAssetUploadHandler {
29
+ /**
30
+ * Built per request: the hook is offered the bucket, which only the route knows. A hook's key is
31
+ * checked against the scope, never rewritten: the application may record that key elsewhere.
32
+ */
33
+ static buildNaming(opts) {
34
+ const { env, bucketName, objectKey } = opts;
35
+ const { helper, keyPrefix } = env;
36
+ if (!objectKey && keyPrefix === undefined) {
37
+ return undefined;
38
+ }
39
+ return (naming) => {
40
+ // The component's own name under a scope: the original name must stay one segment, as without one.
41
+ if (!objectKey && !helper.isValidSegment({ segment: naming.file.originalName })) {
42
+ throw getError({ message: '[upload] Invalid original file name' });
43
+ }
44
+ const defaultKey = `${keyPrefix ?? ''}${BaseStorageHelper.normalizeObjectName(naming)}`;
45
+ const key = objectKey
46
+ ? objectKey({ bucket: { name: bucketName }, file: naming.file, defaultKey })
47
+ : defaultKey;
48
+ if (!StaticAssetKeyScopeUtility.isInScope({ key, keyPrefix })) {
49
+ throw getError({
50
+ error: StaticAssetErrors.OBJECT_KEY_OUT_OF_SCOPE,
51
+ message: `Object key is outside the key prefix of this entry | key: ${key} | keyPrefix: ${keyPrefix}`,
52
+ });
53
+ }
54
+ return key;
55
+ };
56
+ }
57
+ static async recordMetaLinks(opts) {
58
+ const { env, uploaded, labels } = opts;
59
+ const { helper, metaLink } = env;
60
+ if (!metaLink) {
61
+ return uploaded;
62
+ }
63
+ const results = [];
64
+ for (const uploadResult of uploaded) {
65
+ try {
66
+ const fileStat = await helper.getStat({
67
+ bucket: uploadResult.bucket,
68
+ object: uploadResult.object,
69
+ });
70
+ const data = await StaticAssetMetaLinkUtility.createRow({
71
+ metaLink,
72
+ helper,
73
+ storage: env.storage,
74
+ uploadResult,
75
+ fileStat,
76
+ labels,
77
+ });
78
+ results.push({ ...uploadResult, metaLink: { data } });
79
+ }
80
+ catch (error) {
81
+ env.logger
82
+ .for('UPLOAD')
83
+ .error('Failed to create MetaLink | objectName: %s | Error: %s', uploadResult.object.key, error);
84
+ // A CODE, never the driver text: this 200 bypasses the error middleware that strips
85
+ // `detail`/`table`/`constraint`. The real error is logged in full above.
86
+ results.push({
87
+ ...uploadResult,
88
+ metaLink: { error: StaticAssetMetaLinkCodes.CREATE_FAILED },
89
+ });
90
+ }
91
+ }
92
+ return results;
93
+ }
94
+ static async handle(opts) {
95
+ const { ctx, env } = opts;
96
+ const serverUpload = StaticAssetRouteUtility.requireFeature({
97
+ value: env.serverUpload,
98
+ feature: StaticAssetFeatures.SERVER_UPLOAD,
99
+ });
100
+ const { bucket } = await StaticAssetRouteUtility.resolveTarget({ ctx, env });
101
+ const { files, fields } = await RequestUtility.parseMultipartBody({
102
+ context: ctx,
103
+ maxFiles: serverUpload.maxFiles,
104
+ });
105
+ const labels = StaticAssetLabelsUtility.parse({ fields });
106
+ const folderPath = fields.folderPath || undefined;
107
+ const uploadFiles = files.map((file) => {
108
+ const { buffer } = file;
109
+ if (!buffer?.length) {
110
+ throw getError({
111
+ error: StaticAssetErrors.FILE_EMPTY,
112
+ message: `Empty file content | name: ${file.originalname}`,
113
+ });
114
+ }
115
+ // Authoritative: `buffer.length`, not the client-declared `size`.
116
+ if (serverUpload.maxBytes !== undefined && buffer.length > serverUpload.maxBytes) {
117
+ throw getError({
118
+ error: StaticAssetErrors.UPLOAD_TOO_LARGE,
119
+ message: `File ${file.originalname} of ${buffer.length} bytes exceeds the maximum of ${serverUpload.maxBytes}`,
120
+ });
121
+ }
122
+ return {
123
+ originalName: file.originalname,
124
+ mimetype: file.mimetype,
125
+ buffer,
126
+ size: file.size,
127
+ encoding: file.encoding,
128
+ folderPath,
129
+ };
130
+ });
131
+ const uploaded = await env.helper.upload({
132
+ bucket,
133
+ files: uploadFiles,
134
+ normalizeNameFn: StaticAssetUploadHandler.buildNaming({
135
+ env,
136
+ bucketName: bucket.name,
137
+ objectKey: serverUpload.objectKey,
138
+ }),
139
+ normalizeLinkFn: env.link,
140
+ // The storage checks the caller's folders against `maxFolderDepth`, and the finished key, scope included, against the deeper bound.
141
+ maxFolderDepth: env.maxFolderDepth,
142
+ maxKeyDepth: env.objectKeyMaxDepth,
143
+ });
144
+ const results = await StaticAssetUploadHandler.recordMetaLinks({ env, uploaded, labels });
145
+ return ctx.json(results, HTTP.ResultCodes.RS_2.Ok);
146
+ }
147
+ }
148
+ export const uploadRoute = {
149
+ key: StaticAssetRouteKeys.UPLOAD,
150
+ feature: StaticAssetFeatures.SERVER_UPLOAD,
151
+ build: (env) => ({
152
+ config: StaticAssetDefinition.multipart({
153
+ method: HTTP.Methods.POST,
154
+ path: '/objects',
155
+ body: MultipartBodySchema,
156
+ response: z.array(z.object({
157
+ bucket: z.object({ name: z.string() }),
158
+ object: z.object({ key: z.string(), size: z.number(), contentType: z.string() }),
159
+ link: z.string(),
160
+ metaLink: MetaLinkOutcomeSchema,
161
+ })),
162
+ }),
163
+ handler: (ctx) => StaticAssetUploadHandler.handle({ ctx, env }),
164
+ }),
165
+ // The route's body validator reads the whole multipart body, so the length check has to run before it.
166
+ middleware: ({ env, own }) => env.serverUpload?.maxBytes === undefined
167
+ ? own
168
+ : StaticAssetRouteOptionsUtility.appendLengthGuard({
169
+ middleware: own,
170
+ maxBytes: env.serverUpload.maxBytes,
171
+ maxFiles: env.serverUpload.maxFiles,
172
+ }),
173
+ };
174
+ //# sourceMappingURL=upload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.js","sourceRoot":"","sources":["../../../../../../src/components/static-asset/controller/routes/upload.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EACL,iBAAiB,EACjB,cAAc,GAIf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,oBAAoB,GAGrB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE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AAG,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;gBAChF,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;gBAChB,QAAQ,EAAE,qBAAqB;aAChC,CAAC,CACH;SACF,CAAC;QACF,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,wBAAwB,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;KAChE,CAAC;IACF,uGAAuG;IACvG,UAAU,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,CAC3B,GAAG,CAAC,YAAY,EAAE,QAAQ,KAAK,SAAS;QACtC,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,8BAA8B,CAAC,iBAAiB,CAAC;YAC/C,UAAU,EAAE,GAAG;YACf,QAAQ,EAAE,GAAG,CAAC,YAAY,CAAC,QAAQ;YACnC,QAAQ,EAAE,GAAG,CAAC,YAAY,CAAC,QAAQ;SACpC,CAAC;CACT,CAAC","sourcesContent":["import type { TRouteContext } from '@/base/controllers';\nimport { z } from '@hono/zod-openapi';\nimport {\n BaseStorageHelper,\n RequestUtility,\n type IUploadFile,\n type IUploadResult,\n type TUploadNaming,\n} from '@venizia/ignis-helpers';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n StaticAssetErrors,\n StaticAssetMetaLinkCodes,\n StaticAssetRouteKeys,\n type TStaticAssetObjectKeyResolver,\n type TStaticAssetUploadLabels,\n} from '../../common';\nimport { StaticAssetKeyScopeUtility } from '../../utilities/key-scope.utility';\nimport { StaticAssetMetaLinkUtility } from '../../utilities/meta-link.utility';\nimport { StaticAssetRouteOptionsUtility } from '../../utilities/route-options.utility';\nimport {\n type IStaticAssetRoute,\n type IStaticAssetRouteEnv,\n StaticAssetFeatures,\n StaticAssetRouteUtility,\n} from './context';\nimport { StaticAssetDefinition } from './definition';\nimport { StaticAssetLabelsUtility, UploadLabelsSchema } from './labels';\nimport { MetaLinkRowSchema } from './objects';\n\nconst MultipartBodySchema = z.object({\n files: z.union([z.instanceof(File), z.array(z.instanceof(File))]).openapi({\n type: 'array',\n items: { type: 'string', format: 'binary' },\n }),\n ...UploadLabelsSchema.shape,\n folderPath: z.string().optional().openapi({\n description: 'Target folder path for uploaded files (e.g., \"photos/2024\")',\n example: 'photos/2024',\n }),\n});\n\n/** What an upload or a commit says about the MetaLink row: the row, or a code when only the row failed. */\nexport const MetaLinkOutcomeSchema = z\n .union([z.object({ data: MetaLinkRowSchema }), z.object({ error: z.string() })])\n .optional();\n\nclass StaticAssetUploadHandler {\n /**\n * Built per request: the hook is offered the bucket, which only the route knows. A hook's key is\n * checked against the scope, never rewritten: the application may record that key elsewhere.\n */\n static buildNaming(opts: {\n env: IStaticAssetRouteEnv;\n bucketName: string;\n objectKey?: TStaticAssetObjectKeyResolver;\n }) {\n const { env, bucketName, objectKey } = opts;\n const { helper, keyPrefix } = env;\n\n if (!objectKey && keyPrefix === undefined) {\n return undefined;\n }\n\n return (naming: { file: TUploadNaming }) => {\n // The component's own name under a scope: the original name must stay one segment, as without one.\n if (!objectKey && !helper.isValidSegment({ segment: naming.file.originalName })) {\n throw getError({ message: '[upload] Invalid original file name' });\n }\n\n const defaultKey = `${keyPrefix ?? ''}${BaseStorageHelper.normalizeObjectName(naming)}`;\n const key = objectKey\n ? objectKey({ bucket: { name: bucketName }, file: naming.file, defaultKey })\n : defaultKey;\n\n if (!StaticAssetKeyScopeUtility.isInScope({ key, keyPrefix })) {\n throw getError({\n error: StaticAssetErrors.OBJECT_KEY_OUT_OF_SCOPE,\n message: `Object key is outside the key prefix of this entry | key: ${key} | keyPrefix: ${keyPrefix}`,\n });\n }\n\n return key;\n };\n }\n\n static async recordMetaLinks(opts: {\n env: IStaticAssetRouteEnv;\n uploaded: IUploadResult[];\n labels: TStaticAssetUploadLabels;\n }): Promise<IUploadResult[]> {\n const { env, uploaded, labels } = opts;\n const { helper, metaLink } = env;\n\n if (!metaLink) {\n return uploaded;\n }\n\n const results: IUploadResult[] = [];\n\n for (const uploadResult of uploaded) {\n try {\n const fileStat = await helper.getStat({\n bucket: uploadResult.bucket,\n object: uploadResult.object,\n });\n const data = await StaticAssetMetaLinkUtility.createRow({\n metaLink,\n helper,\n storage: env.storage,\n uploadResult,\n fileStat,\n labels,\n });\n\n results.push({ ...uploadResult, metaLink: { data } });\n } catch (error) {\n env.logger\n .for('UPLOAD')\n .error(\n 'Failed to create MetaLink | objectName: %s | Error: %s',\n uploadResult.object.key,\n error,\n );\n // A CODE, never the driver text: this 200 bypasses the error middleware that strips\n // `detail`/`table`/`constraint`. The real error is logged in full above.\n results.push({\n ...uploadResult,\n metaLink: { error: StaticAssetMetaLinkCodes.CREATE_FAILED },\n });\n }\n }\n\n return results;\n }\n\n static async handle(opts: { ctx: TRouteContext; env: IStaticAssetRouteEnv }) {\n const { ctx, env } = opts;\n const serverUpload = StaticAssetRouteUtility.requireFeature({\n value: env.serverUpload,\n feature: StaticAssetFeatures.SERVER_UPLOAD,\n });\n const { bucket } = await StaticAssetRouteUtility.resolveTarget({ ctx, env });\n\n const { files, fields } = await RequestUtility.parseMultipartBody({\n context: ctx,\n maxFiles: serverUpload.maxFiles,\n });\n const labels = StaticAssetLabelsUtility.parse({ fields });\n const folderPath = fields.folderPath || undefined;\n\n const uploadFiles: IUploadFile[] = files.map((file) => {\n const { buffer } = file;\n\n if (!buffer?.length) {\n throw getError({\n error: StaticAssetErrors.FILE_EMPTY,\n message: `Empty file content | name: ${file.originalname}`,\n });\n }\n\n // Authoritative: `buffer.length`, not the client-declared `size`.\n if (serverUpload.maxBytes !== undefined && buffer.length > serverUpload.maxBytes) {\n throw getError({\n error: StaticAssetErrors.UPLOAD_TOO_LARGE,\n message: `File ${file.originalname} of ${buffer.length} bytes exceeds the maximum of ${serverUpload.maxBytes}`,\n });\n }\n\n return {\n originalName: file.originalname,\n mimetype: file.mimetype,\n buffer,\n size: file.size,\n encoding: file.encoding,\n folderPath,\n };\n });\n\n const uploaded = await env.helper.upload({\n bucket,\n files: uploadFiles,\n normalizeNameFn: StaticAssetUploadHandler.buildNaming({\n env,\n bucketName: bucket.name,\n objectKey: serverUpload.objectKey,\n }),\n normalizeLinkFn: env.link,\n // The storage checks the caller's folders against `maxFolderDepth`, and the finished key, scope included, against the deeper bound.\n maxFolderDepth: env.maxFolderDepth,\n maxKeyDepth: env.objectKeyMaxDepth,\n });\n const results = await StaticAssetUploadHandler.recordMetaLinks({ env, uploaded, labels });\n\n return ctx.json(results, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n\nexport const uploadRoute: IStaticAssetRoute = {\n key: StaticAssetRouteKeys.UPLOAD,\n feature: StaticAssetFeatures.SERVER_UPLOAD,\n build: (env) => ({\n config: StaticAssetDefinition.multipart({\n method: HTTP.Methods.POST,\n path: '/objects',\n body: MultipartBodySchema,\n response: z.array(\n z.object({\n bucket: z.object({ name: z.string() }),\n object: z.object({ key: z.string(), size: z.number(), contentType: z.string() }),\n link: z.string(),\n metaLink: MetaLinkOutcomeSchema,\n }),\n ),\n }),\n handler: (ctx) => StaticAssetUploadHandler.handle({ ctx, env }),\n }),\n // The route's body validator reads the whole multipart body, so the length check has to run before it.\n middleware: ({ env, own }) =>\n env.serverUpload?.maxBytes === undefined\n ? own\n : StaticAssetRouteOptionsUtility.appendLengthGuard({\n middleware: own,\n maxBytes: env.serverUpload.maxBytes,\n maxFiles: env.serverUpload.maxFiles,\n }),\n};\n"]}
@@ -112,7 +112,7 @@ export declare class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseM
112
112
  tableName: "MetaLink";
113
113
  dataType: "json";
114
114
  columnType: "PgJsonb";
115
- data: Record<string, any>;
115
+ data: Record<string, unknown>;
116
116
  driverParam: unknown;
117
117
  notNull: false;
118
118
  hasDefault: false;
@@ -124,7 +124,7 @@ export declare class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseM
124
124
  identity: undefined;
125
125
  generated: undefined;
126
126
  }, {}, {
127
- $type: Record<string, any>;
127
+ $type: Record<string, unknown>;
128
128
  }>;
129
129
  storageType: import("drizzle-orm/pg-core").PgColumn<{
130
130
  name: "storage_type";
@@ -391,7 +391,7 @@ export declare class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseM
391
391
  tableName: "MetaLink";
392
392
  dataType: "json";
393
393
  columnType: "PgJsonb";
394
- data: Record<string, any>;
394
+ data: Record<string, unknown>;
395
395
  driverParam: unknown;
396
396
  notNull: false;
397
397
  hasDefault: false;
@@ -403,7 +403,7 @@ export declare class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseM
403
403
  identity: undefined;
404
404
  generated: undefined;
405
405
  }, {}, {
406
- $type: Record<string, any>;
406
+ $type: Record<string, unknown>;
407
407
  }>;
408
408
  storageType: import("drizzle-orm/pg-core").PgColumn<{
409
409
  name: "storage_type";
@@ -1 +1 @@
1
- {"version":3,"file":"base.model.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/models/base.model.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AACxC,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,GAGnB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAEpF,mNAAmN;AAE5M,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,oBAAqD;aAC1E,WAAM,GAAG,OAAO,CAC9B,UAAU,EACV;QACE,GAAG,kBAAkB,CAAC,kBAAkB,CAAC,EAAE,EAAE,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,CAAC;QACxE,GAAG,kBAAkB,CAAC,kBAAkB,EAAE;QAC1C,UAAU,EAAE,IAAI,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AEc,cAAS,GAAG,GAAG,EAAE,CAAC,EAAE,AAAX,CAAY;;AApC1B,iBAAiB;IAD7B,KAAK,CAAC,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC;GACxB,iBAAiB,CAqC7B","sourcesContent":["import { model } from '@/base/metadata';\nimport {\n BaseRelationalEntity,\n PostgresIdEnricher,\n PostgresTzEnricher,\n type TTableObject,\n type TTableSchemaWithId,\n} from '@venizia/ignis-connectors/postgres';\nimport { boolean, index, integer, jsonb, pgTable, text } from 'drizzle-orm/pg-core';\n\n/** One row per (object, owner) pairing, NOT per object: one product image attached to the product and to each variant is the common case, so `(bucketName, objectName)` is indexed and deliberately NOT unique. */\n@model({ migration: { use: false } })\nexport class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseMetaLinkModel.schema> {\n static override schema = pgTable(\n 'MetaLink',\n {\n ...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),\n ...PostgresTzEnricher.generateColumnDefs(),\n bucketName: text('bucket_name').notNull(),\n objectName: text('object_name').notNull(),\n link: text().notNull(),\n mimetype: text().notNull(),\n size: integer().notNull(),\n etag: text(),\n metadata: jsonb().$type<Record<string, any>>(),\n storageType: text('storage_type').notNull(),\n isSynced: boolean('is_synced').notNull().default(false),\n\n /** An opaque label the caller chooses - a size, a role, a rendition name. The component stores and returns it and reads no meaning into it. */\n variant: text(),\n\n /** Display order within ONE principal. Defaults to 0 so legacy rows tie and `ORDER BY sequence, createdAt` reproduces the order they already had. */\n sequence: integer().notNull().default(0),\n\n /** A polymorphic owner: the type names the table, the id the row. Both nullable - an object may belong to nothing yet, which is how `recreate-metalink` writes one. */\n principalType: text('principal_type'),\n principalId: text('principal_id'),\n },\n (def) => [\n index(`IDX_MetaLink_bucketName`).on(def.bucketName),\n index(`IDX_MetaLink_objectName`).on(def.objectName),\n index(`IDX_MetaLink_storageType`).on(def.storageType),\n index(`IDX_MetaLink_isSynced`).on(def.isSynced),\n // Ordering runs inside a principal filter, so filter columns lead and the sort column trails.\n index(`IDX_MetaLink_principal_sequence`).on(def.principalType, def.principalId, def.sequence),\n ],\n );\n\n static override relations = () => [];\n}\n\n/** The table schema of `BaseMetaLinkModel`. */\nexport type TMetaLinkSchema = typeof BaseMetaLinkModel.schema;\n/** A MetaLink row as selected from the table. */\nexport type TMetaLink = TTableObject<TMetaLinkSchema>;\n\n/** Any table whose row carries the MetaLink fields. The component reads and writes the ROW, so the table is free to carry another name or to live in another Postgres schema. */\nexport type TMetaLinkCompatibleSchema = TTableSchemaWithId & { $inferSelect: TMetaLink };\n"]}
1
+ {"version":3,"file":"base.model.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/models/base.model.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AACxC,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,GAGnB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAEpF,mNAAmN;AAE5M,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,oBAAqD;aAC1E,WAAM,GAAG,OAAO,CAC9B,UAAU,EACV;QACE,GAAG,kBAAkB,CAAC,kBAAkB,CAAC,EAAE,EAAE,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,CAAC;QACxE,GAAG,kBAAkB,CAAC,kBAAkB,EAAE;QAC1C,UAAU,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,OAAO,EAAE;QACzC,UAAU,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,OAAO,EAAE;QACzC,IAAI,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE;QACtB,QAAQ,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE;QAC1B,IAAI,EAAE,OAAO,EAAE,CAAC,OAAO,EA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gresTzEnricher,\n type TTableObject,\n type TTableSchemaWithId,\n} from '@venizia/ignis-connectors/postgres';\nimport { boolean, index, integer, jsonb, pgTable, text } from 'drizzle-orm/pg-core';\n\n/** One row per (object, owner) pairing, NOT per object: one product image attached to the product and to each variant is the common case, so `(bucketName, objectName)` is indexed and deliberately NOT unique. */\n@model({ migration: { use: false } })\nexport class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseMetaLinkModel.schema> {\n static override schema = pgTable(\n 'MetaLink',\n {\n ...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),\n ...PostgresTzEnricher.generateColumnDefs(),\n bucketName: text('bucket_name').notNull(),\n objectName: text('object_name').notNull(),\n link: text().notNull(),\n mimetype: text().notNull(),\n size: integer().notNull(),\n etag: text(),\n metadata: jsonb().$type<Record<string, unknown>>(),\n storageType: text('storage_type').notNull(),\n isSynced: boolean('is_synced').notNull().default(false),\n\n /** An opaque label the caller chooses - a size, a role, a rendition name. The component stores and returns it and reads no meaning into it. */\n variant: text(),\n\n /** Display order within ONE principal. Defaults to 0 so legacy rows tie and `ORDER BY sequence, createdAt` reproduces the order they already had. */\n sequence: integer().notNull().default(0),\n\n /** A polymorphic owner: the type names the table, the id the row. Both nullable - an object may belong to nothing yet, which is how `recreate-metalink` writes one. */\n principalType: text('principal_type'),\n principalId: text('principal_id'),\n },\n (def) => [\n index(`IDX_MetaLink_bucketName`).on(def.bucketName),\n index(`IDX_MetaLink_objectName`).on(def.objectName),\n index(`IDX_MetaLink_storageType`).on(def.storageType),\n index(`IDX_MetaLink_isSynced`).on(def.isSynced),\n // Ordering runs inside a principal filter, so filter columns lead and the sort column trails.\n index(`IDX_MetaLink_principal_sequence`).on(def.principalType, def.principalId, def.sequence),\n ],\n );\n\n static override relations = () => [];\n}\n\n/** The table schema of `BaseMetaLinkModel`. */\nexport type TMetaLinkSchema = typeof BaseMetaLinkModel.schema;\n/** A MetaLink row as selected from the table. */\nexport type TMetaLink = TTableObject<TMetaLinkSchema>;\n\n/** Any table whose row carries the MetaLink fields. The component reads and writes the ROW, so the table is free to carry another name or to live in another Postgres schema. */\nexport type TMetaLinkCompatibleSchema = TTableSchemaWithId & { $inferSelect: TMetaLink };\n"]}
@@ -1,6 +1,7 @@
1
- import type { IBucketRef, IObjectRef, IStorageHelper, IUploadResult } from '@venizia/ignis-helpers';
1
+ import type { z } from '@hono/zod-openapi';
2
+ import type { IBucketRef, IObjectLocation, IObjectRef, IStorageHelper, IUploadResult } from '@venizia/ignis-helpers';
2
3
  import { BaseService } from '@venizia/ignis-kernel';
3
- import type { TStaticAssetDirectUploadOptions, TMetaLinkConfig, TStaticAssetStorageType, TStaticAssetUploadQuery } from '../common/index.js';
4
+ import type { IStaticAssetValidation, IStaticAssetValidationResult, TStaticAssetDirectUploadOptions, TMetaLinkConfig, TStaticAssetStorageType, TStaticAssetUploadLabels } from '../common/index.js';
4
5
  import type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models/index.js';
5
6
  /** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */
6
7
  export interface IStaticAssetCommitResult {
@@ -14,34 +15,59 @@ export interface IStaticAssetUploadCommitServiceOptions<Schema extends TMetaLink
14
15
  /** Names the logger; the controller's own name is the usual value. */
15
16
  scope: string;
16
17
  helper: IStorageHelper;
17
- /** The controller's `keyPrefix` as configured; normalized here the way the controller does. */
18
- keyPrefix?: string;
19
- directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix' | 'onCommit'>;
18
+ /** The entry's `keyPrefix` as configured; normalized here the way the controller does. */
19
+ keyPrefix: string;
20
+ directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix'> & {
21
+ /** Absent, every file is valid. */
22
+ validation?: IStaticAssetValidation<z.ZodType>;
23
+ };
20
24
  storage: TStaticAssetStorageType;
21
- useMetaLink?: boolean;
22
25
  metaLink?: TMetaLinkConfig<Schema>;
23
- /** The controller mount path, the base of the link a commit returns. */
24
- basePath: string;
25
- rawObjectPath?: boolean;
26
+ /** The link a commit returns for the committed object: the entry's own, so a commit and an upload agree. */
27
+ link: (opts: IObjectLocation) => string;
26
28
  }
27
29
  /**
28
30
  * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,
29
31
  * callable without a request. A service that saves its own record commits the upload in the same
30
32
  * call instead of asking the client for a second request.
31
33
  *
32
- * The token proves the key was issued by a policy; it carries no owner. Whether the current caller
33
- * may commit that key is the application's decision, made before it calls `commit`.
34
+ * The token proves the key was issued by a policy. It names an owner only when
35
+ * `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who
36
+ * holds the token can.
34
37
  */
35
38
  export declare class StaticAssetUploadCommitService<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> extends BaseService {
36
39
  private readonly options;
37
- private readonly keyPrefix?;
40
+ private readonly keyPrefix;
38
41
  private readonly pendingPrefix;
39
- private readonly basePath;
40
42
  constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>);
43
+ /**
44
+ * Everything `commit` checks before it touches storage, and nothing else: the signature, the
45
+ * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and
46
+ * no side effect, so an application can read an uploaded file and report its problems to the user
47
+ * before anything is committed.
48
+ *
49
+ * A token this refuses is refused the same way `commit` refuses it, and every refusal says no more
50
+ * than that the token is no good: a caller learns nothing about which keys exist.
51
+ */
52
+ verify(opts: {
53
+ token: string;
54
+ owner?: string;
55
+ }): IObjectLocation;
56
+ /**
57
+ * `verify`, then the application's own check of the pending file. With no `validation` configured
58
+ * every file is valid. The issues are the application's, in the shape of its `issueSchema`.
59
+ */
60
+ validate(opts: {
61
+ token: string;
62
+ owner?: string;
63
+ }): Promise<IStaticAssetValidationResult<unknown>>;
64
+ private runValidation;
41
65
  /** Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the row. A MetaLink failure rides the result as a code: the object IS committed by then. */
42
66
  commit(opts: {
43
- commitToken: string;
44
- labels?: TStaticAssetUploadQuery;
67
+ token: string;
68
+ /** Who is committing. A token issued to an owner commits only for that owner. */
69
+ owner?: string;
70
+ labels?: TStaticAssetUploadLabels;
45
71
  }): Promise<IStaticAssetCommitResult>;
46
72
  }
47
73
  //# sourceMappingURL=commitment.service.d.ts.map
@@ -1,22 +1,22 @@
1
+ import { getError } from '@venizia/ignis-helpers/core';
1
2
  import { BaseService } from '@venizia/ignis-kernel';
2
- import { StaticAssetMetaLinkCodes } from '../common/index.js';
3
+ import { StaticAssetErrors, StaticAssetMetaLinkCodes } from '../common/index.js';
3
4
  import { StaticAssetCommitTokenUtility } from '../utilities/index.js';
4
5
  import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
5
6
  import { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility.js';
6
- import { StaticAssetObjectLinkUtility } from '../utilities/object-link.utility.js';
7
7
  /**
8
8
  * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,
9
9
  * callable without a request. A service that saves its own record commits the upload in the same
10
10
  * call instead of asking the client for a second request.
11
11
  *
12
- * The token proves the key was issued by a policy; it carries no owner. Whether the current caller
13
- * may commit that key is the application's decision, made before it calls `commit`.
12
+ * The token proves the key was issued by a policy. It names an owner only when
13
+ * `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who
14
+ * holds the token can.
14
15
  */
15
16
  export class StaticAssetUploadCommitService extends BaseService {
16
17
  constructor(opts) {
17
18
  super({ scope: opts.scope });
18
19
  this.options = opts;
19
- this.basePath = StaticAssetObjectLinkUtility.normalizeBasePath({ basePath: opts.basePath });
20
20
  const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({
21
21
  keyPrefix: opts.keyPrefix,
22
22
  pendingPrefix: opts.directUpload.pendingPrefix,
@@ -26,26 +26,62 @@ export class StaticAssetUploadCommitService extends BaseService {
26
26
  this.keyPrefix = prefixes.keyPrefix;
27
27
  this.pendingPrefix = prefixes.pendingPrefix;
28
28
  }
29
+ /**
30
+ * Everything `commit` checks before it touches storage, and nothing else: the signature, the
31
+ * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and
32
+ * no side effect, so an application can read an uploaded file and report its problems to the user
33
+ * before anything is committed.
34
+ *
35
+ * A token this refuses is refused the same way `commit` refuses it, and every refusal says no more
36
+ * than that the token is no good: a caller learns nothing about which keys exist.
37
+ */
38
+ verify(opts) {
39
+ const payload = StaticAssetCommitTokenUtility.read({
40
+ token: opts.token,
41
+ secretKey: this.options.directUpload.secretKey,
42
+ });
43
+ // The same error as a forged token: a caller learns only that the token is no good for them.
44
+ if (payload.owner !== undefined && payload.owner !== opts.owner) {
45
+ throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
46
+ }
47
+ // A token another controller signed with the same secret must not land outside this scope.
48
+ StaticAssetKeyScopeUtility.assertInScope({
49
+ key: payload.object.key.slice(this.pendingPrefix.length),
50
+ keyPrefix: this.keyPrefix,
51
+ });
52
+ return { bucket: payload.bucket, object: payload.object };
53
+ }
54
+ /**
55
+ * `verify`, then the application's own check of the pending file. With no `validation` configured
56
+ * every file is valid. The issues are the application's, in the shape of its `issueSchema`.
57
+ */
58
+ async validate(opts) {
59
+ const pending = this.verify({ token: opts.token, owner: opts.owner });
60
+ return this.runValidation({ pending, owner: opts.owner });
61
+ }
62
+ async runValidation(opts) {
63
+ const { helper, directUpload } = this.options;
64
+ if (!directUpload.validation) {
65
+ return { isValid: true, issues: [] };
66
+ }
67
+ return directUpload.validation.handler({ ...opts.pending, owner: opts.owner, helper });
68
+ }
29
69
  /** Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the row. A MetaLink failure rides the result as a code: the object IS committed by then. */
30
70
  async commit(opts) {
31
- const { helper, directUpload, storage, useMetaLink, metaLink } = this.options;
71
+ const { helper, storage, metaLink, link: buildLink } = this.options;
32
72
  // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged
33
73
  // token fails without a round trip, so timing says nothing.
34
- const payload = StaticAssetCommitTokenUtility.read({
35
- token: opts.commitToken,
36
- secretKey: directUpload.secretKey,
37
- });
74
+ const pending = this.verify({ token: opts.token, owner: opts.owner });
75
+ const { bucket: bucketRef, object: pendingObject } = pending;
76
+ // An invalid file never leaves the pending prefix: this runs before the copy.
77
+ const validation = await this.runValidation({ pending, owner: opts.owner });
78
+ if (!validation.isValid) {
79
+ throw getError(StaticAssetErrors.UPLOAD_INVALID);
80
+ }
38
81
  // Labels, not authorization - the token deliberately carries no business fields, so they travel
39
82
  // beside it rather than inside it.
40
- const query = opts.labels ?? {};
41
- const bucketRef = { name: payload.bucket };
42
- const pendingObject = { key: payload.key };
43
- const object = { key: payload.key.slice(this.pendingPrefix.length) };
44
- // A token another controller signed with the same secret must not land outside this scope.
45
- StaticAssetKeyScopeUtility.assertInScope({ key: object.key, keyPrefix: this.keyPrefix });
46
- // Before the copy, so a hook that throws leaves the object under the pending prefix
47
- // for a lifecycle rule, rather than stranding it at the final key.
48
- await directUpload.onCommit?.({ bucket: bucketRef, pendingObject, object });
83
+ const labels = opts.labels ?? {};
84
+ const object = { key: pendingObject.key.slice(this.pendingPrefix.length) };
49
85
  await helper.copyObject({
50
86
  bucket: bucketRef,
51
87
  source: pendingObject,
@@ -62,17 +98,11 @@ export class StaticAssetUploadCommitService extends BaseService {
62
98
  .for('UPLOAD_COMMIT')
63
99
  .warn('Committed, but the pending object remains | key: %s | error: %s', pendingObject.key, error);
64
100
  }
65
- const link = StaticAssetObjectLinkUtility.build({
66
- basePath: this.basePath,
67
- bucket: bucketRef,
68
- object,
69
- hasConfiguredBucket: true,
70
- rawObjectPath: this.options.rawObjectPath,
71
- });
101
+ const link = buildLink({ bucket: bucketRef, object });
72
102
  // The two paths have to agree: without this a client reading `metaLink` off the
73
103
  // response renders an empty state with no error - the failure nobody reports.
74
104
  let metaLinkResult;
75
- if (useMetaLink && metaLink) {
105
+ if (metaLink) {
76
106
  try {
77
107
  const fileStat = await helper.getStat({ bucket: bucketRef, object });
78
108
  const data = await StaticAssetMetaLinkUtility.createRow({
@@ -87,7 +117,7 @@ export class StaticAssetUploadCommitService extends BaseService {
87
117
  fileStat,
88
118
  }),
89
119
  fileStat,
90
- query,
120
+ labels,
91
121
  });
92
122
  metaLinkResult = { data };
93
123
  }
@@ -104,7 +134,7 @@ export class StaticAssetUploadCommitService extends BaseService {
104
134
  bucket: bucketRef,
105
135
  object,
106
136
  link,
107
- ...(metaLinkResult === undefined ? {} : { metaLink: metaLinkResult }),
137
+ metaLink: metaLinkResult,
108
138
  };
109
139
  }
110
140
  }
@@ -1 +1 @@
1
- {"version":3,"file":"commitment.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/commitment.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAO7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,4BAA4B,EAAE,MAAM,kCAAkC,CAAC;AA6BhF;;;;;;;GAOG;AACH,MAAM,OAAO,8BAEX,SAAQ,WAAW;IAMnB,YAAY,IAAoD;QAC9D,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE7B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,QAAQ,GAAG,4BAA4B,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;QAE5F,MAAM,QAAQ,GAAG,0BAA0B,CAAC,2BAA2B,CAAC;YACtE,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,aAAa,EAAE,IAAI,CAAC,YAAY,CAAC,aAAa;YAC9C,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,C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ACR,GAAG,CAAC,eAAe,CAAC;qBACpB,KAAK,CAAC,wDAAwD,EAAE,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;gBACtF,cAAc,GAAG,EAAE,KAAK,EAAE,wBAAwB,CAAC,aAAa,EAAE,CAAC;YACrE,CAAC;QACH,CAAC;QAED,OAAO;YACL,MAAM,EAAE,SAAS;YACjB,MAAM;YACN,IAAI;YACJ,GAAG,CAAC,cAAc,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC;SACtE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { IBucketRef, IObjectRef, IStorageHelper, IUploadResult } from '@venizia/ignis-helpers';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport { StaticAssetMetaLinkCodes } from '../common';\nimport { StaticAssetCommitTokenUtility } from '../utilities';\nimport type {\n TStaticAssetDirectUploadOptions,\n TMetaLinkConfig,\n TStaticAssetStorageType,\n TStaticAssetUploadQuery,\n} from '../common';\nimport { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility';\nimport { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility';\nimport { StaticAssetObjectLinkUtility } from '../utilities/object-link.utility';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\n\n/** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */\nexport interface IStaticAssetCommitResult {\n bucket: IBucketRef;\n object: IObjectRef;\n link: string;\n metaLink?: IUploadResult['metaLink'];\n}\n\n/** `Schema` is the MetaLink table the application bound, the same type parameter the component carries. */\nexport interface IStaticAssetUploadCommitServiceOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> {\n /** Names the logger; the controller's own name is the usual value. */\n scope: string;\n helper: IStorageHelper;\n /** The controller's `keyPrefix` as configured; normalized here the way the controller does. */\n keyPrefix?: string;\n directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix' | 'onCommit'>;\n storage: TStaticAssetStorageType;\n useMetaLink?: boolean;\n metaLink?: TMetaLinkConfig<Schema>;\n /** The controller mount path, the base of the link a commit returns. */\n basePath: string;\n rawObjectPath?: boolean;\n}\n\n/**\n * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,\n * callable without a request. A service that saves its own record commits the upload in the same\n * call instead of asking the client for a second request.\n *\n * The token proves the key was issued by a policy; it carries no owner. Whether the current caller\n * may commit that key is the application's decision, made before it calls `commit`.\n */\nexport class StaticAssetUploadCommitService<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> extends BaseService {\n private readonly options: IStaticAssetUploadCommitServiceOptions<Schema>;\n private readonly keyPrefix?: string;\n private readonly pendingPrefix: string;\n private readonly basePath: string;\n\n constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>) {\n super({ scope: opts.scope });\n\n this.options = opts;\n this.basePath = StaticAssetObjectLinkUtility.normalizeBasePath({ basePath: opts.basePath });\n\n const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({\n keyPrefix: opts.keyPrefix,\n pendingPrefix: opts.directUpload.pendingPrefix,\n helper: opts.helper,\n scope: opts.scope,\n });\n this.keyPrefix = prefixes.keyPrefix;\n this.pendingPrefix = prefixes.pendingPrefix;\n }\n\n /** Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the row. A MetaLink failure rides the result as a code: the object IS committed by then. */\n async commit(opts: {\n commitToken: string;\n labels?: TStaticAssetUploadQuery;\n }): Promise<IStaticAssetCommitResult> {\n const { helper, directUpload, storage, useMetaLink, metaLink } = this.options;\n\n // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged\n // token fails without a round trip, so timing says nothing.\n const payload = StaticAssetCommitTokenUtility.read({\n token: opts.commitToken,\n secretKey: directUpload.secretKey,\n });\n\n // Labels, not authorization - the token deliberately carries no business fields, so they travel\n // beside it rather than inside it.\n const query = opts.labels ?? {};\n\n const bucketRef = { name: payload.bucket };\n const pendingObject = { key: payload.key };\n const object = { key: payload.key.slice(this.pendingPrefix.length) };\n\n // A token another controller signed with the same secret must not land outside this scope.\n StaticAssetKeyScopeUtility.assertInScope({ key: object.key, keyPrefix: this.keyPrefix });\n\n // Before the copy, so a hook that throws leaves the object under the pending prefix\n // for a lifecycle rule, rather than stranding it at the final key.\n await directUpload.onCommit?.({ bucket: bucketRef, pendingObject, object });\n\n await helper.copyObject({\n bucket: bucketRef,\n source: pendingObject,\n destination: object,\n });\n\n // The copy IS the commit; removing the temporary object is cleanup. A failure here\n // leaves one object for the lifecycle rule, and failing the request would tell the\n // caller their upload did not work when it did.\n try {\n await helper.removeObject({ bucket: bucketRef, object: pendingObject });\n } catch (error) {\n this.logger\n .for('UPLOAD_COMMIT')\n .warn(\n 'Committed, but the pending object remains | key: %s | error: %s',\n pendingObject.key,\n error,\n );\n }\n\n const link = StaticAssetObjectLinkUtility.build({\n basePath: this.basePath,\n bucket: bucketRef,\n object,\n hasConfiguredBucket: true,\n rawObjectPath: this.options.rawObjectPath,\n });\n\n // The two paths have to agree: without this a client reading `metaLink` off the\n // response renders an empty state with no error - the failure nobody reports.\n let metaLinkResult: IUploadResult['metaLink'];\n\n if (useMetaLink && metaLink) {\n try {\n const fileStat = await helper.getStat({ bucket: bucketRef, object });\n const data = await StaticAssetMetaLinkUtility.createRow({\n metaLink,\n helper,\n storage,\n uploadResult: StaticAssetMetaLinkUtility.buildStoredUploadResult({\n helper,\n bucket: bucketRef,\n object,\n link,\n fileStat,\n }),\n fileStat,\n query,\n });\n\n metaLinkResult = { data };\n } catch (error) {\n // The object IS committed by now. A 500 would send the caller back with a token\n // whose source no longer exists, so this rides the body as a code, like UPLOAD.\n this.logger\n .for('UPLOAD_COMMIT')\n .error('Failed to create MetaLink | objectName: %s | Error: %s', object.key, error);\n metaLinkResult = { error: StaticAssetMetaLinkCodes.CREATE_FAILED };\n }\n }\n\n return {\n bucket: bucketRef,\n object,\n link,\n ...(metaLinkResult === undefined ? {} : { metaLink: metaLinkResult }),\n };\n }\n}\n"]}
1
+ {"version":3,"file":"commitment.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/commitment.service.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAS7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AA8B5E;;;;;;;;GAQG;AACH,MAAM,OAAO,8BAEX,SAAQ,WAAW;IAKnB,YAAY,IAAoD;QAC9D,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE7B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QAEpB,MAAM,QAAQ,GAAG,0BAA0B,CAAC,2BAA2B,CAAC;YACtE,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,aAAa,EAAE,IAAI,CAAC,YAAY,CAAC,aAAa;YAC9C,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC;IAC9C,CAAC;IAED;;;;;;;;OAQG;IACH,MAAM,CAAC,IAAuC;QAC5C,MAAM,OAAO,GAAG,6BAA6B,CAAC,IAAI,CAAC;YACjD,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,SAAS;SAC/C,CAAC,CAAC;QAEH,6FAA6F;QAC7F,IAAI,OA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H,iEAAiE,EACjE,aAAa,CAAC,GAAG,EACjB,KAAK,CACN,CAAC;QACN,CAAC;QAED,MAAM,IAAI,GAAG,SAAS,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;QAEtD,gFAAgF;QAChF,8EAA8E;QAC9E,IAAI,cAAyC,CAAC;QAE9C,IAAI,QAAQ,EAAE,CAAC;YACb,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;gBACrE,MAAM,IAAI,GAAG,MAAM,0BAA0B,CAAC,SAAS,CAAC;oBACtD,QAAQ;oBACR,MAAM;oBACN,OAAO;oBACP,YAAY,EAAE,0BAA0B,CAAC,uBAAuB,CAAC;wBAC/D,MAAM;wBACN,MAAM,EAAE,SAAS;wBACjB,MAAM;wBACN,IAAI;wBACJ,QAAQ;qBACT,CAAC;oBACF,QAAQ;oBACR,MAAM;iBACP,CAAC,CAAC;gBAEH,cAAc,GAAG,EAAE,IAAI,EAAE,CAAC;YAC5B,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,gFAAgF;gBAChF,gFAAgF;gBAChF,IAAI,CAAC,MAAM;qBACR,GAAG,CAAC,eAAe,CAAC;qBACpB,KAAK,CAAC,wDAAwD,EAAE,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;gBACtF,cAAc,GAAG,EAAE,KAAK,EAAE,wBAAwB,CAAC,aAAa,EAAE,CAAC;YACrE,CAAC;QACH,CAAC;QAED,OAAO;YACL,MAAM,EAAE,SAAS;YACjB,MAAM;YACN,IAAI;YACJ,QAAQ,EAAE,cAAc;SACzB,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { z } from '@hono/zod-openapi';\nimport type {\n IBucketRef,\n IObjectLocation,\n IObjectRef,\n IStorageHelper,\n IUploadResult,\n} from '@venizia/ignis-helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport { StaticAssetErrors, StaticAssetMetaLinkCodes } from '../common';\nimport { StaticAssetCommitTokenUtility } from '../utilities';\nimport type {\n IStaticAssetValidation,\n IStaticAssetValidationResult,\n TStaticAssetDirectUploadOptions,\n TMetaLinkConfig,\n TStaticAssetStorageType,\n TStaticAssetUploadLabels,\n} from '../common';\nimport { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility';\nimport { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\n\n/** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */\nexport interface IStaticAssetCommitResult {\n bucket: IBucketRef;\n object: IObjectRef;\n link: string;\n metaLink?: IUploadResult['metaLink'];\n}\n\n/** `Schema` is the MetaLink table the application bound, the same type parameter the component carries. */\nexport interface IStaticAssetUploadCommitServiceOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> {\n /** Names the logger; the controller's own name is the usual value. */\n scope: string;\n helper: IStorageHelper;\n /** The entry's `keyPrefix` as configured; normalized here the way the controller does. */\n keyPrefix: string;\n directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix'> & {\n /** Absent, every file is valid. */\n validation?: IStaticAssetValidation<z.ZodType>;\n };\n storage: TStaticAssetStorageType;\n metaLink?: TMetaLinkConfig<Schema>;\n /** The link a commit returns for the committed object: the entry's own, so a commit and an upload agree. */\n link: (opts: IObjectLocation) => string;\n}\n\n/**\n * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,\n * callable without a request. A service that saves its own record commits the upload in the same\n * call instead of asking the client for a second request.\n *\n * The token proves the key was issued by a policy. It names an owner only when\n * `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who\n * holds the token can.\n */\nexport class StaticAssetUploadCommitService<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> extends BaseService {\n private readonly options: IStaticAssetUploadCommitServiceOptions<Schema>;\n private readonly keyPrefix: string;\n private readonly pendingPrefix: string;\n\n constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>) {\n super({ scope: opts.scope });\n\n this.options = opts;\n\n const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({\n keyPrefix: opts.keyPrefix,\n pendingPrefix: opts.directUpload.pendingPrefix,\n helper: opts.helper,\n scope: opts.scope,\n });\n this.keyPrefix = prefixes.keyPrefix;\n this.pendingPrefix = prefixes.pendingPrefix;\n }\n\n /**\n * Everything `commit` checks before it touches storage, and nothing else: the signature, the\n * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and\n * no side effect, so an application can read an uploaded file and report its problems to the user\n * before anything is committed.\n *\n * A token this refuses is refused the same way `commit` refuses it, and every refusal says no more\n * than that the token is no good: a caller learns nothing about which keys exist.\n */\n verify(opts: { token: string; owner?: string }): IObjectLocation {\n const payload = StaticAssetCommitTokenUtility.read({\n token: opts.token,\n secretKey: this.options.directUpload.secretKey,\n });\n\n // The same error as a forged token: a caller learns only that the token is no good for them.\n if (payload.owner !== undefined && payload.owner !== opts.owner) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n // A token another controller signed with the same secret must not land outside this scope.\n StaticAssetKeyScopeUtility.assertInScope({\n key: payload.object.key.slice(this.pendingPrefix.length),\n keyPrefix: this.keyPrefix,\n });\n\n return { bucket: payload.bucket, object: payload.object };\n }\n\n /**\n * `verify`, then the application's own check of the pending file. With no `validation` configured\n * every file is valid. The issues are the application's, in the shape of its `issueSchema`.\n */\n async validate(opts: {\n token: string;\n owner?: string;\n }): Promise<IStaticAssetValidationResult<unknown>> {\n const pending = this.verify({ token: opts.token, owner: opts.owner });\n\n return this.runValidation({ pending, owner: opts.owner });\n }\n\n private async runValidation(opts: {\n pending: IObjectLocation;\n owner?: string;\n }): Promise<IStaticAssetValidationResult<unknown>> {\n const { helper, directUpload } = this.options;\n\n if (!directUpload.validation) {\n return { isValid: true, issues: [] };\n }\n\n return directUpload.validation.handler({ ...opts.pending, owner: opts.owner, helper });\n }\n\n /** Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the row. A MetaLink failure rides the result as a code: the object IS committed by then. */\n async commit(opts: {\n token: string;\n /** Who is committing. A token issued to an owner commits only for that owner. */\n owner?: string;\n labels?: TStaticAssetUploadLabels;\n }): Promise<IStaticAssetCommitResult> {\n const { helper, storage, metaLink, link: buildLink } = this.options;\n\n // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged\n // token fails without a round trip, so timing says nothing.\n const pending = this.verify({ token: opts.token, owner: opts.owner });\n const { bucket: bucketRef, object: pendingObject } = pending;\n\n // An invalid file never leaves the pending prefix: this runs before the copy.\n const validation = await this.runValidation({ pending, owner: opts.owner });\n\n if (!validation.isValid) {\n throw getError(StaticAssetErrors.UPLOAD_INVALID);\n }\n\n // Labels, not authorization - the token deliberately carries no business fields, so they travel\n // beside it rather than inside it.\n const labels = opts.labels ?? {};\n\n const object = { key: pendingObject.key.slice(this.pendingPrefix.length) };\n\n await helper.copyObject({\n bucket: bucketRef,\n source: pendingObject,\n destination: object,\n });\n\n // The copy IS the commit; removing the temporary object is cleanup. A failure here\n // leaves one object for the lifecycle rule, and failing the request would tell the\n // caller their upload did not work when it did.\n try {\n await helper.removeObject({ bucket: bucketRef, object: pendingObject });\n } catch (error) {\n this.logger\n .for('UPLOAD_COMMIT')\n .warn(\n 'Committed, but the pending object remains | key: %s | error: %s',\n pendingObject.key,\n error,\n );\n }\n\n const link = buildLink({ bucket: bucketRef, object });\n\n // The two paths have to agree: without this a client reading `metaLink` off the\n // response renders an empty state with no error - the failure nobody reports.\n let metaLinkResult: IUploadResult['metaLink'];\n\n if (metaLink) {\n try {\n const fileStat = await helper.getStat({ bucket: bucketRef, object });\n const data = await StaticAssetMetaLinkUtility.createRow({\n metaLink,\n helper,\n storage,\n uploadResult: StaticAssetMetaLinkUtility.buildStoredUploadResult({\n helper,\n bucket: bucketRef,\n object,\n link,\n fileStat,\n }),\n fileStat,\n labels,\n });\n\n metaLinkResult = { data };\n } catch (error) {\n // The object IS committed by now. A 500 would send the caller back with a token\n // whose source no longer exists, so this rides the body as a code, like UPLOAD.\n this.logger\n .for('UPLOAD_COMMIT')\n .error('Failed to create MetaLink | objectName: %s | Error: %s', object.key, error);\n metaLinkResult = { error: StaticAssetMetaLinkCodes.CREATE_FAILED };\n }\n }\n\n return {\n bucket: bucketRef,\n object,\n link,\n metaLink: metaLinkResult,\n };\n }\n}\n"]}
@@ -14,9 +14,9 @@ export interface IStaticAssetUploadPolicyServiceOptions {
14
14
  helper: IStorageHelper;
15
15
  /** A policy names ONE bucket, so a direct upload has no bucket in its URL. */
16
16
  bucket: TValueOrAsyncResolver<string>;
17
- /** The controller's `keyPrefix` as configured; normalized here the way the controller does. */
18
- keyPrefix?: string;
19
- directUpload: Pick<TStaticAssetDirectUploadOptions, 'maxBytes' | 'expiresIn' | 'secretKey' | 'pendingPrefix'>;
17
+ /** The entry's `keyPrefix` as configured; normalized here the way the controller does. Required: it keeps the pending prefix out of everything the routes serve. */
18
+ keyPrefix: string;
19
+ directUpload: Pick<TStaticAssetDirectUploadOptions, 'maxBytes' | 'expires' | 'secretKey' | 'pendingPrefix'>;
20
20
  }
21
21
  /**
22
22
  * Signs the permission for a browser to post bytes straight to storage: the body of the
@@ -28,10 +28,14 @@ export interface IStaticAssetUploadPolicyServiceOptions {
28
28
  export declare class StaticAssetUploadPolicyService extends BaseService {
29
29
  private readonly options;
30
30
  private readonly policyKeyPrefix;
31
+ private readonly commitLifetimeMs?;
31
32
  constructor(opts: IStaticAssetUploadPolicyServiceOptions);
33
+ /** `undefined` when `expires.commit` is not set: the token then dies with the policy. */
34
+ private static resolveCommitLifetimeMs;
32
35
  /** One signed policy per file. A size over `maxBytes` is refused before any policy is signed. */
33
36
  issuePolicies(opts: {
34
37
  files: TStaticAssetUploadPolicyRequest['files'];
38
+ owner?: string;
35
39
  }): Promise<TStaticAssetUploadPolicy[]>;
36
40
  }
37
41
  //# sourceMappingURL=policy.service.d.ts.map