ocel 0.0.0 → 0.0.1-alpha.1

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 (74) hide show
  1. package/bin/run.js +39 -0
  2. package/dist/blob/bucket.d.ts +55 -0
  3. package/dist/blob/bucket.js +65 -0
  4. package/dist/blob/index.d.ts +8 -0
  5. package/dist/blob/index.js +13 -0
  6. package/dist/blob/integrations/client.d.ts +25 -0
  7. package/dist/blob/integrations/client.js +71 -0
  8. package/dist/blob/integrations/hono.d.ts +31 -0
  9. package/dist/blob/integrations/hono.js +11 -0
  10. package/dist/blob/mime-types.d.ts +1 -0
  11. package/dist/blob/mime-types.js +1 -0
  12. package/dist/blob/parse.d.ts +16 -0
  13. package/dist/blob/parse.js +69 -0
  14. package/dist/blob/s3-listener.d.ts +7 -0
  15. package/dist/blob/s3-listener.js +35 -0
  16. package/dist/blob/types.d.ts +128 -0
  17. package/dist/blob/types.js +1 -0
  18. package/dist/blob/upload-error.d.ts +35 -0
  19. package/dist/blob/upload-error.js +54 -0
  20. package/dist/blob/uploader.d.ts +67 -0
  21. package/dist/blob/uploader.js +323 -0
  22. package/dist/internal/db/index.d.ts +68 -0
  23. package/dist/internal/db/index.js +73 -0
  24. package/dist/lambda/index.d.ts +2 -0
  25. package/dist/lambda/index.js +4 -0
  26. package/dist/lambda/integrations/express.d.ts +3 -0
  27. package/dist/lambda/integrations/express.js +13 -0
  28. package/dist/lambda/integrations/hono.d.ts +3 -0
  29. package/dist/lambda/integrations/hono.js +13 -0
  30. package/dist/lambda/lambda.d.ts +43 -0
  31. package/dist/lambda/lambda.js +30 -0
  32. package/dist/postgres/index.d.ts +2 -0
  33. package/dist/postgres/index.js +4 -0
  34. package/dist/postgres/pg.d.ts +11 -0
  35. package/dist/postgres/pg.js +24 -0
  36. package/dist/utils/component.d.ts +3 -0
  37. package/dist/utils/component.js +1 -0
  38. package/dist/utils/constants.d.ts +2 -0
  39. package/dist/utils/constants.js +2 -0
  40. package/dist/utils/nanoid.d.ts +1 -0
  41. package/dist/utils/nanoid.js +6 -0
  42. package/dist/utils/rpc.d.ts +11 -0
  43. package/dist/utils/rpc.js +17 -0
  44. package/dist/utils/stack.d.ts +4 -0
  45. package/dist/utils/stack.js +23 -0
  46. package/dist/workflow/index.d.ts +3 -0
  47. package/dist/workflow/index.js +4 -0
  48. package/dist/workflow/workflow.d.ts +34 -0
  49. package/dist/workflow/workflow.js +146 -0
  50. package/package.json +93 -8
  51. package/src/blob/bucket.ts +92 -0
  52. package/src/blob/index.ts +34 -0
  53. package/src/blob/integrations/client.ts +127 -0
  54. package/src/blob/integrations/hono.ts +16 -0
  55. package/src/blob/mime-types.ts +68 -0
  56. package/src/blob/parse.ts +93 -0
  57. package/src/blob/s3-listener.ts +48 -0
  58. package/src/blob/types.ts +142 -0
  59. package/src/blob/upload-error.ts +67 -0
  60. package/src/blob/uploader.ts +426 -0
  61. package/src/internal/db/index.ts +78 -0
  62. package/src/lambda/index.ts +8 -0
  63. package/src/lambda/integrations/express.ts +25 -0
  64. package/src/lambda/integrations/hono.ts +25 -0
  65. package/src/lambda/lambda.ts +94 -0
  66. package/src/postgres/index.ts +5 -0
  67. package/src/postgres/pg.ts +33 -0
  68. package/src/utils/component.ts +3 -0
  69. package/src/utils/constants.ts +2 -0
  70. package/src/utils/nanoid.ts +9 -0
  71. package/src/utils/rpc.ts +28 -0
  72. package/src/utils/stack.ts +26 -0
  73. package/src/workflow/index.ts +9 -0
  74. package/src/workflow/workflow.ts +235 -0
