cozy-stack-client.md

June 15, 2026 · View on GitHub

Classes

AppCollection

Extends DocumentCollection API along with specific methods for io.cozy.apps.

AppsRegistryCollection

Extends DocumentCollection API along with specific methods for io.cozy.apps_registry.

Collection

Utility class to abstract an regroup identical methods and logics for specific collections.

CozyStackClient

Main API against the cozy-stack server.

DocumentCollection

Abstracts a collection of documents of the same doctype, providing CRUD methods and other helpers.

FileCollection

Implements DocumentCollection API along with specific methods for io.cozy.files.

Files are a special type of documents and are handled differently by the stack: special routes are to be used, and there is a notion of referenced files, aka files associated to a specific document

NotesCollection

Implements DocumentCollection API to interact with the /notes endpoint of the stack

OAuthClient

Specialized CozyStackClient for mobile, implementing stack registration through OAuth.

OAuthClientsCollection

Implements DocumentCollection API to interact with the /settings/clients endpoint of the stack

PermissionCollection

Implements DocumentCollection API along with specific methods for io.cozy.permissions.

PromiseCache

Caches promises while they are pending Serves to dedupe equal queries requested at the same time

SettingsCollection

Implements DocumentCollection API to interact with the /settings endpoint of the stack

SharingCollection

Implements the DocumentCollection API along with specific methods for io.cozy.sharings.

ShortcutsCollection

Provides helpers to interact with shortcuts documents on the Cozy stack.

TriggerCollection

Implements DocumentCollection API along with specific methods for io.cozy.triggers.

Constants

dontThrowNotFoundErrorobject

Handler for error response which return a empty value for "not found" error

isIndexNotFoundErrorArray | null

Helper to identify an index not found error

isIndexConflictErrorArray | null

Helper to identify an index conflict

isIndexNotUsedWarningArray | null

Helper to identify a not used index

isNoUsableIndexErrorArray | null

Helper to identify a no usable index error

isTimeoutErrorArray | null

Helper to identify timeout error See cozy-stack's timeout value for couchdb request: https://github.com/cozy/cozy-stack/blob/669cd694132388ef6b7d1a58cf3d1b5dfb52896a/pkg/config/config/config.go#L963

isDocumentUpdateConflictArray | null

Helper to identify a document conflict

isFileboolean

Returns true when parameter has type directory, file or has _type io.cozy.files

isDirectoryboolean

Returns true when parameters has type directory

getIllegalCharactersstring

Get the list of illegal characters in the file name

makeKeyFromPartialFilterstring

Process a partial filter to generate a string key

/!\ Warning: this method is similar to cozy-pouch-link mango.makeKeyFromPartialFilter() If you edit this method, please check if the change is also needed in mango file

getIndexNameFromFieldsstring

Name an index, based on its indexed fields and partial filter.

It follows this naming convention: by_{indexed_field1}_and_{indexed_field2}_filter_({partial_filter.key1}_{partial_filter.value1})_and_({partial_filter.key2}_{partial_filter.value2})

/!\ Warning: this method is similar to cozy-pouch-link mango.getIndexNameFromFields() If you edit this method, please check if the change is also needed in mango file

transformSortMangoSort

Transform sort into Array

getIndexFieldsArray

Compute fields that should be indexed for a mango query to work

isMatchingIndexboolean

Check if an index is matching the given fields

makeOperatorsExplicitobject

Transform a query to make all operators explicit

getPermissionsForobject

Build a permission set

normalizeSettingsobject

Normalizing a document for SettingsCollection context

getSharingRulesArray.<Rule>

Rules determine the behavior of the sharing when changes are made to the shared document See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing

SHORTCUTS_DOCTYPE : string

Doctype for shortcuts documents.

forceDownload

Force a download from the given href

encodePathstring

Encode a path for use in a URL by encoding special characters but keeping slashes

sharedDriveApiPrefixstring

Returns a FileCollection API prefix for manipulating a shared drive's files.

Functions

getAccessToken()string

Get the access token string

getAccessToken()string

Get the app token string

getIconURL()

Get Icon URL using blob mechanism if OAuth connected or using preloaded url when blob not needed

handleNorOperator(conditions)Array

Handle the $nor operator in a query CouchDB transforms $nor into $and with $ne operators

sortObjectByKey(a, b)number

Compares two objects based on their first key to determine their order.

garbageCollect()

Delete outdated results from cache

memoize()

Memoize with maxDuration and custom key

normalizeDoctypeJsonApi(doctype)function

Normalizes a document in JSON API format for a specific doctype

getSharingRulesForPhotosAlbum(document)Array.<Rule>

Compute the rules that define how to share a Photo Album. See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing

getSharingPolicyForReferencedFiles()SharingPolicy

Compute the sharing policy for a ReferencedFile based on its sharing type

getSharingPolicyForAlbum()Array.<Rule>

Compute the sharing policy for an Album based on its sharing type

getSharingRulesForFile(document)Array.<Rule>

Compute the rules that define how to share a File. See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing

getSharingRulesForSharedDrive(document)Array.<Rule>

Compute the rules that define a shared drive.

getSharingPolicyForFile(document)SharingPolicy

Compute the sharing policy for a File based on its sharing type

getSharingRulesForOrganizations(document)Array.<Rule>

Compute the rules that define how to share an Organization. See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing

toRelationshipItem(item)RelationshipItem

Compute the RelationshipItem that can be referenced as a sharing recipient

getCozyURL()

Get a uniform formatted URL and SSL information according to a provided URL

joinPath(start, end)string

Join two paths together ensuring there is only one slash between them

Typedefs

FetchChangesReturnValuePromise.<FetchChangesReturnValue>

Use Couch _changes API Deleted and design docs are filtered by default, thus documents are retrieved in the response (include_docs is set to true in the parameters of _changes).

You should use fetchChangesRaw to have low level control on _changes parameters.

CozyStackClient : module:"./CozyStackClient.js"
IOCozyFolder : object

Folder

SpecificFileAttributesForKonnector : object

Specific file attributes for creation for konnector

CouchDBViewCursor : Array.<string> | string

Cursor used for Mango queries pagination

DirectoryAttributes : object

Attributes used for directory creation

FileAttributes : object

Attributes used for file creation

FileDocument : object

Document representing a io.cozy.files

Stream : object

Stream is not defined in a browser, but is on NodeJS environment

OAuthClient : object

Document representing a io.cozy.oauth.clients

FileCollectionOptions : object

Options that can be passed to FileCollection's constructor

ArchivePages : object

Attributes used for create archive link by ids

FetchChangesReturnValueFetchChangesReturnValue

Use cozy-stack's _changes API for io.cozy.files Design docs are filtered by default, thus documents are retrieved in the response (includeDocs is set to true in the parameters of _changes). Deleted and trashed documents can be filtered on demand and files' paths can be requested as well.

Since deleted and trashed documents are skipped by cozy-stack rather than CouchDB, when either option is set to true, the response can contain less documents than the defined limit. Thus one should rely solely on the pending result attribute to determine if more documents can be fetched or not.

You should use fetchChangesRaw to call CouchDB's _changes API.

JobDocument : object

Document representing a io.cozy.jobs

MangoPartialFilter : Object
MangoSelector : object
MangoSort : Array.<object>
MangoQueryOptions : object
DesignDoc : object

Attributes representing a design doc

CozyStackClient : module:"./CozyStackClient.js"
NotesCollectionOptions : object

Options that can be passed to NotesCollection's constructor

SessionCode : string
SessionCodeRes
AccessTokenRes
TwoFactorNeededRes
PermissionCollectionOptions : object

Options that can be passed to PermissionCollection's constructor

PermissionPermission

async getOwnPermissions - deprecated: please use fetchOwnPermissions instead

PermissionPermission

async fetchOwnPermissions - Fetches permissions

Rule : object

A sharing rule

SharingRulesOptions : object
Recipient : object

An io.cozy.contact

Sharing : object

An io.cozy.sharings document

SharingPolicy : object

Define the add/update/remove policies for a sharing

SharingType : undefined | 'one-way' | 'two-way'

Define how a document is synced between sharing's owner and receivers.

RelationshipItem : object

Define a recipient that can be used as target of a sharing

CozyStackClient : object

AppCollection

Extends DocumentCollection API along with specific methods for io.cozy.apps.

Kind: global class

appCollection.all() ⇒ Object

Lists all apps, without filters.

The returned documents are not paginated by the stack.

Kind: instance method of AppCollection
Returns: Object - The JSON API conformant response.
Throws:

  • FetchError

AppsRegistryCollection

Extends DocumentCollection API along with specific methods for io.cozy.apps_registry.

Kind: global class

appsRegistryCollection.get(slug) ⇒ Promise.<{data: object}>

Fetches an app from the registry.

Kind: instance method of AppsRegistryCollection
Returns: Promise.<{data: object}> - JsonAPI response containing normalized document as data attribute
Throws:

  • FetchError
ParamTypeDescription
slugstringSlug of the app

Collection

Utility class to abstract an regroup identical methods and logics for specific collections.

Kind: global class

Collection.get(stackClient, endpoint, options) ⇒ Promise.<object>

Utility method aimed to return only one document.

Kind: static method of Collection
Returns: Promise.<object> - JsonAPI response containing normalized document as data attribute

ParamTypeDefaultDescription
stackClientCozyStackClientCozyStackClient
endpointstringStack endpoint
optionsobjectOptions of the collection
options.normalizefunctionCallback to normalize response data (default data => data)
[options.method]string"GET"HTTP method

CozyStackClient

Main API against the cozy-stack server.

Kind: global class

cozyStackClient.collection(doctype, options) ⇒ DocumentCollection

Creates a DocumentCollection instance.

Kind: instance method of CozyStackClient

ParamTypeDescription
doctypestringThe collection doctype.
optionsobjectOptions to pass to the collection.

cozyStackClient.fetch(method, path, [body], [opts]) ⇒ object

Fetches an endpoint in an authorized way.

Kind: instance method of CozyStackClient
Throws:

  • FetchError
ParamTypeDefaultDescription
methodstringThe HTTP method.
pathstringThe URI.
[body]objectThe payload.
[opts]object{}Options for fetch

cozyStackClient.refreshToken() ⇒ Promise

Retrieves a new app token by refreshing the currently used token.

Kind: instance method of CozyStackClient
Returns: Promise - A promise that resolves with a new AccessToken object
Throws:

  • Error The client should already have an access token to use this function
  • Error The client couldn't fetch a new token

cozyStackClient.fetchJSON(method, path, body, options) ⇒ object

Fetches JSON in an authorized way.

Kind: instance method of CozyStackClient
Throws:

  • FetchError
ParamTypeDescription
methodstringThe HTTP method.
pathstringThe URI.
bodyobjectThe payload.
optionsobjectOptions

cozyStackClient.setToken(token)

Change or set the API token

