Pyric
Navigate

API reference

pyric/storage

69 published symbols from pyric

Generated from the TypeScript declarations shipped at this import path.

Check behavioral conformance

Classes

InspectStorageHandler

Constructors

Constructor
new InspectStorageHandler(): InspectStorageHandler;
Returns

InspectStorageHandler

Methods

execute()
execute(scope: ProjectScope): Promise<InspectStorageResult>;
Parameters
ParameterType
scopeProjectScope
Returns

Promise<InspectStorageResult>


ProvisionStorageHandler

Constructors

Constructor
new ProvisionStorageHandler(): ProvisionStorageHandler;
Returns

ProvisionStorageHandler

Methods

execute()
execute(
   scope: ProjectScope,
   input: ProvisionStorageInput,
onProgress?: ProvisionProgress): Promise<ProvisionStorageOutcome>;
Parameters
ParameterType
scopeProjectScope
inputProvisionStorageInput
onProgress?ProvisionProgress
Returns

Promise<ProvisionStorageOutcome>


StorageError

Storage error carrying a prefixed storage/<code> on .code. Drop-in for err.code === 'storage/object-not-found' branching.

Extends

  • Error

Constructors

Constructor
new StorageError(code: StorageErrorCode, message: string): StorageError;
Parameters
ParameterType
codeStorageErrorCode
messagestring
Returns

StorageError

Overrides
Error.constructor

Properties

PropertyModifierTypeDescription
codereadonly| "storage/invalid-argument" | "storage/unknown" | "storage/object-not-found" | "storage/quota-exceeded" | "storage/unauthenticated" | "storage/unauthorized" | "storage/invalid-root-operation" | "storage/invalid-format" | "storage/canceled"Prefixed code, e.g. storage/object-not-found.

StorageProvisioningError

Pure-fetch client for the Firebase Storage provisioning APIs. Takes an OAuth access token directly — works equally from a Node agent runtime or a browser. Used by:

  • ProvisionStorageHandler server-side via the agent SDK
  • Consumers like the multi-tenant playground via direct import

The caller is responsible for token scope. firebase scope is enough for the :addFirebase + defaultLocation:finalize calls, but NOT for enabling the underlying firebasestorage.googleapis.com service (which is the first-time gate). Service-enable requires cloud-platform scope OR a service account with roles/serviceusage.serviceUsageAdmin. Each function below documents which scope it needs.

Endpoints under play:

  • serviceusage.googleapis.com/v1/projects/{p}/services/{s}:enable
  • firebase.googleapis.com/v1beta1/projects/{p}/defaultLocation:finalize
  • firebasestorage.googleapis.com/v1beta/projects/{p}/buckets
  • firebasestorage.googleapis.com/v1beta/projects/{p}/buckets/{b}:addFirebase
  • firebaserules.googleapis.com/v1/projects/{p}/releases/firebase.storage

Extends

  • Error

Constructors

Constructor
new StorageProvisioningError(
   status: number,
   body: string,
   reason: string,
   message: string): StorageProvisioningError;
Parameters
ParameterType
statusnumber
bodystring
reasonstring
messagestring
Returns

StorageProvisioningError

Overrides
Error.constructor

Properties

PropertyModifierType
bodyreadonlystring
reasonreadonlystring
statusreadonlynumber

Interfaces

CorsRule

A single CORS rule entry, mirroring the GCS bucket CORS schema. See https://cloud.google.com/storage/docs/cross-origin#cors-elements.

Properties

PropertyType
maxAgeSeconds?number
methodstring[]
originstring[]
responseHeader?string[]

EvaluationInput

Properties

PropertyType
requestStorageRequest
resourceStorageResource

EvaluationResult

Properties

PropertyTypeDescription
allowedboolean-
reasonsstring[]Human-readable explanation of why — used by Slice 8’s integration to populate storage/unauthorized error messages.

FirebaseStorage

Public opaque handle. Carries a Target via TARGET_SYMBOL; never inspected by consumer code, which interacts with storage only through ref and the operation free functions.

Properties