@@ -0,0 +1,127 @@
1
+ import type z from "zod";
2
+ import type { Bucket } from "../bucket";
3
+ import type { PresignUploadBody, PresignUploadResponse } from "../types";
4
+
5
+ type PollResponse = {
6
+ files: Array<{
7
+ fileKey: string;
8
+ status: "PENDING" | "SUCCESS" | "FAILED";
9
+ file?: { path: string; contentDisposition: string; contentType: string };
10
+ metadata?: unknown;
11
+ }>;
12
+ completed: boolean;
13
+ };
14
+
15
+ type InferReturn<TRouter, K extends keyof TRouter> = TRouter[K] extends {
16
+ _def: { output: infer R };
17
+ }
18
+ ? R
19
+ : never;
20
+
21
+ type InferInput<TRouter, K extends keyof TRouter> = TRouter[K] extends {
22
+ _def: { input: infer R };
23
+ }
24
+ ? R
25
+ : never;
26
+
27
+ export function createUploadClient<TBucket extends Bucket<any>>(opts: {
28
+ url: string;
29
+ }) {
30
+ return {
31
+ upload: async <K extends keyof TBucket["_shape"]>(
32
+ uploader: K,
33
+ args: InferInput<TBucket["_shape"], K> extends never
34
+ ? {
35
+ files: File[];
36
+ onClientUploadComplete?: (
37
+ res: InferReturn<TBucket["_shape"], K>,
38
+ ) => void;
39
+ }
40
+ : {
41
+ files: File[];
42
+ input: z.infer<InferInput<TBucket["_shape"], K>>;
43
+ onClientUploadComplete?: (
44
+ res: InferReturn<TBucket["_shape"], K>,
45
+ ) => void;
46
+ },
47
+ ) => {
48
+ const url = opts.url;
49
+ const searchParams = new URLSearchParams();
50
+ searchParams.append("action", "presign");
51
+ searchParams.append("uploader", String(uploader));
52
+
53
+ // get presign urls
54
+ const result = (await fetch(`${url}?${searchParams.toString()}`, {
55
+ method: "POST",
56
+ headers: {
57
+ "Content-Type": "application/json",
58
+ },
59
+ body: JSON.stringify({
60
+ files: args.files.map((f) => {
61
+ return {
62
+ name: f.name,
63
+ size: f.size,
64
+ type: f.type,
65
+ lastModified: f.lastModified,
66
+ mimeType: f.type,
67
+ };
68
+ }),
69
+ ...("input" in args ? { input: args.input } : {}),
70
+ } satisfies PresignUploadBody),
71
+ }).then((r) => r.json())) as PresignUploadResponse;
72
+
73
+ // upload files to presign urls (sessionId required for S3 listener to update DynamoDB)
74
+ await Promise.all(
75
+ args.files.map((file, index) => {
76
+ if (!result.files[index]?.url) {
77
+ throw new Error(`No presign URL returned for file index ${index}`);
78
+ }
79
+
80
+ return fetch(result.files[index].url, {
81
+ method: "PUT",
82
+ headers: {
83
+ "Content-Type": file.type,
84
+ "Content-Disposition": "inline",
85
+ },
86
+ body: file,
87
+ });
88
+ }),
89
+ );
90
+
91
+ // poll for completion (S3 listener Lambda updates DynamoDB when upload lands)
92
+ const pollParams = new URLSearchParams();
93
+ pollParams.append("action", "poll");
94
+ pollParams.append("uploader", String(uploader));
95
+ pollParams.append("sessionId", result.sessionId);
96
+
97
+ const pollUntilComplete = async (): Promise<PollResponse> => {
98
+ const res = await fetch(`${url}?${pollParams.toString()}`, {
99
+ method: "POST",
100
+ headers: { "Content-Type": "application/json" },
101
+ body: JSON.stringify({}),
102
+ });
103
+ const data = (await res.json()) as PollResponse;
104
+ if (data.completed) return data;
105
+ await new Promise((r) => setTimeout(r, 1000));
106
+ return pollUntilComplete();
107
+ };
108
+
109
+ const pollResult = await pollUntilComplete();
110
+
111
+ if (args.onClientUploadComplete && pollResult.files) {
112
+ const completedFiles = pollResult.files.filter(
113
+ (f) => f.status === "SUCCESS" && f.file,
114
+ );
115
+ const results = completedFiles.map((f) => ({
116
+ file: f.file!,
117
+ metadata: f.metadata ?? {},
118
+ }));
119
+ if (results.length > 0) {
120
+ args.onClientUploadComplete(
121
+ results.length === 1 ? results[0] : (results as any),
122
+ );
123
+ }
124
+ }
125
+ },
126
+ };
127
+ }
@@ -0,0 +1,16 @@
1
+ import type { Context } from "hono";
2
+ import type { Bucket } from "../bucket";
3
+
4
+ export function createRouteHandler(bucket: Bucket<any>) {
5
+ return async (c: Context) => {
6
+ const req = c.req.raw;
7
+ const body = (await req.json()) as any;
8
+
9
+ const result = await bucket.handleUpload({
10
+ body,
11
+ request: req,
12
+ });
13
+
14
+ return c.json(result);
15
+ };
16
+ }
@@ -0,0 +1,68 @@
1
+ export type KnownMimeType =
2
+ // --- APPLICATION ---
3
+ | "application/json"
4
+ | "application/xml"
5
+ | "application/octet-stream" // Generic binary data
6
+ | "application/zip"
7
+ | "application/gzip"
8
+ | "application/x-tar"
9
+ | "application/wasm"
10
+ | "application/x-7z-compressed" // 7z files
11
+ | "application/x-sh" // Shell script
12
+ | "application/*"
13
+
14
+ // --- DOCUMENTS / TEXT ---
15
+ | "text/plain"
16
+ | "text/csv"
17
+ | "text/html"
18
+ | "text/css"
19
+ | "text/javascript" // Use application/javascript in production
20
+ | "application/javascript"
21
+ | "application/typescript"
22
+ | "application/pdf"
23
+ | "application/rtf"
24
+ | "text/*"
25
+
26
+ // --- IMAGES ---
27
+ | "image/jpeg"
28
+ | "image/png"
29
+ | "image/gif"
30
+ | "image/webp"
31
+ | "image/svg+xml"
32
+ | "image/bmp"
33
+ | "image/tiff"
34
+ | "image/avif"
35
+ | "image/vnd.microsoft.icon" // ICO files
36
+ | "image/*"
37
+
38
+ // --- AUDIO ---
39
+ | "audio/mpeg" // MP3
40
+ | "audio/wav"
41
+ | "audio/ogg"
42
+ | "audio/aac"
43
+ | "audio/flac"
44
+ | "audio/*"
45
+
46
+ // --- VIDEO ---
47
+ | "video/mp4"
48
+ | "video/webm"
49
+ | "video/ogg"
50
+ | "video/quicktime" // MOV
51
+ | "video/x-msvideo" // AVI
52
+ | "video/*"
53
+
54
+ // --- MICROSOFT OFFICE / OPEN OFFICE (Crucial for Business Apps) ---
55
+ | "application/msword" // .doc
56
+ | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" // .docx
57
+ | "application/vnd.ms-excel" // .xls
58
+ | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" // .xlsx
59
+ | "application/vnd.ms-powerpoint" // .ppt
60
+ | "application/vnd.openxmlformats-officedocument.presentationml.presentation" // .pptx
61
+ | "application/vnd.oasis.opendocument.text" // .odt
62
+ | "application/vnd.oasis.opendocument.spreadsheet" // .ods
63
+
64
+ // --- FONT ---
65
+ | "font/otf"
66
+ | "font/ttf"
67
+ | "font/woff"
68
+ | "font/woff2";
@@ -0,0 +1,93 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ import type { FileSize } from "./types";
3
+ import { UploadError } from "./upload-error";
4
+
5
+ export function parseReq(req: Request | IncomingMessage): {
6
+ headers: Record<string, string>;
7
+ method: string;
8
+ url: string;
9
+ path: string;
10
+ query: URLSearchParams;
11
+ } {
12
+ if (req instanceof Request) {
13
+ const headers: Record<string, string> = {};
14
+ req.headers.forEach((value, key) => {
15
+ headers[key] = value;
16
+ });
17
+ return {
18
+ headers,
19
+ method: req.method,
20
+ url: req.url,
21
+ path: new URL(req.url).pathname,
22
+ query: new URL(req.url).searchParams,
23
+ };
24
+ }
25
+
26
+ const headers: Record<string, string> = {};
27
+ for (const [key, value] of Object.entries(req.headers)) {
28
+ if (typeof value === "string") {
29
+ headers[key] = value;
30
+ } else if (Array.isArray(value)) {
31
+ headers[key] = value.join(", ");
32
+ }
33
+ }
34
+
35
+ const url = new URL(req.url || "", "http://localhost");
36
+
37
+ return {
38
+ headers,
39
+ method: req.method || "GET",
40
+ url: req.url || "",
41
+ path: url.pathname,
42
+ query: url.searchParams,
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Converts a human-readable file size string (e.g., "10MB", "2.5GB") into bytes.
48
+ * Throws an error for invalid input formats.
49
+ * * @param size The file size represented as a number (bytes) or a string with units (KB, MB, GB, B).
50
+ * @returns The size in bytes (number).
51
+ */
52
+ export function parseFileSize(size: FileSize): number {
53
+ if (typeof size === "number") {
54
+ if (size < 0) {
55
+ throw UploadError.badRequest("File size cannot be negative.");
56
+ }
57
+ return size;
58
+ }
59
+
60
+ // Convert the input to uppercase to handle 'mb', 'MB', 'Mb' uniformly
61
+ const cleanSize = size.toUpperCase().trim();
62
+
63
+ // Regular expression to extract the numeric value and the unit
64
+ // Captures: (1) The number part, (2) The unit part (B, KB, MB, GB)
65
+ const match = cleanSize.match(/^(\d+(\.\d+)?)([A-Z]+)$/);
66
+
67
+ if (!match) {
68
+ throw UploadError.badRequest(
69
+ `Invalid file size format: "${size}". Expected formats: "10MB", "2GB", "512KB", or raw bytes.`
70
+ );
71
+ }
72
+
73
+ const numericValue = Number.parseFloat(match[1] ?? "0");
74
+ const unit = match[3] ?? "";
75
+
76
+ const byteConversionMap: Record<string, number> = {
77
+ B: 1,
78
+ KB: 1024,
79
+ MB: 1024 ** 2, // 1,048,576
80
+ GB: 1024 ** 3, // 1,073,741,824
81
+ };
82
+
83
+ const multiplier = byteConversionMap[unit];
84
+
85
+ if (!multiplier) {
86
+ throw new Error(
87
+ `Invalid file size unit: "${unit}". Must be B, KB, MB, or GB.`
88
+ );
89
+ }
90
+
91
+ // Return the size rounded to the nearest integer byte
92
+ return Math.round(numericValue * multiplier);
93
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * S3 event listener Lambda for ocel/blob.
3
+ * Receives ObjectCreated events, reads x-ocel-session-id from object metadata,
4
+ * and updates the UploadSession in DynamoDB to SUCCESS.
5
+ */
6
+ import type { S3Handler, S3Event } from "aws-lambda";
7
+ import { HeadObjectCommand, S3Client } from "@aws-sdk/client-s3";
8
+ import { UpdateItemCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";
9
+
10
+ const s3 = new S3Client({});
11
+ const dynamo = new DynamoDBClient({});
12
+ const TABLE_NAME = process.env.OCEL_TABLE_NAME || "OcelTable";
13
+
14
+ export const handler: S3Handler = async (event: S3Event) => {
15
+ for (const record of event.Records) {
16
+ const bucket = record.s3.bucket.name;
17
+ const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
18
+
19
+ try {
20
+ const head = await s3.send(
21
+ new HeadObjectCommand({ Bucket: bucket, Key: key }),
22
+ );
23
+ const sessionId = head.Metadata?.["x-ocel-session-id"];
24
+ if (!sessionId) continue;
25
+
26
+ const pk = `SESSION#${sessionId}`.toLowerCase();
27
+ const sk = `FILE#${bucket}#${key}`.toLowerCase();
28
+
29
+ await dynamo.send(
30
+ new UpdateItemCommand({
31
+ TableName: TABLE_NAME,
32
+ Key: {
33
+ pk: { S: pk },
34
+ sk: { S: sk },
35
+ },
36
+ UpdateExpression: "SET #status = :status, updatedAt = :now",
37
+ ExpressionAttributeNames: { "#status": "status" },
38
+ ExpressionAttributeValues: {
39
+ ":status": { S: "SUCCESS" },
40
+ ":now": { S: new Date().toISOString() },
41
+ },
42
+ }),
43
+ );
44
+ } catch (err) {
45
+ console.error(`Failed to update session for ${bucket}/${key}:`, err);
46
+ }
47
+ }
48
+ };
@@ -0,0 +1,142 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ import z, { type ZodType } from "zod";
3
+ import type { KnownMimeType } from "./mime-types";
4
+ import type { UploadError } from "./upload-error";
5
+
6
+ type SuggestedSize = "1KB" | "100KB" | "1MB" | "10MB" | "100MB" | "1GB";
7
+ export type FileSizeUnit = "B" | "KB" | "MB" | "GB";
8
+ export type UnitAutocomplete<TUnit extends string> = `${number}${TUnit}`;
9
+ export type FileSize =
10
+ | SuggestedSize
11
+ | UnitAutocomplete<FileSizeUnit>
12
+ | number
13
+ | (string & {});
14
+
15
+ export type StringWithAutocomplete<T extends string> = T | (string & {});
16
+ export type HandleUploadBody = PresignUploadBody | CallbackBody<any>;
17
+ export type HandleUploadResult = PresignUploadResponse;
18
+
19
+ export type PresignUploadBody = {
20
+ files: {
21
+ name: string;
22
+ size: number;
23
+ mimeType: string;
24
+ lastModified: number;
25
+ }[];
26
+ input?: Record<string, any>;
27
+ };
28
+
29
+ export type PresignUploadResponse = {
30
+ files: {
31
+ url: string;
32
+ key: string;
33
+ name: string;
34
+ }[];
35
+ sessionId: string;
36
+ };
37
+
38
+ export type CallbackBody<TMeta> = {
39
+ metadata: TMeta;
40
+ file: {
41
+ path: string;
42
+ contentDisposition: string;
43
+ contentType: string;
44
+ };
45
+ };
46
+
47
+ export type UploadFileBody = {
48
+ key: string;
49
+ name: string;
50
+ size: number;
51
+ mimeType: string;
52
+ disposition: string;
53
+ lastModified: number;
54
+ metadata?: Record<string, string>;
55
+ };
56
+
57
+ export type PathConfig = {
58
+ prefix?: string;
59
+ suffix?: string;
60
+ randomSuffix?: boolean;
61
+ };
62
+
63
+ export type PathContext<TMeta> = [TMeta] extends [never]
64
+ ? {
65
+ /**
66
+ * File extension including the dot (e.g., .jpg, .png)
67
+ */
68
+ ext: string;
69
+ /**
70
+ * File name without extension
71
+ */
72
+ fileNameWithoutExt: string;
73
+ /**
74
+ * Original file name as uploaded by user
75
+ */
76
+ fileNameWithExt: string;
77
+ }
78
+ : {
79
+ /**
80
+ * File extension including the dot (e.g., .jpg, .png)
81
+ */
82
+ ext: string;
83
+ /**
84
+ * File name without extension
85
+ */
86
+ fileNameWithoutExt: string;
87
+ /**
88
+ * Original file name as uploaded by user
89
+ */
90
+ fileNameWithExt: string;
91
+ /**
92
+ * Any metadata returned by middleware function
93
+ */
94
+ metadata: TMeta;
95
+ };
96
+
97
+ export type PathGenerator<TMeta> = (ctx: PathContext<TMeta>) => string;
98
+ export type PathInput<TMeta> = PathConfig | PathGenerator<TMeta>;
99
+
100
+ export type TUploaderConfig<
101
+ TInput extends ZodType = never,
102
+ TMeta = never,
103
+ TReturn = unknown
104
+ > = {
105
+ path?: PathInput<TMeta>;
106
+ input?: TInput;
107
+ accept?: StringWithAutocomplete<KnownMimeType>[];
108
+ limits?: {
109
+ maxFileSize?: FileSize | ((ctx: { metadata?: TMeta }) => FileSize);
110
+ maxFileCount?: number | ((ctx: { metadata?: TMeta }) => number);
111
+ minFileCount?: number | ((ctx: { metadata?: TMeta }) => number);
112
+ };
113
+ contentDisposition?: "inline" | "attachment";
114
+
115
+ onBeforeUpload: (
116
+ opts: [TInput] extends [never]
117
+ ? {
118
+ files: PresignUploadBody["files"];
119
+ req: Request | IncomingMessage;
120
+ }
121
+ : {
122
+ files: PresignUploadBody["files"];
123
+ input: z.infer<TInput>;
124
+ req: Request | IncomingMessage;
125
+ }
126
+ ) => TMeta | Promise<TMeta>;
127
+ onUploadError?: (args: { error: UploadError }) => void | Promise<void>;
128
+ onUploadComplete?: (args: {
129
+ metadata: TMeta;
130
+ file: { path: string; contentDisposition: string; contentType: string };
131
+ }) => TReturn | Promise<TReturn>;
132
+
133
+ _def: {
134
+ meta: TMeta;
135
+ input: TInput;
136
+ output: TReturn;
137
+ };
138
+ };
139
+
140
+ export type TBucketConfig<TUploaderShape> = {
141
+ uploaders: TUploaderShape;
142
+ };
@@ -0,0 +1,67 @@
1
+ export class UploadError extends Error {
2
+ public readonly statusCode: number;
3
+ public readonly code: string;
4
+
5
+ constructor(
6
+ message: string,
7
+ statusCode = 500,
8
+ code = "INTERNAL_SERVER_ERROR"
9
+ ) {
10
+ super(message);
11
+ this.statusCode = statusCode;
12
+ this.code = code;
13
+
14
+ // Essential for 'instanceof' to work correctly when extending built-in classes in TypeScript
15
+ Object.setPrototypeOf(this, UploadError.prototype);
16
+ }
17
+
18
+ // --- Static Factory Helpers (The DX Magic) ---
19
+
20
+ /**
21
+ * 400 Bad Request
22
+ * Use when the input is invalid (e.g. file too big, wrong extension)
23
+ */
24
+ static badRequest(message = "Bad Request") {
25
+ return new UploadError(message, 400, "BAD_REQUEST");
26
+ }
27
+
28
+ /**
29
+ * 401 Unauthorized
30
+ * Use when the user is not logged in or missing headers
31
+ */
32
+ static unauthorized(message = "Unauthorized") {
33
+ return new UploadError(message, 401, "UNAUTHORIZED");
34
+ }
35
+
36
+ /**
37
+ * 403 Forbidden
38
+ * Use when the user is logged in but doesn't have permission (e.g. wrong plan)
39
+ */
40
+ static forbidden(message = "Forbidden") {
41
+ return new UploadError(message, 403, "FORBIDDEN");
42
+ }
43
+
44
+ /**
45
+ * 404 Not Found
46
+ * Use when a resource required for the upload is missing
47
+ */
48
+ static notFound(message = "Not Found") {
49
+ return new UploadError(message, 404, "NOT_FOUND");
50
+ }
51
+
52
+ /**
53
+ * 429 Too Many Requests
54
+ * Use for rate limiting logic
55
+ */
56
+ static tooManyRequests(message = "Too many requests") {
57
+ return new UploadError(message, 429, "TOO_MANY_REQUESTS");
58
+ }
59
+
60
+ /**
61
+ * 500 Internal Server Error
62
+ * Use for unexpected crashes or database failures
63
+ */
64
+ static internal(message = "Internal Server Error") {
65
+ return new UploadError(message, 500, "INTERNAL_SERVER_ERROR");
66
+ }
67
+ }