Kind: instance method of CozyStackClient

ParamTypeDescription
tokenstring | AppToken | AccessTokenStack API token

cozyStackClient.getAccessToken() ⇒ string

Get the access token string, being an oauth token or an app token

Kind: instance method of CozyStackClient
Returns: string - token

DocumentCollection

Abstracts a collection of documents of the same doctype, providing CRUD methods and other helpers.

Kind: global class

documentCollection.all(options) ⇒ Promise.<{data, meta, skip, bookmark, next}>

Lists all documents of the collection, without filters.

The returned documents are paginated by the stack.

Kind: instance method of DocumentCollection
Returns: Promise.<{data, meta, skip, bookmark, next}> - The JSON API conformant response.
Throws:

  • FetchError
ParamTypeDefaultDescription
optionsobjectThe fetch options: pagination & fetch of specific docs.
[options.limit]number | null100Pagination limit
[options.skip]number0Pagination Skip
[options.bookmark]stringPagination bookmark
[options.keys]Array.<string>Keys to query

documentCollection.fetchDocumentsWithMango(path, selector, options)

Fetch Documents with Mango

Kind: instance method of DocumentCollection

ParamTypeDescription
pathstringpath to fetch
selectorMangoSelectorselector
optionsMangoQueryOptionsrequest options

documentCollection.findWithMango(path, selector, options) ⇒ Promise.<object>

Find documents with the mango selector and create index if missing.

We adopt an optimistic approach for index creation: we run the query first, and only if an index missing error is returned, the index is created and the query run again.

Kind: instance method of DocumentCollection
Returns: Promise.<object> - - The find response
Access: protected

ParamTypeDescription
pathstringThe route path
selectorMangoSelectorThe mango selector
optionsMangoQueryOptionsThe find options

documentCollection.find(selector, options) ⇒ Promise.<{data, skip, bookmark, next, execution_stats}>

Returns a filtered list of documents using a Mango selector.

The returned documents are paginated by the stack.

Kind: instance method of DocumentCollection
Returns: Promise.<{data, skip, bookmark, next, execution_stats}> - The JSON API conformant response.
Throws:

  • FetchError
ParamTypeDescription
selectorMangoSelectorThe Mango selector.
optionsMangoQueryOptionsMangoQueryOptions

documentCollection.findAll(selector, options) ⇒ Promise.<Array.<{data}>>

Returns a filtered list with all documents using a Mango selector, automatically fetching more documents if the total of documents is superior to the pagination limit. Can result in a lot of network requests.

The returned documents are paginated by the stack.

Kind: instance method of DocumentCollection
Returns: Promise.<Array.<{data}>> - Documents fetched
Throws:

  • FetchError
ParamTypeDescription
selectorMangoSelectorThe Mango selector.
optionsMangoQueryOptionsMangoQueryOptions

documentCollection.get(id) ⇒ Promise.<object>

Get a document by id

Kind: instance method of DocumentCollection
Returns: Promise.<object> - JsonAPI response containing normalized document as data attribute

ParamTypeDescription
idstringThe document id.

documentCollection.getAll()

Get many documents by id

Kind: instance method of DocumentCollection

documentCollection.create(doc)

Creates a document

Kind: instance method of DocumentCollection

ParamTypeDescription
docobjectDocument to create. Optional: you can force the id with the _id attribute

documentCollection.update(document)

Updates a document

Kind: instance method of DocumentCollection

ParamTypeDescription
documentobjectDocument to update. Do not forget the _id attribute

documentCollection.destroy(doc)

Destroys a document

Kind: instance method of DocumentCollection

ParamTypeDescription
docobjectDocument to destroy. Do not forget _id and _rev attributes

documentCollection.updateAll(rawDocs)

Updates several documents in one batch

Kind: instance method of DocumentCollection

ParamTypeDescription
rawDocsArray.<Document>Documents to be updated

documentCollection.destroyAll(docs)

Deletes several documents in one batch

Kind: instance method of DocumentCollection

ParamTypeDescription
docsArray.<Document>Documents to delete

documentCollection.toMangoOptions(selector, options) ⇒ MangoQueryOptions

Returns Mango Options from Selector and Options

Kind: instance method of DocumentCollection
Returns: MangoQueryOptions - Mango options

ParamTypeDescription
selectorMangoSelectorMango selector
optionsMangoQueryOptionsMango Options

documentCollection.createIndex(fields, indexOption) ⇒ Promise.<{id, fields}>

Kind: instance method of DocumentCollection

ParamTypeDescription
fieldsArrayFields to index
indexOptionobjectOptions for the index
[indexOption.partialFilter]MangoPartialFilterpartialFilter
[indexOption.indexName]stringindexName

documentCollection.fetchAllMangoIndexes() ⇒ Promise.<Array.<DesignDoc>>

Retrieve all design docs of mango indexes

Kind: instance method of DocumentCollection
Returns: Promise.<Array.<DesignDoc>> - The design docs

documentCollection.destroyIndex(index) ⇒ Promise.<object>

Delete the specified design doc

Kind: instance method of DocumentCollection
Returns: Promise.<object> - The delete response

ParamTypeDescription
indexDesignDocThe design doc to remove

documentCollection.copyIndex(existingIndex, newIndexName) ⇒ Promise.<DesignDoc>

Copy an existing design doc.

This is useful to create a new design doc without having to recompute the existing index.

Kind: instance method of DocumentCollection
Returns: Promise.<DesignDoc> - The copy response

ParamTypeDescription
existingIndexDesignDocThe design doc to copy
newIndexNamestringThe name of the copy

documentCollection.fetchChangesRaw(couchOptions)

Calls _changes route from CouchDB No further treatment is done contrary to fetchchanges

Kind: instance method of DocumentCollection
See: https://docs.couchdb.org/en/stable/api/database/changes.html

ParamTypeDescription
couchOptionsobjectCouch options for changes https://kutt.it/5r7MNQ
[couchOptions.since]stringBookmark telling CouchDB from which point in time should changes be returned
[couchOptions.doc_ids]Array.<string>Only return changes for a subset of documents
[couchOptions.includeDocs]booleanIncludes full documents as part of results
[couchOptions.filter]stringFilter

DocumentCollection.normalizeDoctype(doctype) ⇒ function

Provides a callback for Collection.get

Kind: static method of DocumentCollection
Returns: function - (data, response) => normalizedDocument using normalizeDoc

ParamTypeDescription
doctypestringDocument doctype

FileCollection

Implements DocumentCollection API along with specific methods for io.cozy.files.

Files are a special type of documents and are handled differently by the stack: special routes are to be used, and there is a notion of referenced files, aka files associated to a specific document

Kind: global class

new FileCollection(doctype, stackClient, [options])

ParamTypeDescription
doctypestringDoctype of the collection (should be io.cozy.files)
stackClientCozyStackClientThe client used to make requests to the server
[options]FileCollectionOptionsThe collection options

fileCollection.forceFileDownload

Force a file download from the given href

Kind: instance property of FileCollection

ParamTypeDescription
hrefstringThe link to download
filenamestringThe file name to download

fileCollection.get(id) ⇒ Object

Fetches the file's data

Kind: instance method of FileCollection
Returns: Object - Information about the file or folder and it's descendents

ParamTypeDescription
idstringFile id

fileCollection.getAll(ids) ⇒ Promise.<{data, meta, execution_stats}>

Get all files by their ids

Kind: instance method of FileCollection
Returns: Promise.<{data, meta, execution_stats}> - JSON API response

ParamTypeDescription
idsArray.<string>files ids

fileCollection.find(selector, options) ⇒ Promise.<{data, meta, skip, next, bookmark, execution_stats}>

Returns a filtered list of documents using a Mango selector.

The returned documents are paginated by the stack.

Kind: instance method of FileCollection
Returns: Promise.<{data, meta, skip, next, bookmark, execution_stats}> - The JSON API conformant response.
Throws:

  • FetchError
ParamTypeDescription
selectorobjectThe Mango selector.
optionsMangoQueryOptionsThe query options

fileCollection.findReferencedBy(document, options) ⇒ Promise.<{data, included, meta, skip, next}>

async findReferencedBy - Returns the list of files referenced by a document — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/

Kind: instance method of FileCollection
Returns: Promise.<{data, included, meta, skip, next}> - The JSON API conformant response.

ParamTypeDescription
documentobjectA JSON representing a document, with at least a _type and _id field.
optionsobjectAdditional options
[options.skip]number | nullFor skip-based pagination, the number of referenced files to skip.
[options.limit]number | nullFor pagination, the number of results to return.
[options.cursor]CouchDBViewCursor | nullFor cursor-based pagination, the index cursor.

fileCollection.addReferencedBy(document, documents) ⇒ Promise.<{data, meta}>

Add referenced_by documents to a file — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/#post-filesfile-idrelationshipsreferenced_by

For example, to have an album referenced by a file:

addReferencedBy({_id: 123, _type: "io.cozy.files", name: "cozy.jpg"}, [{_id: 456, _type: "io.cozy.photos.albums", name: "Happy Cloud"}])

Kind: instance method of FileCollection
Returns: Promise.<{data, meta}> - The JSON API conformant response.

ParamTypeDescription
documentFileDocumentA JSON representing the file
documentsArrayAn array of JSON documents having a _type and _id field.

fileCollection.removeReferencedBy(document, documents) ⇒ Promise.<{data, meta}>

Remove referenced_by documents from a file — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/#delete-filesfile-idrelationshipsreferenced_by

For example, to remove an album reference from a file:

 removeReferencedBy({_id: 123, _type: "io.cozy.files", name: "cozy.jpg"}, [{_id: 456, _type: "io.cozy.photos.albums", name: "Happy Cloud"}])

Kind: instance method of FileCollection
Returns: Promise.<{data, meta}> - The JSON API conformant response.

ParamTypeDescription
documentobjectA JSON representing the file
documentsArrayAn array of JSON documents having a _type and _id field.

fileCollection.addReferencesTo(document, documents)

Add files references to a document — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/#post-datatypedoc-idrelationshipsreferences

For example, to add a photo to an album:

 addReferencesTo({_id: 456, _type: "io.cozy.photos.albums", name: "Happy Cloud"}, [{_id: 123, _type: "io.cozy.files", name: "cozy.jpg"}])

Kind: instance method of FileCollection

ParamTypeDescription
documentobjectA JSON representing a document, with at least a _type and _id field.
documentsArrayAn array of JSON files having an _id field. Returns 204 No Content

fileCollection.removeReferencesTo(document, documents)

Remove files references to a document — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/#delete-datatypedoc-idrelationshipsreferences

For example, to remove a photo from an album:

 removeReferencesTo({_id: 456, _type: "io.cozy.photos.albums", name: "Happy Cloud"}, [{_id: 123, _type: "io.cozy.files", name: "cozy.jpg"}])

Kind: instance method of FileCollection