PropertyModifierType
[TARGET_SYMBOL]readonlySandboxTarget
app?readonlyFirebaseApp

FirebaseStorageBucket

Properties

PropertyType
bucketIdstring
namestring
reconciling?boolean

FirestoreLookup

Injected capability that lets a Storage rule read Firestore documents (firestore.get(path) / firestore.exists(path)), WITHOUT the pure evaluator importing the Firestore sandbox. The enforcement layer builds one from the sandbox’s admin Firestore accessor (a synchronous in-memory read) and passes it into evaluateStorageRules; pure/test callers that omit it get the deny-with-reason “unsupported” behavior instead.

Paths are the document path RELATIVE to the database — the collection/doc form sandbox.admin.getDocument expects — after the evaluator has stripped the /databases/<db>/documents/ prefix from the rule’s path literal.

Methods

exists()
exists(path: string): boolean;

Whether a document exists at path.

Parameters
ParameterType
pathstring
Returns

boolean

get()
get(path: string): Record<string, unknown>;

The document’s fields, or null when the document does not exist.

Parameters
ParameterType
pathstring
Returns

Record<string, unknown>


FullMetadata

Server-set + client-settable fields read back from uploadBytes / getMetadata / updateMetadata. Server-set fields (bucket, fullPath, name, generation, metageneration, timeCreated, updated, size) are populated by the upload pipeline; client-settable fields round-trip from SettableMetadata.

Extends

Properties

PropertyType
bucketstring
cacheControl?string
contentDisposition?string
contentEncoding?string
contentLanguage?string
contentType?string
customMetadata?{ [key: string]: string; }
fullPathstring
generationstring
md5Hash?string
metagenerationstring
namestring
sizenumber
timeCreatedstring
updatedstring

InspectStorageResult

Properties

PropertyType
buckets{ bucketId: string; name: string; }[]
defaultLocationstring
serviceState"enabled" | "disabled" | "unknown"

ListResult

Mirrors firebase/storage’s ListResult. nextPageToken is undefined for listAll; query pyric can-i-use storage/list for the current availability of the separate paginated operation.

Properties

PropertyType
itemsStorageReference[]
nextPageToken?string
prefixesStorageReference[]

ProvisionStorageInput

Shapes for the Storage provisioning + status tools.

Types only — the agent-tool parameter schemas live inline in tools.ts as JSON Schema (the ToolHandler contract).

Properties

PropertyTypeDescription
bucketId?stringOverride the default Firebase Storage bucket ID. Defaults to {projectId}.firebasestorage.app.
cors?{ maxAgeSeconds?: number; method: string[]; origin: string[]; responseHeader?: string[]; }[]CORS rules to apply to the bucket. Required for browser-side reads/writes from a non-Firebase origin. Omit to leave existing CORS untouched.
locationId?stringDefault GCP resources location to use when the project has not been finalized yet. IRREVERSIBLE once set. Common values: us-central, nam5, eur3. Default: us-central.
rules?stringStorage rules source to deploy after the bucket is linked. Optional; when omitted, whatever rules are currently released (possibly the deny-all default) stay in place.

ProvisionStorageOptions

Properties

PropertyTypeDescription
bucketId?stringOverride the default Firebase Storage bucket ID. Defaults to {projectId}.firebasestorage.app — the bucket Firebase Console creates automatically.
cors?CorsRule[]CORS rules to apply to the bucket after it’s linked. Required for browser-side reads/writes from a non-Firebase origin — buckets created via the Cloud Console (vs Firebase Console) often ship with no CORS configuration, which manifests as No 'Access-Control-Allow-Origin' header on the first XMLHttpRequest from a hosted page. Pass defaultPlaygroundCors(origin) for a sensible starter config, or a custom array. Omit to leave the bucket’s CORS alone.
locationId?stringDefault GCP resources location to use if the project hasn’t been finalized yet. Ignored when the location is already set. Default: 'us-central'.
onProgress?ProvisionProgressOptional progress callback, invoked at each provisioning step boundary.
rules?stringStorage rules source to deploy after the bucket is linked. When omitted, no rules are deployed (the project keeps whatever rules were last released — possibly the default deny-all).

