| 104 | |
| 105 | /** Build a session-scoped artifacts client over a namespace binding. */ |
| 106 | export function createArtifact(binding: Artifacts, sessionId: string): ArtifactClient { |
| 107 | // Validate the session id eagerly so a bad id fails at |
| 108 | // construction rather than on first use. |
| 109 | scopePrefix(sessionId); |
| 110 | |
| 111 | const client: ArtifactClient = { |
| 112 | sessionId, |
| 113 | |
| 114 | async create(name, opts) { |
| 115 | const result = await binding.create(scopedName(sessionId, name), opts); |
| 116 | return { ...result, name: unscopeOr(sessionId, result.name, name) }; |
| 117 | }, |
| 118 | |
| 119 | async get(name) { |
| 120 | const handle = await binding.get(scopedName(sessionId, name)); |
| 121 | // The handle is a live Workers-RPC stub (ArtifactsRepo extends |
| 122 | // RpcTarget). The published `@cloudflare/workers-types` shape is |
| 123 | // wrong in both directions: it models the metadata as inherited |
| 124 | // `ArtifactsRepoInfo` properties (which the runtime stub does |
| 125 | // not expose — reading `handle.remote` yields an RpcPromise for |
| 126 | // a nonexistent method) and omits `info()` (which the runtime |
| 127 | // does have, returning the metadata by value). Reach `info()` |
| 128 | // through a typed view until the published types are corrected. |
| 129 | const view = handle as unknown as { info(): Promise<ArtifactsRepoInfo> }; |
| 130 | const info = await view.info(); |
| 131 | return repoInfo(info, name); |
| 132 | }, |
| 133 | |
| 134 | async list() { |
| 135 | const out: ArtifactRepoSummary[] = []; |
| 136 | let cursor: string | undefined; |
| 137 | let done = false; |
| 138 | const seenCursors = new Set<string>(); |
| 139 | while (!done) { |
| 140 | const page = await binding.list({ limit: LIST_PAGE_SIZE, cursor }); |
| 141 | for (const repo of page.repos) { |
| 142 | const local = unscopedName(sessionId, repo.name); |
| 143 | if (local !== undefined) out.push({ ...repo, name: local }); |
| 144 | } |
| 145 | const next = page.cursor; |
| 146 | if (next === undefined) { |
| 147 | done = true; |
| 148 | } else { |
| 149 | if (seenCursors.has(next)) { |
| 150 | throw new Error(`artifacts list returned a non-advancing cursor: ${next}`); |
| 151 | } |
| 152 | seenCursors.add(next); |
| 153 | cursor = next; |
| 154 | } |
| 155 | } |
| 156 | return out; |
| 157 | }, |
| 158 | |
| 159 | async import(name, source, opts) { |
| 160 | const result = await binding.import({ |
| 161 | source, |
| 162 | target: { name: scopedName(sessionId, name), opts }, |
| 163 | }); |