ParamTypeDescription
documentobjectA JSON representing a document, with at least a _type and _id field.
documentsArrayAn array of JSON files having an _id field. Returns 204 No Content

fileCollection.destroy(file, [options]) ⇒ Promise.<{data}>

Sends file to trash and removes references to it

Kind: instance method of FileCollection
Returns: Promise.<{data}> - The JSON API conformant response.

ParamTypeDescription
fileFileDocumentFile that will be sent to trash
[options]objectOptionnal request options

fileCollection.emptyTrash() ⇒ Promise.<{data}>

Empty the Trash

Kind: instance method of FileCollection
Returns: Promise.<{data}> - The JSON API conformant response.
Throws:

  • FetchError

fileCollection.restore(id) ⇒ Promise.<{data}>

Restores a trashed file.

Kind: instance method of FileCollection
Returns: Promise.<{data}> - The JSON API conformant response.
Throws:

  • FetchError
ParamTypeDescription
idstringThe file's id

fileCollection.copy(id, [name], [dirId], [options]) ⇒ Promise.<object>

Copy a file.

Kind: instance method of FileCollection
Returns: Promise.<object> - - A promise that returns the copied file if resolved.
Throws:

  • FetchError
ParamTypeDescription
idstringThe file's id
[name]stringThe file copy name
[dirId]stringThe destination directory id
[options]objectOptionnal request options

fileCollection.deleteFilePermanently(id, [options]) ⇒ Promise.<{data}>

async deleteFilePermanently - Definitely delete a file

Kind: instance method of FileCollection
Returns: Promise.<{data}> - The JSON API conformant response.

ParamTypeDescription
idstringThe id of the file to delete
[options]objectOptionnal request options

fileCollection.upload(data, dirPath, [options]) ⇒ Promise.<object>

Kind: instance method of FileCollection
Returns: Promise.<object> - Created io.cozy.files

ParamTypeDescription
dataFile | Blob | Stream | string | ArrayBufferfile to be uploaded
dirPathstringPath to upload the file to. ie : /Administative/XXX/
[options]objectOptionnal request options

fileCollection.create(attributes, [options])

Creates directory or file.

  • Used by StackLink to support CozyClient.create('io.cozy.files', options)

Kind: instance method of FileCollection
Throws:

  • Error - explaining reason why creation failed
ParamTypeDescription
attributesFileAttributes | DirectoryAttributesAttributes of the created file/directory
attributes.dataFile | Blob | string | ArrayBufferWill be used as content of the created file
[options]objectOptionnal request options

fileCollection.updateFile(data, params, options) ⇒ Promise.<FileAttributes>

updateFile - Updates a file's data

Kind: instance method of FileCollection
Returns: Promise.<FileAttributes> - Updated document
Throws:

  • Error - explaining reason why update failed
ParamTypeDescription
dataFile | Blob | Stream | string | ArrayBufferfile to be uploaded
paramsFileAttributesFile attributes to update and doUpload options (additional headers)
optionsobjectRequest Options

fileCollection.download(file, versionId, filename)

Download a file or a specific version of the file

Kind: instance method of FileCollection

ParamTypeDefaultDescription
fileobjectio.cozy.files object
versionIdstringnullId of the io.cozy.files.version
filenamestringThe name you want for the downloaded file (by default the same as the file)

fileCollection.fetchFileContentById(id)

Fetch the binary of a file or a specific version of a file Useful for instance when you can't download the file directly (via a content-disposition attachement header) and need to store it before doing an operation.

Kind: instance method of FileCollection

ParamTypeDescription
idstringId of the io.cozy.files or io.cozy.files.version

fileCollection.getBeautifulSize(file, decimal)

Get a beautified size for a given file 1024B => 1KB 102404500404B => 95.37 GB

Kind: instance method of FileCollection

ParamTypeDescription
fileobjectio.cozy.files object
decimalnumbernumber of decimal

fileCollection.downloadArchive(fileIds, [notSecureFilename], [options])

Download an archive of the files

Kind: instance method of FileCollection

ParamTypeDescription
fileIdsArray.<string>List of file ids
[notSecureFilename]stringName of the archive (default: 'files')
[options]objectAdditional options
[options.pages]Array.<ArchivePages>Array of objects, with id the file identifier, and page the page number (1 is the first page)

fileCollection.getArchiveLinkByIds()

Deprecated

Kind: instance method of FileCollection

fileCollection.createArchiveLinkByIds(params) ⇒ Promise.<string>

Create the archive link for a list of files The generated archive is temporary and is not persisted

Kind: instance method of FileCollection
Returns: Promise.<string> - - The archive link

ParamTypeDescription
paramsobjectParameters
params.idsArray.<string>List of file ids
[params.name]stringName of the archive (default: 'files')
[params.pages]Array.<ArchivePages>Array of objects, with id the file identifier, and page the page number (1 is the first page)

fileCollection.isChildOf(child, parent) ⇒ boolean

Checks if the file belongs to the parent's hierarchy.

Kind: instance method of FileCollection
Returns: boolean - Whether the file is a parent's child

ParamTypeDescription
childstring | objectThe file which can either be an id or an object
parentstring | objectThe parent target which can either be an id or an object

fileCollection.statById(id, options) ⇒ object

statById - Fetches the metadata about a document. For folders, the results include the list of child files and folders.

Kind: instance method of FileCollection
Returns: object - A promise resolving to an object containing "data" (the document metadata), "included" (the child documents) and "links" (pagination informations)

ParamTypeDescription
idstringID of the document
optionsobject | nullPagination options
[options.page[limit]]number | nullFor pagination, the number of results to return.
[options.page[skip]]number | nullFor skip-based pagination, the number of referenced files to skip.
[options.page[cursor]]CouchDBViewCursor | nullFor cursor-based pagination, the index cursor.

fileCollection.createDirectoryByPath(path, [options]) ⇒ object

async createDirectoryByPath - Creates one or more folders until the given path exists

Kind: instance method of FileCollection
Returns: object - The document corresponding to the last segment of the path

ParamTypeDescription
pathstringPath of the created directory
[options]objectOptionnal request options

fileCollection.createFileMetadata(attributes) ⇒ Promise.<object>

Send a metadata object that can be associated to a file uploaded after that, via the MetadataID query parameter. See https://github.com/cozy/cozy-stack/blob/master/docs/files.md#post-filesuploadmetadata

Kind: instance method of FileCollection
Returns: Promise.<object> - The Metadata object

ParamTypeDescription
attributesobjectThe file's metadata

fileCollection.updateMetadataAttribute(id, metadata) ⇒ Promise.<object>

Updates the metadata attribute of a io.cozy.files Creates a new version of the file without having to upload again the file's content

To see available content of the metadata attribute see : https://docs.cozy.io/en/cozy-doctypes/docs/io.cozy.files_metadata/

Kind: instance method of FileCollection
Returns: Promise.<object> - io.cozy.files updated

ParamTypeDescription
idstringFile id
metadataobjectio.cozy.files.metadata attributes

fileCollection.getFileTypeFromName(name) ⇒ string

Get the file mime-type based on its name

Kind: instance method of FileCollection
Returns: string - the inferred file mime-type

ParamTypeDescription
namestringThe file name

fileCollection.doUpload(dataArg, path, options, [method])

This method should not be called directly to upload a file. You should use createFile

Kind: instance method of FileCollection

ParamTypeDefaultDescription
dataArgFile | Blob | Stream | string | ArrayBufferfile to be uploaded
pathstringUri to call the stack from. Something like /files/${dirId}?Name=${name}&Type=file&Executable=${executable}&MetadataID=${metadataId}
optionsobjectAdditional headers
[method]string"POST"POST / PUT / PATCH

fileCollection.findNotSynchronizedDirectories(oauthClient, options) ⇒ Array.<(object|IOCozyFolder)>

async findNotSynchronizedDirectories - Returns the list of directories not synchronized on the given OAuth client (mainly Cozy Desktop clients) — see https://docs.cozy.io/en/cozy-stack/not-synchronized-vfs/#get-datatypedoc-idrelationshipsnot_synchronizing

Kind: instance method of FileCollection
Returns: Array.<(object|IOCozyFolder)> - The JSON API conformant response.

ParamTypeDescription
oauthClientOAuthClientA JSON representing an OAuth client, with at least a _type and _id field.
optionsobject | nullPagination options
options.skipnumber | nullFor skip-based pagination, the number of referenced files to skip.
options.limitnumber | nullFor pagination, the number of results to return.
options.cursorCouchDBViewCursor | nullFor cursor-based pagination, the index cursor.
options.includeFilesbooleanInclude the whole file documents in the results list

fileCollection.addNotSynchronizedDirectories(oauthClient, directories)

Add directory synchronization exclusions to an OAuth client — see https://docs.cozy.io/en/cozy-stack/not-synchronized-vfs/#post-datatypedoc-idrelationshipsnot_synchronizing

For example, to exclude directory /Photos from My Computer's desktop synchronization:

addNotSynchronizedDirectories({_id: 123, _type: "io.cozy.oauth.clients", clientName: "Cozy Drive (My Computer)", clientKind: "desktop"}, [{_id: 456, _type: "io.cozy.files", name: "Photos", path: "/Photos"}])

Kind: instance method of FileCollection

ParamTypeDescription
oauthClientOAuthClientA JSON representing the OAuth client
directoriesArrayAn array of JSON documents having a _type and _id fields and representing directories. Returns 204 No Content

fileCollection.removeNotSynchronizedDirectories(oauthClient, directories)

Remove directory synchronization exclusions from an OAuth client — see https://docs.cozy.io/en/cozy-stack/not-synchronized-vfs/#delete-datatypedoc-idrelationshipsnot_synchronizing

For example, to re-include directory /Photos into My Computer's desktop synchronization:

 removeNotSynchronizedDirectories({_id: 123, _type: "io.cozy.oauth.clients", clientName: "Cozy Drive (My Computer)", clientKind: "desktop"}, [{_id: 456, _type: "io.cozy.files", name: "Photos", path: "/Photos"}])

Kind: instance method of FileCollection

ParamTypeDescription
oauthClientOAuthClientA JSON representing the OAuth client
directoriesArrayAn array of JSON documents having a _type and _id field and representing directories. Returns 204 No Content

fileCollection.getOrCreateSharedDrivesDirectory() ⇒ IOCozyFolder

Get or create the Shared Drives directory it if it does not exist.

The Shared Drives directory is a special directory :

  • its _id is io.cozy.files.shared-drives-dir
  • it can contains Nextcloud shortcuts
  • it can contains shared drives

Kind: instance method of FileCollection
Returns: IOCozyFolder - Shared Drives directory

fileCollection.moveRelateToSharedDrive(source, dest, isCopy) ⇒ Promise.<{data: (undefined|object)}>