ProvisionStorageResult

Properties

PropertyType
bucketCreatedboolean
bucketIdstring
corsAppliedboolean
locationFinalizedboolean
locationIdstring
oktrue
rulesDeployedboolean
rulesetName?string
serviceEnabledboolean

SandboxTarget

Sandbox target — IDB-backed, identity from SandboxContext, rules enforced in-process via enforce.ts.

Properties

PropertyModifierTypeDescription
admin?readonlybooleanRules-bypass admin plane. true only on handles minted by the INTERNAL getAdminStorageSandbox factory (exported via pyric/storage/internal, never the public surface): operations on an admin handle skip rule evaluation entirely — the storage mirror of getAdminFirestore / getAdminDatabase. The public modular surface stays rules-honest; this exists so hosts (the SharedWorker’s actAs: { mode: 'admin' } lens) can serve firebase-admin semantics against the same shared store.
bucketreadonlystring-
contextreadonlySandboxContext-
currentAuth?readonly() => { token?: Record<string, unknown>; uid: string; }App handles resolve auth at operation time; explicit contexts stay frozen.
kindreadonly"sandbox"-
sandboxreadonlySandbox-
servicePromisereadonlyPromise<StorageService>-

SettableMetadata

Client-settable fields. Passed to uploadBytes / uploadString / updateMetadata. Every field is optional — the upload pipeline fills any unsupplied client fields with sane defaults (e.g. contentType falls back to application/octet-stream).

Extended by

Properties

PropertyType
cacheControl?string
contentDisposition?string
contentEncoding?string
contentLanguage?string
contentType?string
customMetadata?{ [key: string]: string; }

StorageAdminToolDeps

Properties

PropertyTypeDescription
scopeProjectScopeProject identity + token resolver.

StorageAuth

Identity passed in with the request. null is anonymous.

Properties

PropertyType
token?Record<string, unknown>
uidstring

StorageOptions

Options for getStorageSandbox.

Properties

