`TextEncoder.encode` is typed `Uint8Array<ArrayBufferLike>` in workers-types; it returns a non-shared buffer

オープン 初心者向け
#8,807 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
72/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
cpp, typescript
領域
api

調査の方向性

変更すべき宣言は TextEncoder.encode で、その型は src/workerd/api/encoding.h の C++ バインディングから生成されています。同ファイルにある既存の encodeInto の JSG_TS_OVERRIDE をパターンとして使い、encodeUtf8Chunk に基づくストリーム出力や bytes() も同じ変更が必要かを確認してください。issue の再現コードが @cloudflare/workers-types を使い strict mode でコンパイルでき、型テストが通れば完了です。

索引モデルが issue の本文から書いたものです。

説明

In @cloudflare/workers-types 5.20261121.1, TextEncoder declares:

encode(input?: string): Uint8Array;

Since TypeScript 5.7 made typed arrays generic over their buffer, a bare Uint8Array means Uint8Array<ArrayBufferLike>, which includes SharedArrayBuffer. encode always returns a view over a fresh, non-shared ArrayBuffer, so the precise type is Uint8Array<ArrayBuffer>. TypeScript's own lib.dom.d.ts and lib.webworker.d.ts (5.9) declare encode(input?: string): Uint8Array<ArrayBuffer>, and @types/node declares NodeJS.NonSharedUint8Array.

Repro

TypeScript 7.0.2, @cloudflare/workers-types 5.20261121.1, "types": ["@cloudflare/workers-types"], "strict": true:

export function encode(value: string): Uint8Array<ArrayBuffer> {
  return new TextEncoder().encode(value);
}
error TS2322: Type 'Uint8Array<ArrayBufferLike>' is not assignable to type 'Uint8Array<ArrayBuffer>'.
  Type 'ArrayBufferLike' is not assignable to type 'ArrayBuffer'.
    Type 'SharedArrayBuffer' is not assignable to type 'ArrayBuffer'.

Why it matters

Code that runs on both Node and Workers has to type the result as Uint8Array<ArrayBuffer>, because Node's and lib.dom's BufferSource reject ArrayBufferLike-backed views. With workers-types loaded, the same code then needs a cast or a Uint8Array.from(...) copy.

Request

Declare encode(input?: string): Uint8Array<ArrayBuffer> (for example with a JSG_TS_OVERRIDE in src/workerd/api/encoding.h, as encodeInto already has). Other APIs that return freshly allocated buffers, such as encodeUtf8Chunk-backed streams or bytes(), may have the same widening.

Related: #7833 tracks rejecting SharedArrayBuffer-backed views at runtime in SubtleCrypto. That issue is about runtime behaviour; this one is only about the declared return type.

主要言語
C++
スター
9.3k
フォーク
845
平均マージ
1日 23時間
マージ済み PR(30日)
558

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

cloudflare/workerd のほかの issue

cloudflare/workerd の issue をすべて見る

似ている issue

C++ の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。