Move or copy a file or a directory between locations (personal drive and/or shared drives). Manage 3 cases :

  • From a shared drive to another shared drive (same stack or cross-stack)
  • From a shared drive to a personal drive
  • From a personal drive to a shared drive

Kind: instance method of FileCollection
Returns: Promise.<{data: (undefined|object)}> - - A promise that returns the move/copy action response (if any)

ParamTypeDescription
sourceobjectThe source file/folder to move/copy (required) At least one side (source or destination) must be a shared drive.
[source.instance]stringomit for personal drive If source.instance is provided, source.sharing_id is required.
[source.sharing_id]stringrequired when instance is set
[source.file_id]stringfile needs to move
[source.dir_id]stringfolder needs to move Exactly one of source.file_id or source.dir_id must be provided.
destobjectThe destination folder (required)
[dest.instance]stringomit for personal drive If dest.instance is provided, dest.sharing_id is required.
[dest.sharing_id]stringrequired when instance is set
dest.dir_idstringdestination directory id (required)
isCopybooleancontrols whether the operation is a move (default) or copy. When copy: false (default): The source file/directory is moved to the destination and deleted from the source. When copy: true: The source file/directory is copied to the destination but remains in the source location.

NotesCollection

Implements DocumentCollection API to interact with the /notes endpoint of the stack

Kind: global class

new NotesCollection(stackClient, [options])

ParamTypeDescription
stackClientCozyStackClientThe client used to make requests to the server
[options]NotesCollectionOptionsThe collection options

notesCollection.get(id) ⇒ Object

Fetches the note data

Kind: instance method of NotesCollection
Returns: Object - Information about the note

ParamTypeDescription
idstringNote id

notesCollection.all() ⇒ Object

Fetches all notes

Kind: instance method of NotesCollection
Returns: Object - The JSON API conformant response.

notesCollection.destroy(note) ⇒ Object

Destroys the note on the server

Kind: instance method of NotesCollection
Returns: Object - The deleted note

ParamTypeDescription
noteobjectThe io.cozy.notes document to destroy
[note._id]stringThe note's id

notesCollection.create(options) ⇒ Object

Create a note

Kind: instance method of NotesCollection
Returns: Object - The JSON API conformant response.

ParamTypeDescription
optionsobjectOptions
[options.dir_id]stringdir_id where to create the note

notesCollection.fetchURL(note) ⇒ Object

Returns the details to build the note's url

Kind: instance method of NotesCollection
Returns: Object - The note's url details
See: https://github.com/cozy/cozy-stack/blob/master/docs/notes.md#get-notesidopen

ParamTypeDescription
noteobjectThe io.cozy.notes document to open
[note._id]stringThe note's id

notesCollection.getDefaultSchema() ⇒ object

Returns promise mirror schema for a note

Kind: instance method of NotesCollection
Returns: object - schema

OAuthClient

Specialized CozyStackClient for mobile, implementing stack registration through OAuth.

Kind: global class

oAuthClient.doRegistration()

Performs the HTTP call to register the client to the server

Kind: instance method of OAuthClient

oAuthClient.register() ⇒ Promise

Registers the currenly configured client with the OAuth server and sets internal information from the server response

Kind: instance method of OAuthClient
Returns: Promise - A promise that resolves with a complete list of client information, including client ID and client secret.
Throws:

  • Error When the client is already registered

oAuthClient.unregister() ⇒ Promise

Unregisters the currenly configured client with the OAuth server.

Kind: instance method of OAuthClient
Throws:

  • NotRegisteredException When the client doesn't have it's registration information

oAuthClient.fetchInformation() ⇒ Promise

Fetches the complete set of client information from the server after it has been registered.

Kind: instance method of OAuthClient
Throws:

  • NotRegisteredException When the client doesn't have it's registration information

oAuthClient.updateInformation(information, resetSecret) ⇒ Promise

Overwrites the client own information. This method will update both the local information and the remote information on the OAuth server.

Kind: instance method of OAuthClient
Returns: Promise - Resolves to a complete, updated list of client information
Throws:

  • NotRegisteredException When the client doesn't have it's registration information
ParamTypeDefaultDescription
informationobjectSet of information to update. Note that some fields such as clientID can't be updated.
resetSecretbooleanfalse= false Optionnal, whether to reset the client secret or not

oAuthClient.generateStateCode() ⇒ string

Generates a random state code to be used during the OAuth process

Kind: instance method of OAuthClient

oAuthClient.getAuthCodeURL(options) ⇒ string

Generates the URL that the user should be sent to in order to accept the app's permissions.

Kind: instance method of OAuthClient
Returns: string - The URL
Throws:

  • NotRegisteredException When the client doesn't have it's registration information
ParamTypeDescription
optionsobjectURL generation options
options.stateCodestringA random code to be included in the URl for security. Can be generated with client.generateStateCode()
[options.scopes]ArrayAn array of permission scopes for the token.
[options.sessionCode]SessionCodeA session code that can be used to create a session.
[options.codeChallenge]stringA code challenge that can be used in a PKCE verification process.

oAuthClient.getAccessCodeFromURL(pageURL, stateCode) ⇒ string

Retrieves the access code contained in the URL to which the user is redirected after accepting the app's permissions (the redirectURI).

Kind: instance method of OAuthClient
Returns: string - The access code
Throws:

  • Error The URL should contain the same state code as the one generated with client.getAuthCodeURL(). If not, it will throw an error
ParamTypeDescription
pageURLstringThe redirected page URL, containing the state code and the access code
stateCodestringThe state code that was contained in the original URL the user was sent to (see client.getAuthCodeURL())

oAuthClient.fetchAccessToken(accessCode, oauthOptionsArg, uri, codeVerifier) ⇒ Promise

Exchanges an access code for an access token. This function does not update the client's token.

Kind: instance method of OAuthClient
Returns: Promise - A promise that resolves with an AccessToken object.
Throws:

  • NotRegisteredException When the client doesn't have it's registration information
