Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add script for initializing data #18

Merged
merged 2 commits into from
Mar 20, 2025
Merged

feat: add script for initializing data #18

merged 2 commits into from
Mar 20, 2025

Conversation

luxass
Copy link
Member

@luxass luxass commented Mar 20, 2025

This could potentially be used for adding data for test files more efficiently, but most important it will allow us to setup the data when installing from scratch.

Summary by CodeRabbit

  • New Features
    • Introduced a development dependency to enable enhanced processing.
    • Added an automated process that fetches and processes emoji data from external sources.
    • Implemented a secure endpoint that validates and uploads emoji data, ensuring reliable updates.

This could potentially be used for adding data for test files more efficiently, but most important it will allow us to setup the data when installing from scratch.
Copy link

coderabbitai bot commented Mar 20, 2025

Walkthrough

The update introduces new functionality for managing emoji data. A new development dependency, "nanotar": "^0.2.0", has been added to the package.json. Additionally, two new TypeScript files have been implemented. One script fetches a tarball of emoji data from GitHub, processes it through a worker, and uploads it via an API endpoint. The other script sets up an HTTP server using the Hono framework to handle file uploads, extracts valid emoji data from a tar.gz archive, and uploads the entries to an R2 bucket.

Changes

File(s) Change Summary
package.json Added new devDependency: "nanotar": "^0.2.0".
scripts/copy-emoji-data.ts, scripts/emoji-data-setup-app.ts Introduced two new TypeScript scripts. copy-emoji-data.ts fetches a tarball of emoji data from GitHub, processes it via a worker, and uploads the data to an API endpoint. emoji-data-setup-app.ts sets up an HTTP server with Hono to accept emoji data uploads, extract and filter JSON files, and store them in an R2 bucket.

Sequence Diagram(s)

sequenceDiagram
    participant Script as copy-emoji-data.ts
    participant GitHub as GitHub Repo
    participant Worker as Worker Process
    participant API as Upload API
    Script->>+GitHub: Fetch emoji tarball data
    GitHub-->>-Script: Return tarball (or error)
    Script->>Worker: Start worker with config
    Script->>Script: Create FormData with tarball blob
    Script->>+API: POST request with FormData
    API-->>-Script: Confirm upload
    Script->>Worker: Dispose worker
Loading
sequenceDiagram
    participant Client as Request Client
    participant Server as HTTP Server (Hono)
    participant Parser as parseTarGzip
    participant R2 as R2 Bucket
    Client->>Server: POST /upload with tar.gz file
    Server->>Parser: Extract archive contents
    Parser-->>Server: Return listing of files
    Server->>Server: Filter files by valid prefix
    Server->>R2: Upload valid JSON files
    R2-->>Server: Acknowledge uploads
    Server->>Client: Respond with JSON success message
Loading

Poem

I'm a little rabbit in a code-filled glen,
Hopping through changes again and again.
Fetching emoji data from skies so bright,
Uploading through workers with all my might.
A server stands ready with Hono in play,
My carrot of nanotar lights up the day.
Hoppy code and joy in every byte!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

socket-security bot commented Mar 20, 2025

New dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/[email protected] None 0 37.5 kB pi0

View full report↗︎

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (7)
scripts/copy-emoji-data.ts (3)

7-31: Implement better error handling and response validation

The script successfully fetches emoji data from GitHub and uploads it via a worker, but several improvements would make it more robust:

  1. Add validation for the worker response
  2. Include progress reporting for potentially large downloads
  3. Consider adding a timeout for the fetch operation