PropertyTypeDescription
bucket?stringBucket identifier recorded on uploaded metadata. v1 has a single implicit bucket and does not enforce cross-bucket isolation — passing different values per call is accepted and round-trips in metadata, but the data store is shared.
dbName?stringOverride the IndexedDB database name. Tests pass per-case unique names so state doesn’t leak between runs. Only takes effect on the FIRST call per Sandbox.
projectId?stringProject identity used to derive the default IndexedDB database name (pyric-storage:<projectId> — see storageDbName). IndexedDB is origin-scoped, so without this every project served on the same localhost port shared one storage database (issue #359). Ignored when an explicit dbName is given; only honored on the FIRST call per Sandbox. Hosts pass their project identity here (pyric dev passes the served project’s key; app handles pass options.projectId).
rules?stringStorage rules source. Parsed eagerly so a malformed string throws at config time. Only honored on the FIRST call per Sandbox.

StorageReference

Public reference shape. Methods are inherited from the impl classes below; the interface is exported so consumer code can name the type without depending on the impls.

Properties

PropertyModifierType
bucketreadonlystring
fullPathreadonlystring
namereadonlystring
parentreadonlyStorageReference
rootreadonlyStorageReference
storagereadonlyFirebaseStorage

Methods

toString()
toString(): string;
Returns

string


StorageRequest

Inbound request bindings the rules see.

Properties

PropertyTypeDescription
authStorageAuth-
methodStorageRequestMethod-
pathstringPath of the object the request targets.
resource?{ contentType?: string; metadata?: Record<string, string>; size: number; }Per-Firebase: on writes, request.resource describes the about-to-write object. Omit for reads (the rules language treats request.resource as unset there).
resource.contentType?string-
resource.metadata?Record<string, string>-
resource.sizenumber-

StorageResource

Existing-object bindings (for resource.*). null when no object exists yet (creates).

The object-identity/time fields carry GOOGLE CLOUD STORAGE semantics, not the client SDK’s FullMetadata semantics — the two disagree on name:

  • rules resource.name is the object’s FULL path within the bucket (uploads/pic.png), the GCS object-name convention. The client SDK’s FullMetadata.name is the LAST path segment (pic.png). The adapter (resourceFromStored) therefore sources name from the persisted record’s fullPath, NOT its name.
  • timeCreated / updated are ISO-8601 strings here (the persisted shape); the evaluator converts them to epoch millis when it builds the binding, so they compare numerically against request.time and against each other. Production types them as timestamp and rejects an int in their place (“Received: int < timestamp”).
  • The update-time field is updated. There is NO resource.timeUpdated in the Storage rules language.

A field left undefined reads as ABSENT, which production treats as an evaluation error that denies (see RuleError).

Properties

PropertyTypeDescription
bucket?stringBucket the object lives in.
contentType?string-
generation?numberContent generation (production types it int).
metadata?Record<string, string>-
metageneration?numberMetadata generation (production types it int).
name?stringFull object path within the bucket, e.g. uploads/pic.png.
sizenumber-
timeCreated?stringISO-8601 creation time.
updated?stringISO-8601 time of the most recent content/metadata update.

StorageRules

Opaque parsed-rules handle returned by parseStorageRules.


UploadResult

Return shape of uploadBytes / uploadString.

Properties

PropertyType
metadataFullMetadata
refStorageReference

UploadTask

Extends

Properties

PropertyModifierType
snapshotreadonlyUploadTaskSnapshot

Methods

cancel()
cancel(): boolean;
Returns

boolean

on()
on(
   event: string,
   nextOrObserver?:
  | (snapshot: UploadTaskSnapshot) => unknown
  | {
  complete?: () => unknown;
  error?: (error: Error | StorageError) => unknown;
  next?: (snapshot: UploadTaskSnapshot) => unknown;
},
   error?: (error: Error | StorageError) => unknown,
   complete?: () => unknown): () => void;
Parameters
ParameterType
eventstring
nextOrObserver?| (snapshot: UploadTaskSnapshot) => unknown | { complete?: () => unknown; error?: (error: Error | StorageError) => unknown; next?: (snapshot: UploadTaskSnapshot) => unknown; }
error?(error: Error | StorageError) => unknown
complete?() => unknown
Returns
(): void;
Returns

void

pause()
pause(): boolean;
Returns

boolean

resume()
resume(): boolean;
Returns

boolean


UploadTaskSnapshot

Properties

PropertyModifierType
bytesTransferredreadonlynumber
metadatareadonlyFullMetadata
refreadonlyStorageReference
statereadonlyTaskState
taskreadonlyUploadTask
totalBytesreadonlynumber

Type Aliases

ProvisionStorageErrorCode

type ProvisionStorageErrorCode =
  | "PERMISSION_DENIED"
  | "SERVICE_DISABLED"
  | "LOCATION_FINALIZE_FAILED"
  | "BUCKET_CREATE_FAILED"
  | "RULES_DEPLOY_FAILED"
  | "CORS_UPDATE_FAILED"
  | "UNKNOWN";

ProvisionStorageOutcome

type ProvisionStorageOutcome =
  | {
  bucketCreated: boolean;
  bucketId: string;
  corsApplied: boolean;
  locationFinalized: boolean;
  locationId: string | null;
  rulesDeployed: boolean;
  rulesetName?: string;
  serviceEnabled: boolean;
  success: true;
}
  | {
  error: {
     code: ProvisionStorageErrorCode;
     message: string;
     recoverable: boolean;
  };
  success: false;
};

ServiceEnableState

type ServiceEnableState = "enabled" | "disabled" | "unknown";

StorageErrorCode

type StorageErrorCode =
  | "unknown"
  | "object-not-found"
  | "quota-exceeded"
  | "unauthenticated"
  | "unauthorized"
  | "invalid-root-operation"
  | "invalid-format"
  | "invalid-argument"
  | "canceled";

The unprefixed storage error codes the sandbox can raise. Mirrors the subset of StorageErrorCode used by currently implemented operations.


StorageGrantVerb

type StorageGrantVerb = StorageMethod | StorageVerb;

A verb token that may appear in an allow clause.


StorageMethod

type StorageMethod = "read" | "write";

Coarse permission umbrellas. read covers get + list; write covers create + update + delete.


StorageRequestMethod

type StorageRequestMethod = StorageMethod | StorageVerb;

What a caller records as the request’s operation. Callers pass the precise granular verb; the coarse forms remain accepted so the umbrella semantics are symmetric.


StorageVerb

type StorageVerb = "get" | "list" | "create" | "update" | "delete";

Granular operation verbs. Production Storage maps each operation to exactly one of these: download / getMetadata → get list → list upload to NONEXISTENT path → create upload / updateMetadata over an EXISTING object → update delete → delete


StringFormat

type StringFormat = "raw" | "base64" | "data_url";

uploadString format selector.


Target

type Target = SandboxTarget;

TaskEvent

type TaskEvent = "state_changed";

TaskState

type TaskState = "running" | "paused" | "success" | "canceled" | "error";

Variables

TARGET_SYMBOL

const TARGET_SYMBOL: unique symbol;

Hidden property on every FirebaseStorage handle. Carries the sandbox state free functions share without exposing it publicly.

Functions

addFirebaseToBucket()

function addFirebaseToBucket(
   accessToken: string,
   projectId: string,
bucketId: string): Promise<FirebaseStorageBucket>;

Link a Cloud Storage bucket to Firebase Storage. Idempotent — if the bucket is already Firebase-linked, the API returns 200 with the existing record. The bucket must already exist as a GCS resource; for the default Firebase bucket name ({projectId}.firebasestorage.app), Firebase auto-creates it on first :addFirebase call.

Parameters

ParameterType
accessTokenstring
projectIdstring
bucketIdstring

Returns

Promise<FirebaseStorageBucket>


connectStorageEmulator()

function connectStorageEmulator(
   _storage: FirebaseStorage,
   _host: string,
   _port: number,
   _options?: {
  mockUserToken?: string | Record<string, unknown>;
}): void;

Accepted no-op because the selected Storage backend already is local.

Parameters

ParameterType
_storageFirebaseStorage
_hoststring
_portnumber
_options?{ mockUserToken?: string | Record<string, unknown>; }
_options.mockUserToken?string | Record<string, unknown>

Returns

void


createStorageAdminTools()

function createStorageAdminTools(deps: StorageAdminToolDeps): ToolHandler<unknown, unknown>[];

Bundles:

  • storage_get_status
  • storage_provision

Parameters

ParameterType
depsStorageAdminToolDeps

Returns

ToolHandler<unknown, unknown>[]


defaultPlaygroundCors()

function defaultPlaygroundCors(hostingOrigin: string): CorsRule[];

Default rule for a browser playground hosted on Firebase Hosting. Allows GET/POST/PUT/DELETE/HEAD/OPTIONS from the Hosting origin

  • common localhost dev ports, with response headers needed by the Firebase Storage Web SDK.

Parameters

ParameterType
hostingOriginstring

Returns

CorsRule[]


deleteObject()

function deleteObject(ref: StorageReference, provenance?: EventProvenance): Promise<void>;

Delete the object at ref — removes both the blob and the metadata atomically. No-op when the path doesn’t exist (the persistence layer’s delete is no-op on missing keys).

NOTE: the JS SDK’s deleteObject throws storage/object-not-found when the path is missing. The v1 scope keeps the persistence-layer no-op behavior for now; Slice 8 will reconsider whether to mirror the strict throw.

provenance (host-only): op EventProvenance bound at ISSUE time, threaded EXPLICITLY onto the emitted object_delete event. The delete awaits the backend before emitting, so it escapes the sandbox’s synchronous ambient-provenance window — see the note on uploadBytes.

Parameters

ParameterType
refStorageReference
provenance?EventProvenance

Returns

Promise<void>


deployStorageRules()

function deployStorageRules(
   accessToken: string,
   projectId: string,
   source: string,
   bucketId?: string): Promise<{
  rulesetName: string;
}>;

Deploy a Storage rules source for a specific bucket. Firebase Storage uses per-bucket release names — projects/{p}/releases/firebase.storage/{bucketId} — for actual rule application. The project-wide firebase.storage release exists as a legacy alias but isn’t bound to any bucket in modern projects; deploying to it leaves the bucket’s deny-all rule unchanged.

Defaults bucketId to {projectId}.firebasestorage.app (the Firebase default bucket name). Pass an override when targeting a non-default bucket.

Parameters

ParameterType
accessTokenstring
projectIdstring
sourcestring
bucketId?string

Returns

Promise<{ rulesetName: string; }>


enableStorageService()

function enableStorageService(accessToken: string, projectId: string): Promise<void>;

Enable firebasestorage.googleapis.com on the project. Requires serviceusage.services.enable IAM permission — included in roles/owner, roles/editor (deprecated), or roles/serviceusage.serviceUsageAdmin. The default Firebase Admin SDK service account does NOT have this; the caller’s token must either be a user-OAuth with cloud-platform scope or a SA with the elevated role.

Long-running operation under the hood; the response carries an operation name. We don’t poll — the response 200 is enough signal for our purposes, and a brief settle delay handles propagation.

Parameters

ParameterType
accessTokenstring
projectIdstring

Returns

Promise<void>


evaluateStorageRules()

function evaluateStorageRules(
   rules: StorageRules,
   input: EvaluationInput,
   now?: Date,
   firestoreLookup?: FirestoreLookup): EvaluationResult;

Parameters

ParameterType
rulesStorageRules
inputEvaluationInput
now?Date
firestoreLookup?FirestoreLookup

Returns

EvaluationResult


finalizeDefaultLocation()

function finalizeDefaultLocation(
   accessToken: string,
   projectId: string,
locationId: string): Promise<void>;

Set the project’s default GCP resources location. IRREVERSIBLE — once set, the location cannot be changed. Skip-if-set is the caller’s job; this function unconditionally calls :finalize.

Per observed behavior, :finalize 404s on projects that already have resources provisioned (RTDB, Hosting) without a default location. The error path surfaces that to the caller.

Parameters

ParameterType
accessTokenstring
projectIdstring
locationIdstring

Returns

Promise<void>


getBlob()

function getBlob(ref: StorageReference, maxDownloadSizeBytes?: number): Promise<Blob>;

Read the blob at ref and return it as a Blob. Same semantics as getBytes but skips the arrayBuffer() conversion when the caller wants a Blob directly (e.g. for streaming or URL.createObjectURL). Note: this is the browser-side counterpart of the JS SDK’s getBlob — the v1 scope doesn’t ship a Node-stream variant.

Parameters

ParameterType
refStorageReference
maxDownloadSizeBytes?number

Returns

Promise<Blob>


getBucketCors()

function getBucketCors(accessToken: string, bucketId: string): Promise<CorsRule[]>;

Read the current CORS configuration for a bucket.

Parameters

ParameterType
accessTokenstring
bucketIdstring

Returns

Promise<CorsRule[]>


getBytes()

function getBytes(ref: StorageReference, maxDownloadSizeBytes?: number): Promise<ArrayBuffer>;

Read the blob at ref and return its contents as an ArrayBuffer. Honors the optional maxDownloadSizeBytes cap by truncating to that length.

Parameters

ParameterType
refStorageReference
maxDownloadSizeBytes?number

Returns

Promise<ArrayBuffer>


getDefaultLocation()

function getDefaultLocation(accessToken: string, projectId: string): Promise<string>;

Read the project’s current default GCP resources location. Returns null when the project hasn’t been finalized yet — e.g. brand-new Firebase projects with no resources. firebase scope is sufficient.

Parameters

ParameterType
accessTokenstring
projectIdstring

Returns

Promise<string>


getDownloadURL()

function getDownloadURL(ref: StorageReference): Promise<string>;

Return a URL the current page can use to read the sandbox object. The URL is created from the same rules-checked blob as getBlob. It is a snapshot, cannot be shared outside the page, and stays alive until the caller revokes it or the page unloads.

Parameters

ParameterType
refStorageReference

Returns

Promise<string>


getMetadata()

function getMetadata(ref: StorageReference): Promise<FullMetadata>;

Read the full metadata record at ref. Throws when no object exists at the path (storage/object-not-found).

Mirrors firebase/storage’s getMetadata. Returns the same FullMetadata shape uploadBytes produced — server-set fields pinned at upload time, client-settable fields whatever the latest write left them as.

Parameters

ParameterType
refStorageReference

Returns

Promise<FullMetadata>


getStorage()

function getStorage(app?: FirebaseApp, bucketUrl?: string): AppFirebaseStorage;

Resolve the Firebase-shaped Storage service associated with an app.

Parameters

ParameterType
app?FirebaseApp
bucketUrl?string

Returns

AppFirebaseStorage


getStorageSandbox()

function getStorageSandbox(target:
  | Sandbox
  | SandboxContext, options?: StorageOptions): FirebaseStorage;

Construct (or return cached) a sandbox-backed FirebaseStorage handle. Accepts either a bare Sandbox (anonymous identity wired up via sandbox.withAuth(null)) or an explicit SandboxContext. Idempotent on SandboxContext identity.

Parameters

ParameterType
target| Sandbox | SandboxContext
options?StorageOptions

Returns

FirebaseStorage


getStorageServiceState()

function getStorageServiceState(accessToken: string, projectId: string): Promise<ServiceEnableState>;

Probe whether the firebasestorage.googleapis.com service is enabled on the project. Cheap, uses Service Usage GET. Requires serviceusage.services.get permission (the default Firebase Admin SDK SA has this; user OAuth tokens with firebase scope do not).

Returns 'unknown' on permission failures so callers can downgrade to “try the operation; observe SERVICE_DISABLED” rather than block.

Parameters

ParameterType
accessTokenstring
projectIdstring

Returns

Promise<ServiceEnableState>


listAll()

function listAll(refIn: StorageReference): Promise<ListResult>;

Enumerate every immediate child item + sub-prefix under refIn. Works on the root reference too — pass ref(storage) to scan the whole bucket.

Parameters

ParameterType
refInStorageReference

Returns

Promise<ListResult>


listFirebaseBuckets()

function listFirebaseBuckets(accessToken: string, projectId: string): Promise<FirebaseStorageBucket[]>;

List Firebase-linked Storage buckets on the project. Returns an empty list when none exist yet. Throws when the underlying service is disabled — callers should check getStorageServiceState first if they want to distinguish.

Parameters

ParameterType
accessTokenstring
projectIdstring

Returns

Promise<FirebaseStorageBucket[]>


parseStorageRules()

function parseStorageRules(source: string): StorageRules;

Parse a Storage rules source into an opaque handle. Throws SyntaxError on malformed input. Used by Slice 8’s getStorage(ctx, { rules }) to validate upfront.

Parameters

ParameterType
sourcestring

Returns

StorageRules


provisionStorage()

function provisionStorage(
   accessToken: string,
   projectId: string,
options?: ProvisionStorageOptions): Promise<ProvisionStorageResult>;

End-to-end Storage enablement + provisioning. Each step is idempotent (probe before mutating); the result reports what was actually done.

Permission requirements (caller’s token):

  • roles/serviceusage.serviceUsageAdmin (or Owner) — to enable the service when it’s disabled
  • cloud-platform OAuth scope (or firebase if service already enabled)

The handler throws StorageProvisioningError with the underlying reason (e.g. AUTH_PERMISSION_DENIED, SERVICE_DISABLED) so the caller can route to actionable UX.

Parameters

ParameterType
accessTokenstring
projectIdstring
options?ProvisionStorageOptions

Returns

Promise<ProvisionStorageResult>


ref()

Call Signature

function ref(storage: FirebaseStorage, path?: string): StorageReference;

Construct a reference. Two overloads matching Firebase:

ref(storage, path?)path is bucket-rooted. Omit for root. ref(parent, path)path is relative to parent.fullPath.

Parameters
ParameterType
storageFirebaseStorage
path?string
Returns

StorageReference

Call Signature

function ref(parent: StorageReference, path: string): StorageReference;

Construct a reference. Two overloads matching Firebase:

ref(storage, path?)path is bucket-rooted. Omit for root. ref(parent, path)path is relative to parent.fullPath.

Parameters
ParameterType
parentStorageReference
pathstring
Returns

StorageReference


setBucketCors()

function setBucketCors(
   accessToken: string,
   bucketId: string,
cors: CorsRule[]): Promise<void>;

Replace the bucket’s CORS configuration. Pass an empty array to clear all rules. The GCS API replaces (not merges) the cors field on PATCH.

Parameters

ParameterType
accessTokenstring
bucketIdstring
corsCorsRule[]

Returns

Promise<void>


updateMetadata()

function updateMetadata(
   ref: StorageReference,
   patch: SettableMetadata,
provenance?: EventProvenance): Promise<FullMetadata>;

Update the client-settable metadata at ref. Server-set fields (bucket, fullPath, name, generation, timeCreated, size, md5Hash) are preserved; metageneration bumps and updated refreshes. The blob is untouched.

Pass undefined for a field to leave the previous value in place. To explicitly clear a field, the JS SDK accepts null — we don’t model that in the v1 scope to keep the patch logic simple. Documented for Slice 9’s deferred-features section.

provenance (host-only): op EventProvenance bound at ISSUE time, threaded EXPLICITLY onto the emitted metadata_update event. Emit runs after the backend awaits, escaping the sandbox’s synchronous ambient-provenance window — see the note on uploadBytes.

Parameters

ParameterType
refStorageReference
patchSettableMetadata
provenance?EventProvenance

Returns

Promise<FullMetadata>


uploadBytes()

function uploadBytes(
   ref: StorageReference,
   data: ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob,
   metadata?: SettableMetadata,
provenance?: EventProvenance): Promise<UploadResult>;

Upload bytes to the reference’s fullPath. Replaces any existing object at the path. Returns the populated FullMetadata and the same ref for chaining.

Throws when the reference targets the root (fullPath === '') — uploads need a non-empty path, matching Firebase’s invalid-root-operation precondition.

Provenance is captured from the reference’s operation-scoped Storage handle before the first await. The optional provenance argument remains as a compatibility override for internal callers. Either way, concurrent uploads cannot exchange source or auth-lens identity, and service: 'storage' always wins.

Parameters

ParameterType
refStorageReference
dataArrayBuffer | Uint8Array<ArrayBufferLike> | Blob
metadata?SettableMetadata
provenance?EventProvenance

Returns

Promise<UploadResult>


uploadBytesResumable()

function uploadBytesResumable(
   ref: StorageReference,
   data: ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob,
   metadata?: SettableMetadata,
   provenance?: EventProvenance): UploadTask;

Start a resumable upload of data to ref. Returns an UploadTask that emits synthetic progress events over microtasks before completing the storage write.

Parameters

ParameterType
refStorageReference
dataArrayBuffer | Uint8Array<ArrayBufferLike> | Blob
metadata?SettableMetadata
provenance?EventProvenance

Returns

UploadTask


uploadString()

function uploadString(
   ref: StorageReference,
   value: string,
   format?: StringFormat,
   metadata?: SettableMetadata,
provenance?: EventProvenance): Promise<UploadResult>;

Upload a string in one of three formats:

  • raw (default): UTF-8 text. Defaults contentType to text/plain;charset=utf-8 if neither metadata nor the data specify one.
  • base64: standard base64-encoded bytes.
  • data_url: a data: URL — the MIME prefix is honored as contentType unless the caller overrides it explicitly.

Parameters

ParameterType
refStorageReference
valuestring
format?StringFormat
metadata?SettableMetadata
provenance?EventProvenance

Returns

Promise<UploadResult>