ParamTypeDescription
accessCodestringThe access code contained in the redirection URL — see client.getAccessCodeFromURL()
oauthOptionsArgobject— To use when OAuthClient is not yet registered (during login process)
uristring— To use when OAuthClient is not yet registered (during login process)
codeVerifierstring— The PKCE code verifier (see https://docs.cozy.io/en/cozy-stack/auth/#pkce-extension)

oAuthClient.fetchKonnectorToken(slug) ⇒ Promise.<string>

Used by the flagship application in order to create a token for the konnector with the given slug. This token can then be used by the client-side konnector to make requests to cozy-stack. The flagship app will need to use its own access token to request the konnector token.

Kind: instance method of OAuthClient
Returns: Promise.<string> - - A promise that resolves with a new token

ParamTypeDescription
slugstringThe slug of the konnector

oAuthClient.fetchSessionCode() ⇒ Promise.<SessionCodeRes>

Fetches a new session code. Only usable by the Flagship application

Kind: instance method of OAuthClient
Returns: Promise.<SessionCodeRes> - A promise that resolves with a new session_code
Throws:

  • NotRegisteredException When the client isn't certified to be the Flagship application

oAuthClient.fetchSessionCodeWithPassword() ⇒ Promise.<SessionCodeRes>

Fetches a new session code. Only usable by the Flagship application

Kind: instance method of OAuthClient
Returns: Promise.<SessionCodeRes> - A promise that resolves with a new session_code
Throws:

  • NotRegisteredException When the client isn't certified to be the Flagship application

oAuthClient.loginFlagship() ⇒ Promise.<(AccessTokenRes|TwoFactorNeededRes|SessionCodeRes)>

Get OAuth access and register tokens without having to make OAuth dance

This endpoint returns registration tokens only from a Flagship app, otherwise it returns a session_code that should be used in an OAuth dance

More info: https://docs.cozy.io/en/cozy-stack/flagship/ More info: https://docs.cozy.io/en/cozy-stack/auth/#post-authloginflagship

Kind: instance method of OAuthClient
Returns: Promise.<(AccessTokenRes|TwoFactorNeededRes|SessionCodeRes)> - A promise that resolves with an access token, a session_code or a 2FA code

oAuthClient.refreshToken() ⇒ Promise

Retrieves a new access token by refreshing the currently used token.

Kind: instance method of OAuthClient
Returns: Promise - A promise that resolves with a new AccessToken object
Throws:

  • NotRegisteredException When the client doesn't have it's registration information
  • Error The client should already have an access token to use this function

oAuthClient.setToken(token)

Updates the client's stored token

Kind: instance method of OAuthClient

ParamTypeDescription
tokenstring= null The new token to use — can be a string, a json object or an AccessToken instance.

oAuthClient.setOAuthOptions(options)

Updates the OAuth informations

Kind: instance method of OAuthClient

ParamTypeDescription
optionsobjectMap of OAuth options

oAuthClient.resetClient()

Reset the current OAuth client

Kind: instance method of OAuthClient

oAuthClient.setPassphraseFlagship(params) ⇒ object

This method should be used in flagship app onboarding process to finalize the cozy creation by setting the user password into the cozy-stack

More info: https://docs.cozy.io/en/cozy-stack/settings/#post-settingspassphraseflagship

Kind: instance method of OAuthClient
Returns: object - token - The OAauth token

ParamTypeDescription
paramsobjectparameters needed to set passphrase
params.registerTokenstringregistration token provided by the onboarding link
params.passwordHashstringhash of the master password
params.hintstringhint for the master password
params.keystringkey (crypted) used for the vault encryption
params.publicKeystringpublic key used for sharing ciphers from the vault
params.privateKeystringprivate key (crypted) used for sharing ciphers from the vault
params.iterationsstringnumber of KDF iterations applied when hashing the master password

oAuthClient.checkForRevocation() ⇒ Promise.<boolean>

Check if the OAuth client's has been revoked. If this is the case, call the onRevocationChange callback

Kind: instance method of OAuthClient
Returns: Promise.<boolean> - A Promise that resolves to false if client is still valid, or true if it has been revoked.

OAuthClientsCollection

Implements DocumentCollection API to interact with the /settings/clients endpoint of the stack

Kind: global class

oAuthClientsCollection.all(options) ⇒ object

Fetches all OAuth clients

Kind: instance method of OAuthClientsCollection
Returns: object - The JSON API conformant response.

ParamTypeDescription
optionsobjectQuery options
[options.limit]numberFor pagination, the number of results to return.
[options.bookmark]stringFor bookmark-based pagination, the document _id to start from
[options.keys]Array.<string>Ids of specific clients to return (within the current page),

oAuthClientsCollection.get(id) ⇒ object

Get an OAuth client by id

Kind: instance method of OAuthClientsCollection
Returns: object - JsonAPI response containing normalized client as data attribute

ParamTypeDescription
idstringThe client id.

oAuthClientsCollection.destroy(oauthClient) ⇒ Object

Destroys the OAuth client on the server

Kind: instance method of OAuthClientsCollection
Returns: Object - The deleted client

ParamTypeDescription
oauthClientobjectThe io.cozy.oauth.clients document to destroy

PermissionCollection

Implements DocumentCollection API along with specific methods for io.cozy.permissions.

Kind: global class

new PermissionCollection(doctype, stackClient, [options])

ParamTypeDescription
doctypestringDoctype of the collection (should be io.cozy.permissions)
stackClientCozyStackClientThe client used to make requests to the server
[options]PermissionCollectionOptionsThe collection options

permissionCollection.create(permission)

Create a new set of permissions It can also associates one or more codes to it, via the codes parameter

Kind: instance method of PermissionCollection
See: https://docs.cozy.io/en/cozy-stack/permissions/#post-permissions

ParamTypeDescription
permissionobjectpermission to create
permission.codesstringA comma separed list of values (defaulted to code)
permission.ttlstringMake the codes expire after a delay (bigduration format)
permission.tinybooleanIf set to true then the generated shortcode will be 6 digits Cozy-Stack has a few conditions to be able to use this tiny shortcode ATM you have to specifiy a ttl < 1h, but it can change. see https://docs.cozy.io/en/cozy-stack/permissions/#post-permissions for exact informations bigduration format: https://github.com/justincampbell/bigduration/blob/master/README.md

permissionCollection.add(document, permission, options) ⇒ Promise

Adds a permission to the given document. Document type must be io.cozy.apps, io.cozy.konnectors or io.cozy.permissions

Kind: instance method of PermissionCollection

ParamTypeDescription
documentobjectDocument which receives the permission
permissionobjectDescribes the permission
optionsobjectoptions
[options.expiresAt]stringDate at which the permission will expire. Set to "" to remove it.
[options.password]stringTo generate a password-protected link. Set to "" to remove it.

Example

const permissions = await client.collection('io.cozy.permissions').add(
  konnector,
  {
    folder: {
      type: 'io.cozy.files',
      verbs: ['GET', 'PUT'],
      values: [`io.cozy.files.bc57b60eb2954537b0dcdc6ebd8e9d23`]
    }
  },
  { expiresAt: '2100-01-01T00:00:00Z', password: 'password' }
)

permissionCollection.findLinksByIds(ids) ⇒ Promise

Find sharing links by document ids

This is the shared-drive equivalent of findLinksByDoctype when you already know the document ids. It uses the same this.prefix, so the URL becomes /sharings/drives/:driveId/permissions?ids=... when the collection is built with { driveId }.

The returned permissions are normalized (have _id and _type).

Kind: instance method of PermissionCollection
Returns: Promise - The matching permissions
Throws:

  • Error If the collection is not configured with a driveId
ParamTypeDescription
idsArray.<string>The list of document ids to look up

permissionCollection.findApps()

Deprecated

Kind: instance method of PermissionCollection

permissionCollection.createSharingLink(document, options)

Create a share link

Kind: instance method of PermissionCollection

ParamTypeDescription
documentObjectcozy document
optionsobjectoptions
[options.ttl]stringTime to live (bigduration format, e.g. "4Y3M2D1h30m15s")
[options.password]stringTo generate a password-protected link
[options.verbs]Array.<string>explicit permissions to use
[options.codes]stringA comma separed list of values (defaulted to code)
[options.tiny]booleanIf set to true then the generated shortcode will be 6 digits Cozy-Stack has a few conditions to be able to use this tiny shortcode ATM you have to specifiy a ttl < 1h, but it can change. see https://docs.cozy.io/en/cozy-stack/permissions/#post-permissions for exact informations

permissionCollection.fetchPermissionsByLink(permissions)

Follow the next link to fetch the next permissions

Kind: instance method of PermissionCollection

ParamTypeDescription
permissionsobjectJSON-API based permissions document

permissionCollection.fetchAllLinks(document) ⇒ object

Kind: instance method of PermissionCollection
Returns: object - with all the permissions

ParamTypeDescription
documentobjectCozy doc

permissionCollection.revokeSharingLink(document)

Destroy a sharing link and the related permissions

Kind: instance method of PermissionCollection

ParamTypeDescription
documentobjectdocument to revoke sharing link

PromiseCache

Caches promises while they are pending Serves to dedupe equal queries requested at the same time

Kind: global class

promiseCache.pending : Object.<string, Promise>

Holds pending promises

Kind: instance property of PromiseCache

promiseCache.exec(promiseFunc, keyFunc) ⇒ Promise.<T>

Tries to find a pending promise corresponding to the result of keyFunc

  • If not found, promiseFunc is executed and the resulting promise is stored while it's pending
  • If found, it is immediately returned

Kind: instance method of PromiseCache

ParamTypeDescription
promiseFuncfunctionNot executed only if an "equal" promise is already pending.
keyFuncfunctionReturns a key to find in cache to find a pending promise.

promiseCache.get(keyFunc) ⇒ Promise | null

Kind: instance method of PromiseCache

ParamTypeDescription
keyFuncfunctionReturns a key to find in cache to find a pending promise.

SettingsCollection

Implements DocumentCollection API to interact with the /settings endpoint of the stack

Kind: global class

settingsCollection.get(id) ⇒ object

async get - Calls a route on the /settings API

Kind: instance method of SettingsCollection
Returns: object - The response from the route

ParamTypeDescription
idstringThe setting id to call, eg io.cozy.settings.instance for instance route or io.cozy.settings.context for contextroute

settingsCollection.update(document)

Updates a settings document

Kind: instance method of SettingsCollection

ParamTypeDescription
documentobjectDocument to update. Do not forget the _id attribute

settingsCollection.updateLastSynced()

Updates the current OAuth client's last synchronization date

Kind: instance method of SettingsCollection

SharingCollection

Implements the DocumentCollection API along with specific methods for io.cozy.sharings.

Kind: global class

sharingCollection.findByDoctype(doctype, [options]) ⇒ object

Finds all sharings for a given doctype

Kind: instance method of SharingCollection
Returns: object - The response

ParamTypeDescription
doctypestringThe doctype
[options]SharingRulesOptionsThe options
[options.withSharedDocs]booleanIf true, the response will include the shared documents

sharingCollection.get(id) ⇒ Sharing

Fetches a sharing by id

Kind: instance method of SharingCollection
Returns: Sharing - sharing

ParamTypeDescription
idstringSharing's id

sharingCollection.renameSharedDrive(sharing, newName) ⇒ object

Rename a shared drive

Kind: instance method of SharingCollection
Returns: object - The response

ParamTypeDescription
sharingSharingSharing's id
newNamestringNew name

sharingCollection.fetchSharedDrives() ⇒ Promise.<{data: Array.<Sharing>}>

Fetch shared drives

Kind: instance method of SharingCollection
Returns: Promise.<{data: Array.<Sharing>}> - Shared drives (which are io.cozy.sharings documents)

sharingCollection.create(params)

Creates a new Sharing. See https://docs.cozy.io/en/cozy-stack/sharing/#post-sharings

Kind: instance method of SharingCollection

ParamTypeDescription
paramsobjectSharing params
params.documentSharingThe document to share
params.descriptionstringDescription of the sharing
[params.previewPath]stringThe preview path
[params.rules]Array.<Rule>The rules defined to the sharing. See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing
[params.recipients]Array.<Recipient>Recipients to add to the sharings (will have the same permissions given by the rules defined by the sharing )
[params.readOnlyRecipients]Array.<Recipient>Recipients to add to the sharings with only read only access
[params.openSharing]booleanIf someone else than the owner can add a recipient to the sharing
[params.appSlug]stringSlug of the targeted app
[params.sharedDrive]booleanIf the sharing is a shared drive

sharingCollection.createSharedDrive(params)

Creates a new shared drive. See https://docs.cozy.io/en/cozy-stack/shared-drives/

Kind: instance method of SharingCollection

ParamTypeDescription
paramsobjectSharing params
[params.name]stringName for the new shared drive (mutually exclusive with document)
[params.document]SharingExisting folder to use as shared drive (mutually exclusive with name)
params.descriptionstringDescription of the sharing
[params.recipients]Array.<Recipient>Recipients to add to the sharing
[params.readOnlyRecipients]Array.<Recipient>Recipients to add with read only access

sharingCollection.getDiscoveryLink(sharingId, sharecode, [options]) ⇒ string

getDiscoveryLink - Returns the URL of the page that can be used to accept a sharing. See https://docs.cozy.io/en/cozy-stack/sharing/#get-sharingssharing-iddiscovery

Kind: instance method of SharingCollection

ParamTypeDescription
sharingIdstringId of the sharing
sharecodestringCode of the sharing
[options]objectOptions
[options.shortcut]booleanIf true, add a shortcut to the sharing in the user's cozy and skip the OAuth authorize page.

sharingCollection.addRecipients(options)

Add an array of contacts to the Sharing

Kind: instance method of SharingCollection

ParamTypeDescription
optionsobjectObject
options.documentSharingSharing Object
[options.recipients]Array.<Recipient>Recipients to add to the sharing
[options.readOnlyRecipients]Array.<Recipient>Recipients to add to the sharings with only read only access

sharingCollection.revokeRecipient(sharing, recipientIndex)

Revoke only one recipient of the sharing.

Kind: instance method of SharingCollection

ParamTypeDescription
sharingSharingSharing Object
recipientIndexnumberIndex of this recipient in the members array of the sharing

sharingCollection.setReadOnly(sharing, recipientIndex)

Downgrade a sharing member to read-only.

Kind: instance method of SharingCollection

ParamTypeDescription
sharingSharingSharing Object
recipientIndexnumberIndex of this recipient in the members array of the sharing

sharingCollection.setReadWrite(sharing, recipientIndex)

Upgrade a read-only sharing member to read-write.

Kind: instance method of SharingCollection

ParamTypeDescription
sharingSharingSharing Object
recipientIndexnumberIndex of this recipient in the members array of the sharing

sharingCollection.revokeGroup(sharing, groupIndex)

Revoke only one group of the sharing.

Kind: instance method of SharingCollection

ParamTypeDescription
sharingSharingSharing Object
groupIndexnumberIndex of this group in the groups array of the sharing

sharingCollection.revokeSelf(sharing)

Remove self from the sharing.

Kind: instance method of SharingCollection

ParamTypeDescription
sharingSharingSharing Object

sharingCollection.revokeAllRecipients(sharing)

Revoke the sharing for all the members. Must be called from the owner's cozy

Kind: instance method of SharingCollection

ParamTypeDescription
sharingSharingSharing Objects

ShortcutsCollection

Provides helpers to interact with shortcuts documents on the Cozy stack.

Kind: global class

shortcutsCollection.create(attributes)

Create a shortcut

Kind: instance method of ShortcutsCollection
Throws:

  • Error - explaining reason why creation failed
ParamTypeDescription
attributesobjectshortcut's attributes
attributes.namestringFilename
attributes.urlstringShortcut's URL
attributes.dir_idstringdir_id where to create the shortcut
attributes.typestring | undefinedshortcut's type

shortcutsCollection.get(id) ⇒ Promise.<{data: object}>

Fetches a shortcut by its ID.

Kind: instance method of ShortcutsCollection
Returns: Promise.<{data: object}> - The shortcut data, normalized.
Throws:

  • Error If the fetch fails for any reason.
ParamTypeDescription
idstringThe ID of the shortcut to retrieve.

TriggerCollection

Implements DocumentCollection API along with specific methods for io.cozy.triggers.

Kind: global class

triggerCollection.all(options) ⇒ Object

Get the list of triggers.

Kind: instance method of TriggerCollection
Returns: Object - The JSON API conformant response.
Throws:

  • FetchError

See: https://docs.cozy.io/en/cozy-stack/jobs/#get-jobstriggers

ParamTypeDescription
optionsObjectThe fetch options: Worker allow to filter only triggers associated with a specific worker.

triggerCollection.create(attributes) ⇒ object

Creates a Trigger document

Kind: instance method of TriggerCollection
Returns: object - Stack response, containing trigger document under data attribute.
See: https://docs.cozy.io/en/cozy-stack/jobs/#post-jobstriggers

ParamTypeDescription
attributesobjectTrigger's attributes

triggerCollection.destroy(document) ⇒ object

Deletes a trigger

Kind: instance method of TriggerCollection
Returns: object - The deleted document
See: https://docs.cozy.io/en/cozy-stack/jobs/#delete-jobstriggerstrigger-id

ParamTypeDescription
documentobjectThe trigger to delete — must have an _id field

triggerCollection.find(selector, options) ⇒ Object

Be warned, ATM /jobs/triggers does not return the same informations than /data/io.cozy.triggers (used by the super.find method).

See https://github.com/cozy/cozy-stack/pull/2010

Kind: instance method of TriggerCollection
Returns: Object - The JSON API conformant response.
Throws:

  • FetchError
ParamTypeDescription
selectorobjectWhich kind of worker {konnector,service}
optionsobjectOptions

triggerCollection.launch(trigger) ⇒ object

Force given trigger execution.

Kind: instance method of TriggerCollection
Returns: object - Stack response, containing job launched by trigger, under data attribute.
See: https://docs.cozy.io/en/cozy-stack/jobs/#post-jobstriggerstrigger-idlaunch

ParamTypeDescription
triggerobjectTrigger to launch

triggerCollection.update(trigger) ⇒ object

Updates a Trigger document. Only updatable attributes plus _id are allowed.

Kind: instance method of TriggerCollection
Returns: object - Stack response, containing resulting trigger document under data attribute.

ParamTypeDescription
triggerobjectTrigger's attributes to update + id

dontThrowNotFoundError ⇒ object

Handler for error response which return a empty value for "not found" error

Kind: global constant
Returns: object - JsonAPI response with empty data in case of "not found" error.

ParamTypeDescription
errorErrorAn error
dataArray | object | nullData to return in case of "not found" error

isIndexNotFoundError ⇒ Array | null

Helper to identify an index not found error

Kind: global constant
Returns: Array | null - - Whether or not the error is an index not found error

ParamTypeDescription
errorErrorAn error

isIndexConflictError ⇒ Array | null

Helper to identify an index conflict

Kind: global constant
Returns: Array | null - - Whether or not the error is an index conflict error

ParamTypeDescription
errorErrorAn error

isIndexNotUsedWarning ⇒ Array | null

Helper to identify a not used index

Kind: global constant
Returns: Array | null - Whether or not this is a not used index warning

ParamTypeDescription
warningstringThe warning returned by CouchDB

isNoUsableIndexError ⇒ Array | null

Helper to identify a no usable index error

Kind: global constant
Returns: Array | null - - Whether or not the error is a no usable index error

ParamTypeDescription
errorErrorAn error

isTimeoutError ⇒ Array | null

Helper to identify timeout error See cozy-stack's timeout value for couchdb request: https://github.com/cozy/cozy-stack/blob/669cd694132388ef6b7d1a58cf3d1b5dfb52896a/pkg/config/config/config.go#L963

Kind: global constant
Returns: Array | null - Whether or not the error is a timeout error

ParamTypeDescription
errorErrorAn error

isDocumentUpdateConflict ⇒ Array | null

Helper to identify a document conflict

Kind: global constant
Returns: Array | null - - Whether or not the error is a document conflict error

ParamTypeDescription
errorErrorAn error

isFile ⇒ boolean

Returns true when parameter has type directory, file or has _type io.cozy.files

Kind: global constant
Returns: boolean - true when objects has type directory, file or has _type io.cozy.files or false

ParamTypeDescription
docobjectThe document whose type is checked
[doc._type]stringThe document's doctype
[doc.type]'directory' | 'file'The io.cozy-files document type

isDirectory ⇒ boolean

Returns true when parameters has type directory

Kind: global constant
Returns: boolean - true when parameters has type directory or false

ParamTypeDescription
argsobjectFile
args.typestringThe type of the file

getIllegalCharacters ⇒ string

Get the list of illegal characters in the file name

Kind: global constant
Returns: string - illegal characters separated by spaces
Access: public

ParamTypeDescription
namestringthe file name

makeKeyFromPartialFilter ⇒ string

Process a partial filter to generate a string key

/!\ Warning: this method is similar to cozy-pouch-link mango.makeKeyFromPartialFilter() If you edit this method, please check if the change is also needed in mango file

Kind: global constant
Returns: string - - The string key of the processed partial filter

ParamTypeDescription
conditionobjectAn object representing the partial filter or a sub-condition of the partial filter

getIndexNameFromFields ⇒ string

Name an index, based on its indexed fields and partial filter.

It follows this naming convention: by_{indexed_field1}_and_{indexed_field2}_filter_({partial_filter.key1}_{partial_filter.value1})_and_({partial_filter.key2}_{partial_filter.value2})

/!\ Warning: this method is similar to cozy-pouch-link mango.getIndexNameFromFields() If you edit this method, please check if the change is also needed in mango file

Kind: global constant
Returns: string - The index name, built from the fields

ParamTypeDescription
fieldsArray.<string>The indexed fields
[partialFilter]objectThe partial filter

transformSort ⇒ MangoSort

Transform sort into Array

Kind: global constant

ParamTypeDescription
sortMangoSortThe sorting parameters

getIndexFields ⇒ Array

Compute fields that should be indexed for a mango query to work

Kind: global constant
Returns: Array - - Fields to index

isMatchingIndex ⇒ boolean

Check if an index is matching the given fields

Kind: global constant
Returns: boolean - True if the index is matches the given fields

ParamTypeDescription
indexDesignDocThe index to check
fieldsArrayThe fields that the index must have
partialFilterobjectAn optional partial filter

makeOperatorsExplicit ⇒ object

Transform a query to make all operators explicit

Kind: global constant
Returns: object - - The transformed query with all operators explicit

ParamTypeDescription
queryobjectThe query to transform
reverseEqbooleanIf true, eqwillbetransformedtoeq will be transformed to ne (useful for manage $nor)

getPermissionsFor ⇒ object

Build a permission set

Kind: global constant
Returns: object - permissions object that can be sent through /permissions/*

ParamTypeDescription
documentObjectcozy document
publicLinkbooleanare the permissions for a public link ?
optionsobjectoptions
[options.verbs]Array.<string>explicit permissions to use

normalizeSettings ⇒ object

Normalizing a document for SettingsCollection context

Kind: global constant
Returns: object - normalized document

ParamTypeDescription
docobjectDocument to normalize

getSharingRules ⇒ Array.<Rule>

Rules determine the behavior of the sharing when changes are made to the shared document See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing

Kind: global constant
Returns: Array.<Rule> - The rules that define how to share the document

ParamTypeDescription
documentSharingThe document to share. Should have and _id and a name
[sharingRulesOptions]SharingRulesOptionsThe document to share. Should have and _id and a name

SHORTCUTS_DOCTYPE : string

Doctype for shortcuts documents.

Kind: global constant

forceDownload

Force a download from the given href

Kind: global constant

ParamTypeDescription
hrefstringThe link to download
filenamestringThe file name to download

encodePath ⇒ string

Encode a path for use in a URL by encoding special characters but keeping slashes

Kind: global constant
Returns: string - - The encoded path with special characters for parentheses and spaces

ParamTypeDescription
pathstringThe path to encode

sharedDriveApiPrefix ⇒ string

Returns a FileCollection API prefix for manipulating a shared drive's files.

Kind: global constant
Returns: string - The API prefix to manipulate the drive's files

ParamTypeDescription
driveIdstringThe shared drive ID

getAccessToken() ⇒ string

Get the access token string

Kind: global function
Returns: string - token
See: CozyStackClient.getAccessToken

getAccessToken() ⇒ string

Get the app token string

Kind: global function
Returns: string - token
See: CozyStackClient.getAccessToken

getIconURL()

Get Icon URL using blob mechanism if OAuth connected or using preloaded url when blob not needed

Kind: global function

handleNorOperator(conditions) ⇒ Array

Handle the noroperatorinaqueryCouchDBtransformsnor operator in a query CouchDB transforms nor into andwithand with ne operators

Kind: global function
Returns: Array - - The reversed conditions

ParamTypeDescription
conditionsArrayThe conditions inside the $nor operator

sortObjectByKey(a, b) ⇒ number

Compares two objects based on their first key to determine their order.

Kind: global function
Returns: number - - A negative number if the key of a should appear before the key of b, a positive number if it should appear after, or 0 if they are equal.

ParamTypeDescription
aobjectThe first object to compare
bobjectThe second object to compare

garbageCollect()

Delete outdated results from cache

Kind: global function

memoize()

Memoize with maxDuration and custom key

Kind: global function

normalizeDoctypeJsonApi(doctype) ⇒ function

Normalizes a document in JSON API format for a specific doctype

Kind: global function
Returns: function - A function that normalizes the document

ParamTypeDescription
doctypestringThe document type

getSharingRulesForPhotosAlbum(document) ⇒ Array.<Rule>

Compute the rules that define how to share a Photo Album. See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing

Kind: global function
Returns: Array.<Rule> - The rules that define how to share a Photo Album

ParamTypeDescription
documentSharingThe document to share. Should have and _id and a name

getSharingPolicyForReferencedFiles() ⇒ SharingPolicy

Compute the sharing policy for a ReferencedFile based on its sharing type

Kind: global function
Returns: SharingPolicy - The sharing policy for the ReferencedFile

getSharingPolicyForAlbum() ⇒ Array.<Rule>

Compute the sharing policy for an Album based on its sharing type

Kind: global function
Returns: Array.<Rule> - The sharing policy for the Album

getSharingRulesForFile(document) ⇒ Array.<Rule>

Compute the rules that define how to share a File. See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing

Kind: global function
Returns: Array.<Rule> - The rules that define how to share a File

ParamTypeDescription
documentSharingThe document to share. Should have and _id and a name

getSharingRulesForSharedDrive(document) ⇒ Array.<Rule>

Compute the rules that define a shared drive.

Kind: global function
Returns: Array.<Rule> - The rules that define a shared drive

ParamTypeDescription
documentSharingThe document to share. Should have and _id and a name

getSharingPolicyForFile(document) ⇒ SharingPolicy

Compute the sharing policy for a File based on its sharing type

Kind: global function
Returns: SharingPolicy - The sharing policy for the File

ParamTypeDescription
documentSharingThe document to share. Should have and _id and a name

getSharingRulesForOrganizations(document) ⇒ Array.<Rule>

Compute the rules that define how to share an Organization. See https://docs.cozy.io/en/cozy-stack/sharing-design/#description-of-a-sharing

Kind: global function
Returns: Array.<Rule> - The rules that define how to share an Organization

ParamTypeDescription
documentSharingThe document to share. Should have and _id and a name

toRelationshipItem(item) ⇒ RelationshipItem

Compute the RelationshipItem that can be referenced as a sharing recipient

Kind: global function
Returns: RelationshipItem - The RelationshipItem that can be referenced as a sharing recipient

ParamTypeDescription
itemRecipientThe recipient of a sharing

getCozyURL()

Get a uniform formatted URL and SSL information according to a provided URL

Kind: global function

joinPath(start, end) ⇒ string

Join two paths together ensuring there is only one slash between them

Kind: global function
Returns: string - The joined path

ParamTypeDescription
startstringThe starting part of the path
endstringThe ending part of the path

FetchChangesReturnValue ⇒ Promise.<FetchChangesReturnValue>

Use Couch _changes API Deleted and design docs are filtered by default, thus documents are retrieved in the response (include_docs is set to true in the parameters of _changes).

You should use fetchChangesRaw to have low level control on _changes parameters.

Kind: global typedef

ParamTypeDescription
couchOptionsobjectCouch options for changes
[couchOptions.since]stringBookmark telling CouchDB from which point in time should changes be returned
[couchOptions.doc_ids]Array.<string>Only return changes for a subset of documents
optionsobjectFurther options on the returned documents. By default, it is set to { includeDesign: false, includeDeleted: false }
[options.includeDesign]booleanWhether to include changes from design docs (needs include_docs to be true)
[options.includeDeleted]booleanWhether to include changes for deleted documents (needs include_docs to be true)

Properties

NameType
newLastSeqstring
documentsArray.<object>

CozyStackClient : module:"./CozyStackClient.js"

Kind: global typedef

cozyStackClient.collection(doctype, options) ⇒ DocumentCollection

Creates a DocumentCollection instance.

Kind: instance method of CozyStackClient

ParamTypeDescription
doctypestringThe collection doctype.
optionsobjectOptions to pass to the collection.

cozyStackClient.fetch(method, path, [body], [opts]) ⇒ object

Fetches an endpoint in an authorized way.

Kind: instance method of CozyStackClient
Throws:

  • FetchError
ParamTypeDefaultDescription
methodstringThe HTTP method.
pathstringThe URI.
[body]objectThe payload.
[opts]object{}Options for fetch

cozyStackClient.refreshToken() ⇒ Promise

Retrieves a new app token by refreshing the currently used token.

Kind: instance method of CozyStackClient
Returns: Promise - A promise that resolves with a new AccessToken object
Throws:

  • Error The client should already have an access token to use this function
  • Error The client couldn't fetch a new token

cozyStackClient.fetchJSON(method, path, body, options) ⇒ object

Fetches JSON in an authorized way.

Kind: instance method of CozyStackClient
Throws:

  • FetchError
ParamTypeDescription
methodstringThe HTTP method.
pathstringThe URI.
bodyobjectThe payload.
optionsobjectOptions

cozyStackClient.setToken(token)

Change or set the API token

Kind: instance method of CozyStackClient

ParamTypeDescription
tokenstring | AppToken | AccessTokenStack API token

cozyStackClient.getAccessToken() ⇒ string

Get the access token string, being an oauth token or an app token

Kind: instance method of CozyStackClient
Returns: string - token

IOCozyFolder : object

Folder

Kind: global typedef

SpecificFileAttributesForKonnector : object

Specific file attributes for creation for konnector

Kind: global typedef
Properties

NameTypeDescription
sourceAccountstringthe id of the source account used by a konnector
sourceAccountIdentifierstringthe unique identifier of the account targeted by the connector

CouchDBViewCursor : Array.<string> | string

Cursor used for Mango queries pagination

Kind: global typedef

DirectoryAttributes : object

Attributes used for directory creation

Kind: global typedef
Properties

NameTypeDescription
dirIdstringId of the parent directory.
namebooleanName of the created directory.
executablebooleanIndicates whether the file will be executable.
[metadata]objectio.cozy.files.metadata to attach to the directory

FileAttributes : object

Attributes used for file creation

Kind: global typedef
Properties

NameTypeDescription
idstringId of the document
_idstringId of the document
dirIdstringId of the parent directory.
namestringName of the created file.
lastModifiedDateDateCan be used to set the last modified date of a file.
executablebooleanWhether or not the file is executable
encryptedbooleanWhether or not the file is client-side encrypted
metadataobjectio.cozy.files.metadata to attach to the file

FileDocument : object

Document representing a io.cozy.files

Kind: global typedef
Properties

NameTypeDescription
_idstringId of the file
_revstringRev of the file
attributesFileAttributesAttributes of the file
metaobjectMeta
relationshipsobjectRelationships
referenced_byobjectReferenced by

Stream : object

Stream is not defined in a browser, but is on NodeJS environment

Kind: global typedef

OAuthClient : object

Document representing a io.cozy.oauth.clients

Kind: global typedef
Properties

NameTypeDescription
_idstringId of the client
_typestringDoctype of the client (i.e. io.cozy.oauth.clients)

oAuthClient.doRegistration()

Performs the HTTP call to register the client to the server

Kind: instance method of OAuthClient

oAuthClient.register() ⇒ Promise

Registers the currenly configured client with the OAuth server and sets internal information from the server response

Kind: instance method of OAuthClient
Returns: Promise - A promise that resolves with a complete list of client information, including client ID and client secret.
Throws:

  • Error When the client is already registered

oAuthClient.unregister() ⇒ Promise

Unregisters the currenly configured client with the OAuth server.

Kind: instance method of OAuthClient
Throws:

  • NotRegisteredException When the client doesn't have it's registration information

oAuthClient.fetchInformation() ⇒ Promise

Fetches the complete set of client information from the server after it has been registered.

Kind: instance method of OAuthClient
Throws:

  • NotRegisteredException When the client doesn't have it's registration information

oAuthClient.updateInformation(information, resetSecret) ⇒ Promise

Overwrites the client own information. This method will update both the local information and the remote information on the OAuth server.

Kind: instance method of OAuthClient
Returns: Promise - Resolves to a complete, updated list of client information
Throws:

  • NotRegisteredException When the client doesn't have it's registration information
ParamTypeDefaultDescription
informationobjectSet of information to update. Note that some fields such as clientID can't be updated.
resetSecretbooleanfalse= false Optionnal, whether to reset the client secret or not

oAuthClient.generateStateCode() ⇒ string

Generates a random state code to be used during the OAuth process

Kind: instance method of OAuthClient

oAuthClient.getAuthCodeURL(options) ⇒ string

Generates the URL that the user should be sent to in order to accept the app's permissions.

Kind: instance method of OAuthClient
Returns: string - The URL
Throws:

  • NotRegisteredException When the client doesn't have it's registration information
ParamTypeDescription
optionsobjectURL generation options
options.stateCodestringA random code to be included in the URl for security. Can be generated with client.generateStateCode()
[options.scopes]ArrayAn array of permission scopes for the token.
[options.sessionCode]SessionCodeA session code that can be used to create a session.
[options.codeChallenge]stringA code challenge that can be used in a PKCE verification process.

oAuthClient.getAccessCodeFromURL(pageURL, stateCode) ⇒ string

Retrieves the access code contained in the URL to which the user is redirected after accepting the app's permissions (the redirectURI).

Kind: instance method of OAuthClient
Returns: string - The access code
Throws:

  • Error The URL should contain the same state code as the one generated with client.getAuthCodeURL(). If not, it will throw an error
ParamTypeDescription
pageURLstringThe redirected page URL, containing the state code and the access code
stateCodestringThe state code that was contained in the original URL the user was sent to (see client.getAuthCodeURL())

oAuthClient.fetchAccessToken(accessCode, oauthOptionsArg, uri, codeVerifier) ⇒ Promise

Exchanges an access code for an access token. This function does not update the client's token.

Kind: instance method of OAuthClient
Returns: Promise - A promise that resolves with an AccessToken object.
Throws:

  • NotRegisteredException When the client doesn't have it's registration information
ParamTypeDescription
accessCodestringThe access code contained in the redirection URL — see client.getAccessCodeFromURL()
oauthOptionsArgobject— To use when OAuthClient is not yet registered (during login process)
uristring— To use when OAuthClient is not yet registered (during login process)
codeVerifierstring— The PKCE code verifier (see https://docs.cozy.io/en/cozy-stack/auth/#pkce-extension)

oAuthClient.fetchKonnectorToken(slug) ⇒ Promise.<string>

Used by the flagship application in order to create a token for the konnector with the given slug. This token can then be used by the client-side konnector to make requests to cozy-stack. The flagship app will need to use its own access token to request the konnector token.

Kind: instance method of OAuthClient
Returns: Promise.<string> - - A promise that resolves with a new token

ParamTypeDescription
slugstringThe slug of the konnector

oAuthClient.fetchSessionCode() ⇒ Promise.<SessionCodeRes>

Fetches a new session code. Only usable by the Flagship application

Kind: instance method of OAuthClient
Returns: Promise.<SessionCodeRes> - A promise that resolves with a new session_code
Throws:

  • NotRegisteredException When the client isn't certified to be the Flagship application

oAuthClient.fetchSessionCodeWithPassword() ⇒ Promise.<SessionCodeRes>

Fetches a new session code. Only usable by the Flagship application

Kind: instance method of OAuthClient
Returns: Promise.<SessionCodeRes> - A promise that resolves with a new session_code
Throws:

  • NotRegisteredException When the client isn't certified to be the Flagship application

oAuthClient.loginFlagship() ⇒ Promise.<(AccessTokenRes|TwoFactorNeededRes|SessionCodeRes)>

Get OAuth access and register tokens without having to make OAuth dance

This endpoint returns registration tokens only from a Flagship app, otherwise it returns a session_code that should be used in an OAuth dance

More info: https://docs.cozy.io/en/cozy-stack/flagship/ More info: https://docs.cozy.io/en/cozy-stack/auth/#post-authloginflagship

Kind: instance method of OAuthClient
Returns: Promise.<(AccessTokenRes|TwoFactorNeededRes|SessionCodeRes)> - A promise that resolves with an access token, a session_code or a 2FA code

oAuthClient.refreshToken() ⇒ Promise

Retrieves a new access token by refreshing the currently used token.

Kind: instance method of OAuthClient
Returns: Promise - A promise that resolves with a new AccessToken object
Throws:

  • NotRegisteredException When the client doesn't have it's registration information
  • Error The client should already have an access token to use this function

oAuthClient.setToken(token)

Updates the client's stored token

Kind: instance method of OAuthClient

ParamTypeDescription
tokenstring= null The new token to use — can be a string, a json object or an AccessToken instance.

oAuthClient.setOAuthOptions(options)

Updates the OAuth informations

Kind: instance method of OAuthClient

ParamTypeDescription
optionsobjectMap of OAuth options

oAuthClient.resetClient()

Reset the current OAuth client

Kind: instance method of OAuthClient

oAuthClient.setPassphraseFlagship(params) ⇒ object

This method should be used in flagship app onboarding process to finalize the cozy creation by setting the user password into the cozy-stack

More info: https://docs.cozy.io/en/cozy-stack/settings/#post-settingspassphraseflagship

Kind: instance method of OAuthClient
Returns: object - token - The OAauth token

ParamTypeDescription
paramsobjectparameters needed to set passphrase
params.registerTokenstringregistration token provided by the onboarding link
params.passwordHashstringhash of the master password
params.hintstringhint for the master password
params.keystringkey (crypted) used for the vault encryption
params.publicKeystringpublic key used for sharing ciphers from the vault
params.privateKeystringprivate key (crypted) used for sharing ciphers from the vault
params.iterationsstringnumber of KDF iterations applied when hashing the master password

oAuthClient.checkForRevocation() ⇒ Promise.<boolean>

Check if the OAuth client's has been revoked. If this is the case, call the onRevocationChange callback

Kind: instance method of OAuthClient
Returns: Promise.<boolean> - A Promise that resolves to false if client is still valid, or true if it has been revoked.

FileCollectionOptions : object

Options that can be passed to FileCollection's constructor

Kind: global typedef
Properties

NameTypeDescription
[driveId]stringID of the shared drive targeted by the collection

ArchivePages : object

Attributes used for create archive link by ids

Kind: global typedef
Properties

NameTypeDescription
idstringId of the file
pagenumberThe page number. PDF files only (1 is the first page)

FetchChangesReturnValue ⇒ FetchChangesReturnValue

Use cozy-stack's _changes API for io.cozy.files Design docs are filtered by default, thus documents are retrieved in the response (includeDocs is set to true in the parameters of _changes). Deleted and trashed documents can be filtered on demand and files' paths can be requested as well.

Since deleted and trashed documents are skipped by cozy-stack rather than CouchDB, when either option is set to true, the response can contain less documents than the defined limit. Thus one should rely solely on the pending result attribute to determine if more documents can be fetched or not.

You should use fetchChangesRaw to call CouchDB's _changes API.

Kind: global typedef

ParamTypeDescription
couchOptionsCouchOptionsCouch options for changes
optionsFetchChangesOptionsFurther options on the returned documents. By default, it is set to { includeFilePath: false, skipDeleted: false, skipTrashed: false }

Properties

NameTypeDescription
sincestringBookmark telling CouchDB from which point in time should changes be returned
limitnumberThe maximum number of returned documents for one call
includeDocsbooleanWhether or not complete documents should be returned
fieldsArray.<string>The list of fields that should be returned for each document
includeFilePathbooleanWhether to include the path of file changes (needs includeDocs to be true)
skipDeletedbooleanWhether to skip changes for deleted documents
skipTrashedbooleanWhether to skip changes for trashed documents (needs includeDocs to be true)
newLastSeqstring
pendingboolean
documentsArray.<object>

JobDocument : object

Document representing a io.cozy.jobs

Kind: global typedef
Properties

NameTypeDescription
_idstringId of the job
attributes.statestringstate of the job. Can be 'errored', 'running', 'queued', 'done'
attributes.errorstringError message of the job if any

MangoPartialFilter : Object

Kind: global typedef

MangoSelector : object

Kind: global typedef

MangoSort : Array.<object>

Kind: global typedef

MangoQueryOptions : object

Kind: global typedef
Properties

NameTypeDescription
[selector]MangoSelectorSelector
[sort]MangoSortThe sorting parameters
[fields]Array.<string>The fields to return
[partialFilterFields]Array.<string>The partial filter fields
[limit]number | nullFor pagination, the number of results to return
[skip]number | nullFor skip-based pagination, the number of referenced files to skip
[indexId]string | nullThe _id of the CouchDB index to use for this request
[bookmark]string | nullFor bookmark-based pagination, the document _id to start from
[indexedFields]Array.<string>
[use_index]stringName of the index to use
[execution_stats]booleanIf true, we request the stats from Couch
[partialFilter]MangoPartialFilter | nullAn optional partial filter

DesignDoc : object

Attributes representing a design doc

Kind: global typedef
Properties

NameTypeDescription
_idstringId of the design doc. Can be named, e.g. '_design/by_indexed_attribute' or not, e.g. '_design/12345'
languagestringThe index language. Can be 'query' for mango index or 'javascript' for views.
viewsobjectViews definition, i.e. the index.
_revstringRev version

CozyStackClient : module:"./CozyStackClient.js"

Kind: global typedef

cozyStackClient.collection(doctype, options) ⇒ DocumentCollection

Creates a DocumentCollection instance.

Kind: instance method of CozyStackClient

ParamTypeDescription
doctypestringThe collection doctype.
optionsobjectOptions to pass to the collection.

cozyStackClient.fetch(method, path, [body], [opts]) ⇒ object

Fetches an endpoint in an authorized way.

Kind: instance method of CozyStackClient
Throws:

  • FetchError
ParamTypeDefaultDescription
methodstringThe HTTP method.
pathstringThe URI.
[body]objectThe payload.
[opts]object{}Options for fetch

cozyStackClient.refreshToken() ⇒ Promise

Retrieves a new app token by refreshing the currently used token.

Kind: instance method of CozyStackClient
Returns: Promise - A promise that resolves with a new AccessToken object
Throws:

  • Error The client should already have an access token to use this function
  • Error The client couldn't fetch a new token

cozyStackClient.fetchJSON(method, path, body, options) ⇒ object

Fetches JSON in an authorized way.

Kind: instance method of CozyStackClient
Throws:

  • FetchError
ParamTypeDescription
methodstringThe HTTP method.
pathstringThe URI.
bodyobjectThe payload.
optionsobjectOptions

cozyStackClient.setToken(token)

Change or set the API token

Kind: instance method of CozyStackClient

ParamTypeDescription
tokenstring | AppToken | AccessTokenStack API token

cozyStackClient.getAccessToken() ⇒ string

Get the access token string, being an oauth token or an app token

Kind: instance method of CozyStackClient
Returns: string - token

NotesCollectionOptions : object

Options that can be passed to NotesCollection's constructor

Kind: global typedef
Properties

NameTypeDescription
[driveId]stringID of the shared drive targeted by the collection

SessionCode : string

Kind: global typedef

SessionCodeRes

Kind: global typedef
Properties

NameTypeDescription
session_codestringThe value of the session code

AccessTokenRes

Kind: global typedef
Properties

NameTypeDescription
email_verified_codestringThe email verified code to skip 2FA
access_tokenstringThe OAuth access token
refresh_tokenstringThe OAuth refresh token
token_typestringThe OAuth token type
scopestringThe OAuth scope

TwoFactorNeededRes

Kind: global typedef
Properties

NameTypeDescription
two_factor_tokenstringThe 2FA token

PermissionCollectionOptions : object

Options that can be passed to PermissionCollection's constructor

Kind: global typedef
Properties

NameTypeDescription
[driveId]stringID of the shared drive targeted by the collection

Permission ⇒ Permission

async getOwnPermissions - deprecated: please use fetchOwnPermissions instead

Kind: global typedef
Returns: Permission - permission

Permission ⇒ Permission

async fetchOwnPermissions - Fetches permissions

Kind: global typedef
Returns: Permission - permission

Rule : object

A sharing rule

Kind: global typedef
Properties

NameType
titlestring
doctypestring
valuesArray
[add]string
[update]string
[remove]string

SharingRulesOptions : object

Kind: global typedef
Properties

NameType
[sharedDrive]boolean

Recipient : object

An io.cozy.contact

Kind: global typedef

Sharing : object

An io.cozy.sharings document

Kind: global typedef

SharingPolicy : object

Define the add/update/remove policies for a sharing

Kind: global typedef
Properties

NameType
addstring
updatestring
removestring

SharingType : undefined | 'one-way' | 'two-way'

Define how a document is synced between sharing's owner and receivers.

Kind: global typedef

RelationshipItem : object

Define a recipient that can be used as target of a sharing

Kind: global typedef
Properties

NameTypeDescription
idstringRecipient's ID
typestringReciptient's type (should be 'io.cozy.contacts')

CozyStackClient : object

Kind: global typedef
Properties

NameTypeDescription
oauthOptionsobjectoauthOptions
uristringCozyUri
fetchfunctionfetchMethod
fetchJSONfunctionfetchJSON

cozyStackClient.collection(doctype, options) ⇒ DocumentCollection

Creates a DocumentCollection instance.

Kind: instance method of CozyStackClient

ParamTypeDescription
doctypestringThe collection doctype.
optionsobjectOptions to pass to the collection.

cozyStackClient.fetch(method, path, [body], [opts]) ⇒ object

Fetches an endpoint in an authorized way.

Kind: instance method of CozyStackClient
Throws:

  • FetchError
ParamTypeDefaultDescription
methodstringThe HTTP method.
pathstringThe URI.
[body]objectThe payload.
[opts]object{}Options for fetch

cozyStackClient.refreshToken() ⇒ Promise

Retrieves a new app token by refreshing the currently used token.

Kind: instance method of CozyStackClient
Returns: Promise - A promise that resolves with a new AccessToken object
Throws:

  • Error The client should already have an access token to use this function
  • Error The client couldn't fetch a new token

cozyStackClient.fetchJSON(method, path, body, options) ⇒ object

Fetches JSON in an authorized way.

Kind: instance method of CozyStackClient
Throws:

  • FetchError
ParamTypeDescription
methodstringThe HTTP method.
pathstringThe URI.
bodyobjectThe payload.
optionsobjectOptions

cozyStackClient.setToken(token)

Change or set the API token

Kind: instance method of CozyStackClient

ParamTypeDescription
tokenstring | AppToken | AccessTokenStack API token

cozyStackClient.getAccessToken() ⇒ string

Get the access token string, being an oauth token or an app token

Kind: instance method of CozyStackClient
Returns: string - token