async function run() {
  const res = await fetch("https://github.com/mojisdev/emoji-data/archive/refs/heads/main.tar.gz");

  if (!res.ok) {
    throw new Error(`Failed to fetch emoji-data: ${res.statusText}`);
  }

  const blob = await res.blob();

  const worker = await unstable_startWorker({
    config: path.join(root.toString(), "./wrangler.jsonc"),
    entrypoint: path.join(root.toString(), "./scripts/emoji-data-setup-app.ts"),
  });

  const formData = new FormData();
  formData.append("file", blob, "emoji-data.tar.gz");

-  await worker.fetch("https://api.mojis.dev/upload", {
+  const uploadResponse = await worker.fetch("https://api.mojis.dev/upload", {
    method: "POST",
    // @ts-expect-error hmmm
    body: formData,
  });
+  
+  if (!uploadResponse.ok) {
+    throw new Error(`Failed to upload emoji data: ${await uploadResponse.text()}`);
+  }
+  
+  const result = await uploadResponse.json();
+  console.log("Upload successful:", result.message);

  await worker.dispose();
}

16-19: Consider making worker configuration more flexible

The worker configuration is hardcoded with specific paths. Consider making these configurable through environment variables or command-line arguments for better flexibility across different environments.


24-24: Avoid hardcoded URLs

The URL "https://api.mojis.dev/upload" is hardcoded, which could cause issues in different environments (dev, staging, prod).

- await worker.fetch("https://api.mojis.dev/upload", {
+ const apiUrl = process.env.API_URL || "https://api.mojis.dev";
+ await worker.fetch(`${apiUrl}/upload`, {
scripts/emoji-data-setup-app.ts (4)

18-22: Improve validation error message

The error message for a missing file could be more informative to help users understand what they need to provide.

if (file == null) {
  throw new HTTPException(400, {
-   message: "No file uploaded",
+   message: "No file uploaded. Please provide a tar.gz file containing emoji data",
  });
}

24-28: Fix inconsistent error message casing

The error message for invalid file uploads uses lowercase while other messages start with uppercase. Maintain consistency in error messages.

if (typeof file === "string") {
  throw new HTTPException(400, {
-   message: "invalid file uploaded",
+   message: "Invalid file uploaded",
  });
}

45-52: Add file size validation

The code doesn't check the size of the files being uploaded to the R2 bucket. Implement size validation to prevent storing excessively large files.

const promises = [];
+ const MAX_FILE_SIZE = 1024 * 1024; // 1MB limit per file

for (const entry of tar) {
  if (entry.type !== "file") continue;
  const normalizedEntryName = entry.name.replace("./", "");

+  if (entry.text.length > MAX_FILE_SIZE) {
+    console.warn(`Skipping ${normalizedEntryName}: File exceeds maximum size of ${MAX_FILE_SIZE} bytes`);
+    continue;
+  }
  
  promises.push(c.env.EMOJI_DATA.put(normalizedEntryName, entry.text));
}

58-60: Enhance response with upload statistics

The current response only includes a generic message. Enhance it to include statistics about the uploaded files.

return c.json({
  message: "Files uploaded",
+ count: promises.length,
+ timestamp: new Date().toISOString()
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between de9631c and 1a0c9a1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • scripts/copy-emoji-data.ts (1 hunks)
  • scripts/emoji-data-setup-app.ts (1 hunks)
🔇 Additional comments (1)
package.json (1)

31-31:

✅ Verification successful

New dependency added for tar.gz processing

The addition of nanotar is appropriate for handling the tar.gz files in the new scripts. This lightweight package seems to be a good choice for the specific task of extracting emoji data from archives.


🌐 Web query:

What is nanotar npm package and is it suitable for production use?

💡 Result:

The nanotar npm package is a minimalistic and efficient utility for handling TAR archives in JavaScript environments. Designed for modern runtimes like Node.js 18+, Bun, Deno, browsers, and Edge Workers, it emphasizes performance and compactness (~1KB minified + gzipped). Here's a breakdown of its features and production viability:


Key Features

  • Cross-Platform Compatibility: Works in all major JS runtimes with TypeScript/ESM support[1].
  • Streamlined API: Includes utilities for creating and parsing TAR archives:
    • createTar/createTarGzip for archive generation[1].
    • parseTar/parseTarGzip for parsing, with options to filter files or skip data extraction for metadata-only use cases[1].
  • Compression Support: Built-in GZIP compression/decompression via createTarGzipStream and parseTarGzip[1].
  • Modern Attributes: Supports file metadata like permissions (mode), timestamps (mtime), and ownership details[1].

Production Suitability

  1. Security:
    No known vulnerabilities are reported for the latest version (0.2.0) as of March 2025[13].

  2. Performance:
    Optimized for speed and minimal resource usage, making it ideal for resource-constrained environments like Edge Workers[1].

  3. Maintenance:
    Actively maintained by the unjs ecosystem, with recent updates and clear documentation[1][10].

  4. Limitations:

    • Lacks explicit test suite mentions in its public documentation[1][10].
    • Targets modern JS environments, which may require transpilation for legacy systems[1].

Comparison with Alternatives

Feature nanotar Traditional TAR Tools (e.g., tar-fs)
Size ~1KB Larger (e.g., tar-fs: ~20KB)
ESM/CJS Support Native Often requires polyfills
Compression Built-in GZIP External dependencies (e.g., zlib)
Runtime Compatibility Universal (Node, Deno, Browser) Node.js-focused

Recommendation

Nanotar is production-ready for lightweight TAR operations where bundle size and modern runtime compatibility are critical. For complex workflows requiring extensive testing or legacy system support, evaluate additional validation or alternatives like tar-fs. Always verify compatibility with your deployment environment.

Citations:


Approved: Nanotar Dependency Verified for TAR Processing

The addition of the nanotar dependency in package.json (line 31) is well-justified. As verified, nanotar is a lightweight (~1KB minified + gzipped), production-ready package designed for efficiently handling TAR/GZIP archives across modern JS runtimes. This makes it a suitable choice for processing tar.gz files—as required for extracting emoji data in the new scripts.

Comment on lines +26 to +27
// @ts-expect-error hmmm
body: formData,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Fix TypeScript error instead of suppressing it

The code has a TypeScript error that's being suppressed with a @ts-expect-error comment. This should be addressed properly.

A possible solution would be to properly type the FormData:

- // @ts-expect-error hmmm
- body: formData,
+ body: formData as unknown as BodyInit,

Or you could use an alternative approach that's type-safe.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// @ts-expect-error hmmm
body: formData,
body: formData as unknown as BodyInit,

Comment on lines +11 to +62
app.post(
"/upload",
async (c) => {
const body = await c.req.parseBody();

const file = Array.isArray(body.file) ? body.file[0] : body.file;

if (file == null) {
throw new HTTPException(400, {
message: "No file uploaded",
});
}

if (typeof file === "string") {
throw new HTTPException(400, {
message: "invalid file uploaded",
});
}

const filePrefix = "emoji-data-main/data/";

const tar = await parseTarGzip(await file.arrayBuffer(), {
filter(file) {
if (!file.name.startsWith(filePrefix) || !file.name.endsWith(".json")) {
return false;
}

// remove the file prefix
file.name = file.name.slice(filePrefix.length);

return true;
},
});

const promises = [];

for (const entry of tar) {
if (entry.type !== "file") continue;
const normalizedEntryName = entry.name.replace("./", "");

promises.push(c.env.EMOJI_DATA.put(normalizedEntryName, entry.text));
}

c.executionCtx.waitUntil(
Promise.all(promises),
);

return c.json({
message: "Files uploaded",
});
},
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add comprehensive error handling for file processing

The upload endpoint lacks error handling for processing and uploading files. If any file upload fails, the error won't be properly captured or reported back to the client.

app.post(
  "/upload",
  async (c) => {
    const body = await c.req.parseBody();

    const file = Array.isArray(body.file) ? body.file[0] : body.file;

    if (file == null) {
      throw new HTTPException(400, {
        message: "No file uploaded",
      });
    }

    if (typeof file === "string") {
      throw new HTTPException(400, {
        message: "invalid file uploaded",
      });
    }

    const filePrefix = "emoji-data-main/data/";

+    try {
      const tar = await parseTarGzip(await file.arrayBuffer(), {
        filter(file) {
          if (!file.name.startsWith(filePrefix) || !file.name.endsWith(".json")) {
            return false;
          }

          // remove the file prefix
          file.name = file.name.slice(filePrefix.length);

          return true;
        },
      });

      const promises = [];
+      const results = { success: [], failed: [] };

      for (const entry of tar) {
        if (entry.type !== "file") continue;
        const normalizedEntryName = entry.name.replace("./", "");

-       promises.push(c.env.EMOJI_DATA.put(normalizedEntryName, entry.text));
+       promises.push(
+         c.env.EMOJI_DATA.put(normalizedEntryName, entry.text)
+           .then(() => results.success.push(normalizedEntryName))
+           .catch((error) => results.failed.push({ name: normalizedEntryName, error: error.message }))
+       );
      }

      c.executionCtx.waitUntil(
        Promise.all(promises),
      );

      return c.json({
        message: "Files uploaded",
+       stats: {
+         successful: results.success.length,
+         failed: results.failed.length,
+       },
+       details: results
      });
+    } catch (error) {
+      throw new HTTPException(500, {
+        message: `Failed to process uploaded file: ${error instanceof Error ? error.message : String(error)}`,
+      });
+    }
  },
);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
app.post(
"/upload",
async (c) => {
const body = await c.req.parseBody();
const file = Array.isArray(body.file) ? body.file[0] : body.file;
if (file == null) {
throw new HTTPException(400, {
message: "No file uploaded",
});
}
if (typeof file === "string") {
throw new HTTPException(400, {
message: "invalid file uploaded",
});
}
const filePrefix = "emoji-data-main/data/";
const tar = await parseTarGzip(await file.arrayBuffer(), {
filter(file) {
if (!file.name.startsWith(filePrefix) || !file.name.endsWith(".json")) {
return false;
}
// remove the file prefix
file.name = file.name.slice(filePrefix.length);
return true;
},
});
const promises = [];
for (const entry of tar) {
if (entry.type !== "file") continue;
const normalizedEntryName = entry.name.replace("./", "");
promises.push(c.env.EMOJI_DATA.put(normalizedEntryName, entry.text));
}
c.executionCtx.waitUntil(
Promise.all(promises),
);
return c.json({
message: "Files uploaded",
});
},
);
app.post(
"/upload",
async (c) => {
const body = await c.req.parseBody();
const file = Array.isArray(body.file) ? body.file[0] : body.file;
if (file == null) {
throw new HTTPException(400, {
message: "No file uploaded",
});
}
if (typeof file === "string") {
throw new HTTPException(400, {
message: "invalid file uploaded",
});
}
const filePrefix = "emoji-data-main/data/";
try {
const tar = await parseTarGzip(await file.arrayBuffer(), {
filter(file) {
if (!file.name.startsWith(filePrefix) || !file.name.endsWith(".json")) {
return false;
}
// remove the file prefix
file.name = file.name.slice(filePrefix.length);
return true;
},
});
const promises = [];
const results = { success: [], failed: [] };
for (const entry of tar) {
if (entry.type !== "file") continue;
const normalizedEntryName = entry.name.replace("./", "");
promises.push(
c.env.EMOJI_DATA.put(normalizedEntryName, entry.text)
.then(() => results.success.push(normalizedEntryName))
.catch((error) =>
results.failed.push({ name: normalizedEntryName, error: error.message })
)
);
}
c.executionCtx.waitUntil(Promise.all(promises));
return c.json({
message: "Files uploaded",
stats: {
successful: results.success.length,
failed: results.failed.length,
},
details: results,
});
} catch (error) {
throw new HTTPException(500, {
message: `Failed to process uploaded file: ${
error instanceof Error ? error.message : String(error)
}`,
});
}
},
);

@luxass luxass merged commit 2e682ef into main Mar 20, 2025
4 checks passed
@luxass luxass deleted the import-data branch March 20, 2025 05:37
@coderabbitai coderabbitai bot mentioned this pull request Mar 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant