@unshared/fs 0.6.5 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/createTemporaryDirectory.cjs.map +1 -1
- package/dist/createTemporaryDirectory.js.map +1 -1
- package/dist/createTemporaryFile.cjs.map +1 -1
- package/dist/createTemporaryFile.js.map +1 -1
- package/dist/findAncestor.cjs.map +1 -1
- package/dist/findAncestor.js.map +1 -1
- package/dist/findAncestors.cjs.map +1 -1
- package/dist/findAncestors.js.map +1 -1
- package/dist/glob.cjs.map +1 -1
- package/dist/glob.js.map +1 -1
- package/dist/loadObject.cjs.map +1 -1
- package/dist/loadObject.js.map +1 -1
- package/dist/touch.cjs.map +1 -1
- package/dist/touch.js.map +1 -1
- package/dist/updateFile.cjs.map +1 -1
- package/dist/updateFile.js.map +1 -1
- package/dist/withTemporaryDirectories.cjs.map +1 -1
- package/dist/withTemporaryDirectories.d.ts +29 -0
- package/dist/withTemporaryDirectories.js.map +1 -1
- package/dist/withTemporaryFiles.cjs.map +1 -1
- package/dist/withTemporaryFiles.d.ts +30 -0
- package/dist/withTemporaryFiles.js.map +1 -1
- package/package.json +7 -7
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"createTemporaryDirectory.cjs","sources":["../createTemporaryDirectory.ts"],"sourcesContent":["import { randomInt } from 'node:crypto'\nimport { mkdir, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface CreateTemporaryDirectoryOptions {\n\n /**\n * The directory to create the temporary directory in.\n * Defaults to the system's temporary directory.\n *\n * @default tmpdir()\n */\n directory?: string\n\n /**\n * A function that generates a random string.\n *\n * @default () => Math.random().toString(36).slice(2)\n */\n random?: () => string\n}\n\n/**\n * Create a temporary directory with a random name and return\n * an object containing the directory path, and a function to\n * recursively remove the directory.\n *\n * @param options The options to create the temporary directory.\n * @returns A promise that resolves to the temporary directory object.\n * @example\n * // Create a temporary directory.\n * const [path, remove] = await createTemporaryDirectory()\n *\n * // Do something with the directory.\n * exec(`tar -czf ${path}.tar.gz ${path}`)\n *\n * // Remove the directory.\n * await remove()\n */\nexport async function createTemporaryDirectory(options: CreateTemporaryDirectoryOptions = {}) {\n const {\n directory = tmpdir(),\n random = () => randomInt(0, 1e6).toString(36),\n } = options\n\n // --- Generate a random name.\n const name = random()\n const path = join(directory, name)\n\n // --- Create the directory.\n await mkdir(path, { recursive: true })\n\n // --- Return the path and a function to remove the directory.\n const remove = () => rm(path, { force: true, recursive: true })\n return [path, remove] as const\n}\n"],"names":["tmpdir","randomInt","join","mkdir","rm"],"mappings":";;
|
1
|
+
{"version":3,"file":"createTemporaryDirectory.cjs","sources":["../createTemporaryDirectory.ts"],"sourcesContent":["import { randomInt } from 'node:crypto'\nimport { mkdir, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface CreateTemporaryDirectoryOptions {\n\n /**\n * The directory to create the temporary directory in.\n * Defaults to the system's temporary directory.\n *\n * @default tmpdir()\n */\n directory?: string\n\n /**\n * A function that generates a random string.\n *\n * @default () => Math.random().toString(36).slice(2)\n */\n random?: () => string\n}\n\n/**\n * Create a temporary directory with a random name and return\n * an object containing the directory path, and a function to\n * recursively remove the directory.\n *\n * @param options The options to create the temporary directory.\n * @returns A promise that resolves to the temporary directory object.\n * @example\n * // Create a temporary directory.\n * const [path, remove] = await createTemporaryDirectory()\n *\n * // Do something with the directory.\n * exec(`tar -czf ${path}.tar.gz ${path}`)\n *\n * // Remove the directory.\n * await remove()\n */\nexport async function createTemporaryDirectory(options: CreateTemporaryDirectoryOptions = {}) {\n const {\n directory = tmpdir(),\n random = () => randomInt(0, 1e6).toString(36),\n } = options\n\n // --- Generate a random name.\n const name = random()\n const path = join(directory, name)\n\n // --- Create the directory.\n await mkdir(path, { recursive: true })\n\n // --- Return the path and a function to remove the directory.\n const remove = () => rm(path, { force: true, recursive: true })\n return [path, remove] as const\n}\n"],"names":["tmpdir","randomInt","join","mkdir","rm"],"mappings":";;AAwCA,eAAsB,yBAAyB,UAA2C,IAAI;AAC5F,QAAM;AAAA,IACJ,YAAYA,QAAAA,OAAA;AAAA,IACZ,SAAS,MAAMC,YAAAA,UAAU,GAAG,GAAG,EAAE,SAAS,EAAE;AAAA,EAAA,IAC1C,SAGE,OAAO,OAAA,GACP,OAAOC,UAAAA,KAAK,WAAW,IAAI;AAGjC,SAAA,MAAMC,SAAAA,MAAM,MAAM,EAAE,WAAW,GAAA,CAAM,GAI9B,CAAC,MADO,MAAMC,SAAAA,GAAG,MAAM,EAAE,OAAO,IAAM,WAAW,GAAA,CAAM,CAC1C;AACtB;;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"createTemporaryDirectory.js","sources":["../createTemporaryDirectory.ts"],"sourcesContent":["import { randomInt } from 'node:crypto'\nimport { mkdir, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface CreateTemporaryDirectoryOptions {\n\n /**\n * The directory to create the temporary directory in.\n * Defaults to the system's temporary directory.\n *\n * @default tmpdir()\n */\n directory?: string\n\n /**\n * A function that generates a random string.\n *\n * @default () => Math.random().toString(36).slice(2)\n */\n random?: () => string\n}\n\n/**\n * Create a temporary directory with a random name and return\n * an object containing the directory path, and a function to\n * recursively remove the directory.\n *\n * @param options The options to create the temporary directory.\n * @returns A promise that resolves to the temporary directory object.\n * @example\n * // Create a temporary directory.\n * const [path, remove] = await createTemporaryDirectory()\n *\n * // Do something with the directory.\n * exec(`tar -czf ${path}.tar.gz ${path}`)\n *\n * // Remove the directory.\n * await remove()\n */\nexport async function createTemporaryDirectory(options: CreateTemporaryDirectoryOptions = {}) {\n const {\n directory = tmpdir(),\n random = () => randomInt(0, 1e6).toString(36),\n } = options\n\n // --- Generate a random name.\n const name = random()\n const path = join(directory, name)\n\n // --- Create the directory.\n await mkdir(path, { recursive: true })\n\n // --- Return the path and a function to remove the directory.\n const remove = () => rm(path, { force: true, recursive: true })\n return [path, remove] as const\n}\n"],"names":[],"mappings":";;;;
|
1
|
+
{"version":3,"file":"createTemporaryDirectory.js","sources":["../createTemporaryDirectory.ts"],"sourcesContent":["import { randomInt } from 'node:crypto'\nimport { mkdir, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface CreateTemporaryDirectoryOptions {\n\n /**\n * The directory to create the temporary directory in.\n * Defaults to the system's temporary directory.\n *\n * @default tmpdir()\n */\n directory?: string\n\n /**\n * A function that generates a random string.\n *\n * @default () => Math.random().toString(36).slice(2)\n */\n random?: () => string\n}\n\n/**\n * Create a temporary directory with a random name and return\n * an object containing the directory path, and a function to\n * recursively remove the directory.\n *\n * @param options The options to create the temporary directory.\n * @returns A promise that resolves to the temporary directory object.\n * @example\n * // Create a temporary directory.\n * const [path, remove] = await createTemporaryDirectory()\n *\n * // Do something with the directory.\n * exec(`tar -czf ${path}.tar.gz ${path}`)\n *\n * // Remove the directory.\n * await remove()\n */\nexport async function createTemporaryDirectory(options: CreateTemporaryDirectoryOptions = {}) {\n const {\n directory = tmpdir(),\n random = () => randomInt(0, 1e6).toString(36),\n } = options\n\n // --- Generate a random name.\n const name = random()\n const path = join(directory, name)\n\n // --- Create the directory.\n await mkdir(path, { recursive: true })\n\n // --- Return the path and a function to remove the directory.\n const remove = () => rm(path, { force: true, recursive: true })\n return [path, remove] as const\n}\n"],"names":[],"mappings":";;;;AAwCA,eAAsB,yBAAyB,UAA2C,IAAI;AAC5F,QAAM;AAAA,IACJ,YAAY,OAAA;AAAA,IACZ,SAAS,MAAM,UAAU,GAAG,GAAG,EAAE,SAAS,EAAE;AAAA,EAAA,IAC1C,SAGE,OAAO,OAAA,GACP,OAAO,KAAK,WAAW,IAAI;AAGjC,SAAA,MAAM,MAAM,MAAM,EAAE,WAAW,GAAA,CAAM,GAI9B,CAAC,MADO,MAAM,GAAG,MAAM,EAAE,OAAO,IAAM,WAAW,GAAA,CAAM,CAC1C;AACtB;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"createTemporaryFile.cjs","sources":["../createTemporaryFile.ts"],"sourcesContent":["import { randomInt } from 'node:crypto'\nimport { mkdir, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface CreateTemporaryFileOptions {\n\n /**\n * The directory to create the temporary file in.\n * Defaults to the system's temporary directory.\n *\n * @default tmpdir()\n */\n directory?: string\n\n /**\n * The file extension to use for the temporary file.\n *\n * @default ''\n */\n extension?: string\n\n /**\n * A function that generates a random string.\n *\n * @default () => Math.random().toString(36).slice(2)\n */\n random?: () => string\n}\n\n/**\n * Create a temporary file with a random name and return\n * an object containing the file path, and a function to\n * remove the file.\n *\n * @param content The content to write to the temporary file.\n * @param options The options to create the temporary file.\n * @returns A promise that resolves to the temporary file object.\n * @example\n * // Create a temporary file with the specified content.\n * const [path, remove] = await createTemporaryFile('Hello, world!')\n *\n * // Do something with the file.\n * exec(`openssl sha1 ${path}`)\n *\n * // Remove the file.\n * await remove()\n */\nexport async function createTemporaryFile(content?: Parameters<typeof writeFile>[1], options: CreateTemporaryFileOptions = {}) {\n const {\n directory = tmpdir(),\n extension,\n random = () => randomInt(0, 1e6).toString(36),\n } = options\n\n // --- Generate a random name.\n const rand = random()\n const name = extension ? `${rand}.${extension}` : rand\n const path = join(directory, name)\n\n // --- Write the content to the file.\n await mkdir(directory, { recursive: true })\n await writeFile(path, content ?? '')\n\n // --- Return the path and a function to remove the file.\n const remove = () => rm(path, { force: true })\n return [path, remove] as const\n}\n"],"names":["tmpdir","randomInt","join","mkdir","writeFile","rm"],"mappings":";;AAgDA,eAAsB,oBAAoB,SAA2C,UAAsC,IAAI;
|
1
|
+
{"version":3,"file":"createTemporaryFile.cjs","sources":["../createTemporaryFile.ts"],"sourcesContent":["import { randomInt } from 'node:crypto'\nimport { mkdir, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface CreateTemporaryFileOptions {\n\n /**\n * The directory to create the temporary file in.\n * Defaults to the system's temporary directory.\n *\n * @default tmpdir()\n */\n directory?: string\n\n /**\n * The file extension to use for the temporary file.\n *\n * @default ''\n */\n extension?: string\n\n /**\n * A function that generates a random string.\n *\n * @default () => Math.random().toString(36).slice(2)\n */\n random?: () => string\n}\n\n/**\n * Create a temporary file with a random name and return\n * an object containing the file path, and a function to\n * remove the file.\n *\n * @param content The content to write to the temporary file.\n * @param options The options to create the temporary file.\n * @returns A promise that resolves to the temporary file object.\n * @example\n * // Create a temporary file with the specified content.\n * const [path, remove] = await createTemporaryFile('Hello, world!')\n *\n * // Do something with the file.\n * exec(`openssl sha1 ${path}`)\n *\n * // Remove the file.\n * await remove()\n */\nexport async function createTemporaryFile(content?: Parameters<typeof writeFile>[1], options: CreateTemporaryFileOptions = {}) {\n const {\n directory = tmpdir(),\n extension,\n random = () => randomInt(0, 1e6).toString(36),\n } = options\n\n // --- Generate a random name.\n const rand = random()\n const name = extension ? `${rand}.${extension}` : rand\n const path = join(directory, name)\n\n // --- Write the content to the file.\n await mkdir(directory, { recursive: true })\n await writeFile(path, content ?? '')\n\n // --- Return the path and a function to remove the file.\n const remove = () => rm(path, { force: true })\n return [path, remove] as const\n}\n"],"names":["tmpdir","randomInt","join","mkdir","writeFile","rm"],"mappings":";;AAgDA,eAAsB,oBAAoB,SAA2C,UAAsC,IAAI;AAC7H,QAAM;AAAA,IACJ,YAAYA,QAAAA,OAAA;AAAA,IACZ;AAAA,IACA,SAAS,MAAMC,YAAAA,UAAU,GAAG,GAAG,EAAE,SAAS,EAAE;AAAA,EAAA,IAC1C,SAGE,OAAO,OAAA,GACP,OAAO,YAAY,GAAG,IAAI,IAAI,SAAS,KAAK,MAC5C,OAAOC,UAAAA,KAAK,WAAW,IAAI;AAGjC,SAAA,MAAMC,SAAAA,MAAM,WAAW,EAAE,WAAW,IAAM,GAC1C,MAAMC,SAAAA,UAAU,MAAM,WAAW,EAAE,GAI5B,CAAC,MADO,MAAMC,SAAAA,GAAG,MAAM,EAAE,OAAO,GAAA,CAAM,CACzB;AACtB;;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"createTemporaryFile.js","sources":["../createTemporaryFile.ts"],"sourcesContent":["import { randomInt } from 'node:crypto'\nimport { mkdir, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface CreateTemporaryFileOptions {\n\n /**\n * The directory to create the temporary file in.\n * Defaults to the system's temporary directory.\n *\n * @default tmpdir()\n */\n directory?: string\n\n /**\n * The file extension to use for the temporary file.\n *\n * @default ''\n */\n extension?: string\n\n /**\n * A function that generates a random string.\n *\n * @default () => Math.random().toString(36).slice(2)\n */\n random?: () => string\n}\n\n/**\n * Create a temporary file with a random name and return\n * an object containing the file path, and a function to\n * remove the file.\n *\n * @param content The content to write to the temporary file.\n * @param options The options to create the temporary file.\n * @returns A promise that resolves to the temporary file object.\n * @example\n * // Create a temporary file with the specified content.\n * const [path, remove] = await createTemporaryFile('Hello, world!')\n *\n * // Do something with the file.\n * exec(`openssl sha1 ${path}`)\n *\n * // Remove the file.\n * await remove()\n */\nexport async function createTemporaryFile(content?: Parameters<typeof writeFile>[1], options: CreateTemporaryFileOptions = {}) {\n const {\n directory = tmpdir(),\n extension,\n random = () => randomInt(0, 1e6).toString(36),\n } = options\n\n // --- Generate a random name.\n const rand = random()\n const name = extension ? `${rand}.${extension}` : rand\n const path = join(directory, name)\n\n // --- Write the content to the file.\n await mkdir(directory, { recursive: true })\n await writeFile(path, content ?? '')\n\n // --- Return the path and a function to remove the file.\n const remove = () => rm(path, { force: true })\n return [path, remove] as const\n}\n"],"names":[],"mappings":";;;;AAgDA,eAAsB,oBAAoB,SAA2C,UAAsC,IAAI;
|
1
|
+
{"version":3,"file":"createTemporaryFile.js","sources":["../createTemporaryFile.ts"],"sourcesContent":["import { randomInt } from 'node:crypto'\nimport { mkdir, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface CreateTemporaryFileOptions {\n\n /**\n * The directory to create the temporary file in.\n * Defaults to the system's temporary directory.\n *\n * @default tmpdir()\n */\n directory?: string\n\n /**\n * The file extension to use for the temporary file.\n *\n * @default ''\n */\n extension?: string\n\n /**\n * A function that generates a random string.\n *\n * @default () => Math.random().toString(36).slice(2)\n */\n random?: () => string\n}\n\n/**\n * Create a temporary file with a random name and return\n * an object containing the file path, and a function to\n * remove the file.\n *\n * @param content The content to write to the temporary file.\n * @param options The options to create the temporary file.\n * @returns A promise that resolves to the temporary file object.\n * @example\n * // Create a temporary file with the specified content.\n * const [path, remove] = await createTemporaryFile('Hello, world!')\n *\n * // Do something with the file.\n * exec(`openssl sha1 ${path}`)\n *\n * // Remove the file.\n * await remove()\n */\nexport async function createTemporaryFile(content?: Parameters<typeof writeFile>[1], options: CreateTemporaryFileOptions = {}) {\n const {\n directory = tmpdir(),\n extension,\n random = () => randomInt(0, 1e6).toString(36),\n } = options\n\n // --- Generate a random name.\n const rand = random()\n const name = extension ? `${rand}.${extension}` : rand\n const path = join(directory, name)\n\n // --- Write the content to the file.\n await mkdir(directory, { recursive: true })\n await writeFile(path, content ?? '')\n\n // --- Return the path and a function to remove the file.\n const remove = () => rm(path, { force: true })\n return [path, remove] as const\n}\n"],"names":[],"mappings":";;;;AAgDA,eAAsB,oBAAoB,SAA2C,UAAsC,IAAI;AAC7H,QAAM;AAAA,IACJ,YAAY,OAAA;AAAA,IACZ;AAAA,IACA,SAAS,MAAM,UAAU,GAAG,GAAG,EAAE,SAAS,EAAE;AAAA,EAAA,IAC1C,SAGE,OAAO,OAAA,GACP,OAAO,YAAY,GAAG,IAAI,IAAI,SAAS,KAAK,MAC5C,OAAO,KAAK,WAAW,IAAI;AAGjC,SAAA,MAAM,MAAM,WAAW,EAAE,WAAW,IAAM,GAC1C,MAAM,UAAU,MAAM,WAAW,EAAE,GAI5B,CAAC,MADO,MAAM,GAAG,MAAM,EAAE,OAAO,GAAA,CAAM,CACzB;AACtB;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"findAncestor.cjs","sources":["../findAncestor.ts"],"sourcesContent":["import { access, constants } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\n\n/**\n * Find the first ancestor of a file from a given path. The search will start\n * from the given path and will continue until the root directory is reached.\n * If the file is not found, will throw an error.\n *\n * @param name The file name to find.\n * @param from The path to start from.\n * @returns The absolute path of the file found.\n * @example\n * // Create a file in the root directory.\n * await writeFile('/home/user/file.txt', 'Hello, world!')\n *\n * // Find the file from a subdirectory.\n * await findAncestor('file.txt', '/home/user/project') // '/home/user/file.txt'\n */\nexport async function findAncestor(name: string, from = process.cwd()): Promise<string | undefined> {\n while (from !== '') {\n const absolutePath = resolve(from, name)\n try {\n await access(absolutePath, constants.F_OK)\n return absolutePath\n }\n catch { /* Ignore error. */ }\n\n if (from === '/') break\n from = dirname(from)\n }\n}\n"],"names":["resolve","access","constants","dirname"],"mappings":";;AAkBA,eAAsB,aAAa,MAAc,OAAO,QAAQ,OAAoC;AAClG,SAAO,SAAS,MAAI;
|
1
|
+
{"version":3,"file":"findAncestor.cjs","sources":["../findAncestor.ts"],"sourcesContent":["import { access, constants } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\n\n/**\n * Find the first ancestor of a file from a given path. The search will start\n * from the given path and will continue until the root directory is reached.\n * If the file is not found, will throw an error.\n *\n * @param name The file name to find.\n * @param from The path to start from.\n * @returns The absolute path of the file found.\n * @example\n * // Create a file in the root directory.\n * await writeFile('/home/user/file.txt', 'Hello, world!')\n *\n * // Find the file from a subdirectory.\n * await findAncestor('file.txt', '/home/user/project') // '/home/user/file.txt'\n */\nexport async function findAncestor(name: string, from = process.cwd()): Promise<string | undefined> {\n while (from !== '') {\n const absolutePath = resolve(from, name)\n try {\n await access(absolutePath, constants.F_OK)\n return absolutePath\n }\n catch { /* Ignore error. */ }\n\n if (from === '/') break\n from = dirname(from)\n }\n}\n"],"names":["resolve","access","constants","dirname"],"mappings":";;AAkBA,eAAsB,aAAa,MAAc,OAAO,QAAQ,OAAoC;AAClG,SAAO,SAAS,MAAI;AAClB,UAAM,eAAeA,UAAAA,QAAQ,MAAM,IAAI;AACvC,QAAI;AACF,aAAA,MAAMC,SAAAA,OAAO,cAAcC,SAAAA,UAAU,IAAI,GAClC;AAAA,IACT,QACM;AAAA,IAAsB;AAE5B,QAAI,SAAS,IAAK;AAClB,WAAOC,UAAAA,QAAQ,IAAI;AAAA,EACrB;AACF;;"}
|
package/dist/findAncestor.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"findAncestor.js","sources":["../findAncestor.ts"],"sourcesContent":["import { access, constants } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\n\n/**\n * Find the first ancestor of a file from a given path. The search will start\n * from the given path and will continue until the root directory is reached.\n * If the file is not found, will throw an error.\n *\n * @param name The file name to find.\n * @param from The path to start from.\n * @returns The absolute path of the file found.\n * @example\n * // Create a file in the root directory.\n * await writeFile('/home/user/file.txt', 'Hello, world!')\n *\n * // Find the file from a subdirectory.\n * await findAncestor('file.txt', '/home/user/project') // '/home/user/file.txt'\n */\nexport async function findAncestor(name: string, from = process.cwd()): Promise<string | undefined> {\n while (from !== '') {\n const absolutePath = resolve(from, name)\n try {\n await access(absolutePath, constants.F_OK)\n return absolutePath\n }\n catch { /* Ignore error. */ }\n\n if (from === '/') break\n from = dirname(from)\n }\n}\n"],"names":[],"mappings":";;AAkBA,eAAsB,aAAa,MAAc,OAAO,QAAQ,OAAoC;AAClG,SAAO,SAAS,MAAI;
|
1
|
+
{"version":3,"file":"findAncestor.js","sources":["../findAncestor.ts"],"sourcesContent":["import { access, constants } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\n\n/**\n * Find the first ancestor of a file from a given path. The search will start\n * from the given path and will continue until the root directory is reached.\n * If the file is not found, will throw an error.\n *\n * @param name The file name to find.\n * @param from The path to start from.\n * @returns The absolute path of the file found.\n * @example\n * // Create a file in the root directory.\n * await writeFile('/home/user/file.txt', 'Hello, world!')\n *\n * // Find the file from a subdirectory.\n * await findAncestor('file.txt', '/home/user/project') // '/home/user/file.txt'\n */\nexport async function findAncestor(name: string, from = process.cwd()): Promise<string | undefined> {\n while (from !== '') {\n const absolutePath = resolve(from, name)\n try {\n await access(absolutePath, constants.F_OK)\n return absolutePath\n }\n catch { /* Ignore error. */ }\n\n if (from === '/') break\n from = dirname(from)\n }\n}\n"],"names":[],"mappings":";;AAkBA,eAAsB,aAAa,MAAc,OAAO,QAAQ,OAAoC;AAClG,SAAO,SAAS,MAAI;AAClB,UAAM,eAAe,QAAQ,MAAM,IAAI;AACvC,QAAI;AACF,aAAA,MAAM,OAAO,cAAc,UAAU,IAAI,GAClC;AAAA,IACT,QACM;AAAA,IAAsB;AAE5B,QAAI,SAAS,IAAK;AAClB,WAAO,QAAQ,IAAI;AAAA,EACrB;AACF;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"findAncestors.cjs","sources":["../findAncestors.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { access, constants } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\n\n/**\n * Find all ancestors of a file from a given path. The search will start\n * from the given path and will continue until the root directory is reached.\n * If the file is not found, an empty array will be returned.\n *\n * @param name The file name to find.\n * @param from The path to start from.\n * @returns An awaitable iterator of the absolute paths of the files found.\n * @example\n * // Get all ancestors as an array.\n * const ancestors = await findAncestors('file', '/home/user/project')\n *\n * // Or, iterate over the ancestors one by one.\n * const ancestors = findAncestors('file', '/home/user/project')\n * for await (const ancestor of ancestors) console.log(ancestor)\n */\nexport function findAncestors(name: string, from = process.cwd()): Awaitable<AsyncIterable<string>, string[]> {\n async function * createIterator() {\n while (from !== '') {\n const absolutePath = resolve(from, name)\n try {\n await access(absolutePath, constants.F_OK)\n yield absolutePath\n }\n catch {\n\n /** Ignore error. */\n }\n if (from === '/') break\n from = dirname(from)\n }\n }\n\n // --- Instantiate the iterator and wrap it in an awaitable.\n const iterator = createIterator()\n return awaitable(iterator)\n}\n"],"names":["resolve","access","constants","dirname","awaitable"],"mappings":";;AAqBO,SAAS,cAAc,MAAc,OAAO,QAAQ,OAAmD;AAC5G,kBAAiB,iBAAiB;AAChC,WAAO,SAAS,MAAI;
|
1
|
+
{"version":3,"file":"findAncestors.cjs","sources":["../findAncestors.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { access, constants } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\n\n/**\n * Find all ancestors of a file from a given path. The search will start\n * from the given path and will continue until the root directory is reached.\n * If the file is not found, an empty array will be returned.\n *\n * @param name The file name to find.\n * @param from The path to start from.\n * @returns An awaitable iterator of the absolute paths of the files found.\n * @example\n * // Get all ancestors as an array.\n * const ancestors = await findAncestors('file', '/home/user/project')\n *\n * // Or, iterate over the ancestors one by one.\n * const ancestors = findAncestors('file', '/home/user/project')\n * for await (const ancestor of ancestors) console.log(ancestor)\n */\nexport function findAncestors(name: string, from = process.cwd()): Awaitable<AsyncIterable<string>, string[]> {\n async function * createIterator() {\n while (from !== '') {\n const absolutePath = resolve(from, name)\n try {\n await access(absolutePath, constants.F_OK)\n yield absolutePath\n }\n catch {\n\n /** Ignore error. */\n }\n if (from === '/') break\n from = dirname(from)\n }\n }\n\n // --- Instantiate the iterator and wrap it in an awaitable.\n const iterator = createIterator()\n return awaitable(iterator)\n}\n"],"names":["resolve","access","constants","dirname","awaitable"],"mappings":";;AAqBO,SAAS,cAAc,MAAc,OAAO,QAAQ,OAAmD;AAC5G,kBAAiB,iBAAiB;AAChC,WAAO,SAAS,MAAI;AAClB,YAAM,eAAeA,UAAAA,QAAQ,MAAM,IAAI;AACvC,UAAI;AACF,cAAMC,SAAAA,OAAO,cAAcC,SAAAA,UAAU,IAAI,GACzC,MAAM;AAAA,MACR,QACM;AAAA,MAGN;AACA,UAAI,SAAS,IAAK;AAClB,aAAOC,UAAAA,QAAQ,IAAI;AAAA,IACrB;AAAA,EACF;AAGA,QAAM,WAAW,eAAA;AACjB,SAAOC,UAAAA,UAAU,QAAQ;AAC3B;;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"findAncestors.js","sources":["../findAncestors.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { access, constants } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\n\n/**\n * Find all ancestors of a file from a given path. The search will start\n * from the given path and will continue until the root directory is reached.\n * If the file is not found, an empty array will be returned.\n *\n * @param name The file name to find.\n * @param from The path to start from.\n * @returns An awaitable iterator of the absolute paths of the files found.\n * @example\n * // Get all ancestors as an array.\n * const ancestors = await findAncestors('file', '/home/user/project')\n *\n * // Or, iterate over the ancestors one by one.\n * const ancestors = findAncestors('file', '/home/user/project')\n * for await (const ancestor of ancestors) console.log(ancestor)\n */\nexport function findAncestors(name: string, from = process.cwd()): Awaitable<AsyncIterable<string>, string[]> {\n async function * createIterator() {\n while (from !== '') {\n const absolutePath = resolve(from, name)\n try {\n await access(absolutePath, constants.F_OK)\n yield absolutePath\n }\n catch {\n\n /** Ignore error. */\n }\n if (from === '/') break\n from = dirname(from)\n }\n }\n\n // --- Instantiate the iterator and wrap it in an awaitable.\n const iterator = createIterator()\n return awaitable(iterator)\n}\n"],"names":[],"mappings":";;;AAqBO,SAAS,cAAc,MAAc,OAAO,QAAQ,OAAmD;AAC5G,kBAAiB,iBAAiB;AAChC,WAAO,SAAS,MAAI;
|
1
|
+
{"version":3,"file":"findAncestors.js","sources":["../findAncestors.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { access, constants } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\n\n/**\n * Find all ancestors of a file from a given path. The search will start\n * from the given path and will continue until the root directory is reached.\n * If the file is not found, an empty array will be returned.\n *\n * @param name The file name to find.\n * @param from The path to start from.\n * @returns An awaitable iterator of the absolute paths of the files found.\n * @example\n * // Get all ancestors as an array.\n * const ancestors = await findAncestors('file', '/home/user/project')\n *\n * // Or, iterate over the ancestors one by one.\n * const ancestors = findAncestors('file', '/home/user/project')\n * for await (const ancestor of ancestors) console.log(ancestor)\n */\nexport function findAncestors(name: string, from = process.cwd()): Awaitable<AsyncIterable<string>, string[]> {\n async function * createIterator() {\n while (from !== '') {\n const absolutePath = resolve(from, name)\n try {\n await access(absolutePath, constants.F_OK)\n yield absolutePath\n }\n catch {\n\n /** Ignore error. */\n }\n if (from === '/') break\n from = dirname(from)\n }\n }\n\n // --- Instantiate the iterator and wrap it in an awaitable.\n const iterator = createIterator()\n return awaitable(iterator)\n}\n"],"names":[],"mappings":";;;AAqBO,SAAS,cAAc,MAAc,OAAO,QAAQ,OAAmD;AAC5G,kBAAiB,iBAAiB;AAChC,WAAO,SAAS,MAAI;AAClB,YAAM,eAAe,QAAQ,MAAM,IAAI;AACvC,UAAI;AACF,cAAM,OAAO,cAAc,UAAU,IAAI,GACzC,MAAM;AAAA,MACR,QACM;AAAA,MAGN;AACA,UAAI,SAAS,IAAK;AAClB,aAAO,QAAQ,IAAI;AAAA,IACrB;AAAA,EACF;AAGA,QAAM,WAAW,eAAA;AACjB,SAAO,UAAU,QAAQ;AAC3B;"}
|
package/dist/glob.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"glob.cjs","sources":["../glob.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { MaybeArray } from '@unshared/types'\nimport type { Stats } from 'node:fs'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { createPattern } from '@unshared/string/createPattern'\nimport { readdir, stat } from 'node:fs/promises'\nimport { join, relative } from 'node:path'\n\n/**\n * An entry in the glob result iterator or array.\n */\nexport type GlobEntry = Stats | string\n\n/**\n * The result of a glob operation. If `Stat` is `true` the result will be an\n * array of file stats. Otherwise the result will be an array of file paths.\n */\nexport type GlobResult<T extends boolean = boolean> = T extends true\n ? Awaitable<AsyncIterable<Stats>, Stats[]>\n : Awaitable<AsyncIterable<string>, string[]>\n\nexport interface GlobOptions<Stat extends boolean = boolean> {\n\n /**\n * The current working directory. Used to determine the base path for the glob\n * pattern.\n *\n * @default process.cwd()\n */\n cwd?: string\n\n /**\n * A list of patterns to exclude from the result.\n *\n * @default []\n */\n exclude?: MaybeArray<string>\n\n /**\n * Return the paths relative to the current working directory. Will be ignored\n * if `stats` is `true`.\n *\n * @default false\n */\n getRelative?: boolean\n\n /**\n * Return the file stats instead of the file path. Allowing you to filter-out\n * files based on their stats.\n *\n * @default false\n */\n getStats?: Stat\n\n /**\n * If `true` and the glob pattern will only match directories.\n *\n * @default false\n * @example glob('src/**', { onlyDirectories: true }) // ['src/foo', 'src/foo/bar']\n */\n onlyDirectories?: boolean\n\n /**\n * Only return entries that matches the path of a file.\n *\n * @default false\n * @example glob('src/**', { onlyFiles: true }) // ['src/foo.ts', 'src/foo/bar.ts']\n */\n onlyFiles?: boolean\n}\n\n/**\n * Find files matching a glob pattern.\n *\n * @param pattern The glob pattern.\n * @param options The glob options.\n * @returns An awaitable asyncronous iterator of file paths.\n * @example\n * const files = glob('src/*.ts')\n * for await (const file of files) { ... }\n */\nexport function glob(pattern: MaybeArray<string>, options?: GlobOptions<false>): GlobResult<false>\nexport function glob(pattern: MaybeArray<string>, options?: GlobOptions<true>): GlobResult<true>\nexport function glob<T extends boolean>(pattern: MaybeArray<string>, options?: GlobOptions<T>): GlobResult<T>\nexport function glob(pattern: MaybeArray<string>, options: GlobOptions = {}): GlobResult {\n const {\n cwd = process.cwd(),\n exclude = [],\n getRelative = false,\n getStats = false,\n onlyDirectories = false,\n onlyFiles = false,\n } = options\n\n // --- Convert the pattern to an array of RegExp.\n const patternArray = Array.isArray(pattern) ? pattern : [pattern]\n const patterns = patternArray.map(pattern => createPattern(pattern))\n const exludeArray = Array.isArray(exclude) ? exclude : [exclude]\n const excludePatterns = exludeArray.map(pattern => createPattern(pattern))\n\n // --- Create an iterator that will yield the matching paths.\n const searchPool: string[] = [cwd]\n async function * createIterator() {\n while (searchPool.length > 0) {\n const directory = searchPool.pop()!\n const entities = await readdir(directory, { withFileTypes: true }).catch(() => [])\n\n for (const entity of entities) {\n const pathAbsolute = join(directory, entity.name)\n const pathRelative = relative(cwd, pathAbsolute)\n const isFile = entity.isFile()\n const isDirectory = entity.isDirectory()\n\n // --- Add the directory to the list of directories to check.\n if (isDirectory) searchPool.push(pathAbsolute)\n\n // --- Filter-out the non-matching entries.\n if (onlyFiles && !isFile) continue\n if (onlyDirectories && !isDirectory) continue\n\n // --- Check if the path matches the pattern(s).\n const isMatch = patterns.some(pattern => pattern.test(pathRelative))\n if (!isMatch) continue\n\n // --- Check if the path matches the exclude pattern(s).\n const isExcluded = excludePatterns.some(pattern => pattern.test(pathRelative))\n if (isExcluded) continue\n\n // --- Return the result.\n let result: GlobEntry = pathAbsolute\n if (getStats) result = await stat(pathAbsolute)\n if (getRelative) result = `./${pathRelative}`\n yield result\n }\n }\n }\n\n // --- Instantiate the iterator.\n const iterator = createIterator()\n\n // --- Return the iterator or the result as an array.\n return awaitable(iterator) as GlobResult\n}\n"],"names":["pattern","createPattern","readdir","join","relative","stat","awaitable"],"mappings":";;AAoFO,SAAS,KAAK,SAA6B,UAAuB,IAAgB;
|
1
|
+
{"version":3,"file":"glob.cjs","sources":["../glob.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { MaybeArray } from '@unshared/types'\nimport type { Stats } from 'node:fs'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { createPattern } from '@unshared/string/createPattern'\nimport { readdir, stat } from 'node:fs/promises'\nimport { join, relative } from 'node:path'\n\n/**\n * An entry in the glob result iterator or array.\n */\nexport type GlobEntry = Stats | string\n\n/**\n * The result of a glob operation. If `Stat` is `true` the result will be an\n * array of file stats. Otherwise the result will be an array of file paths.\n */\nexport type GlobResult<T extends boolean = boolean> = T extends true\n ? Awaitable<AsyncIterable<Stats>, Stats[]>\n : Awaitable<AsyncIterable<string>, string[]>\n\nexport interface GlobOptions<Stat extends boolean = boolean> {\n\n /**\n * The current working directory. Used to determine the base path for the glob\n * pattern.\n *\n * @default process.cwd()\n */\n cwd?: string\n\n /**\n * A list of patterns to exclude from the result.\n *\n * @default []\n */\n exclude?: MaybeArray<string>\n\n /**\n * Return the paths relative to the current working directory. Will be ignored\n * if `stats` is `true`.\n *\n * @default false\n */\n getRelative?: boolean\n\n /**\n * Return the file stats instead of the file path. Allowing you to filter-out\n * files based on their stats.\n *\n * @default false\n */\n getStats?: Stat\n\n /**\n * If `true` and the glob pattern will only match directories.\n *\n * @default false\n * @example glob('src/**', { onlyDirectories: true }) // ['src/foo', 'src/foo/bar']\n */\n onlyDirectories?: boolean\n\n /**\n * Only return entries that matches the path of a file.\n *\n * @default false\n * @example glob('src/**', { onlyFiles: true }) // ['src/foo.ts', 'src/foo/bar.ts']\n */\n onlyFiles?: boolean\n}\n\n/**\n * Find files matching a glob pattern.\n *\n * @param pattern The glob pattern.\n * @param options The glob options.\n * @returns An awaitable asyncronous iterator of file paths.\n * @example\n * const files = glob('src/*.ts')\n * for await (const file of files) { ... }\n */\nexport function glob(pattern: MaybeArray<string>, options?: GlobOptions<false>): GlobResult<false>\nexport function glob(pattern: MaybeArray<string>, options?: GlobOptions<true>): GlobResult<true>\nexport function glob<T extends boolean>(pattern: MaybeArray<string>, options?: GlobOptions<T>): GlobResult<T>\nexport function glob(pattern: MaybeArray<string>, options: GlobOptions = {}): GlobResult {\n const {\n cwd = process.cwd(),\n exclude = [],\n getRelative = false,\n getStats = false,\n onlyDirectories = false,\n onlyFiles = false,\n } = options\n\n // --- Convert the pattern to an array of RegExp.\n const patternArray = Array.isArray(pattern) ? pattern : [pattern]\n const patterns = patternArray.map(pattern => createPattern(pattern))\n const exludeArray = Array.isArray(exclude) ? exclude : [exclude]\n const excludePatterns = exludeArray.map(pattern => createPattern(pattern))\n\n // --- Create an iterator that will yield the matching paths.\n const searchPool: string[] = [cwd]\n async function * createIterator() {\n while (searchPool.length > 0) {\n const directory = searchPool.pop()!\n const entities = await readdir(directory, { withFileTypes: true }).catch(() => [])\n\n for (const entity of entities) {\n const pathAbsolute = join(directory, entity.name)\n const pathRelative = relative(cwd, pathAbsolute)\n const isFile = entity.isFile()\n const isDirectory = entity.isDirectory()\n\n // --- Add the directory to the list of directories to check.\n if (isDirectory) searchPool.push(pathAbsolute)\n\n // --- Filter-out the non-matching entries.\n if (onlyFiles && !isFile) continue\n if (onlyDirectories && !isDirectory) continue\n\n // --- Check if the path matches the pattern(s).\n const isMatch = patterns.some(pattern => pattern.test(pathRelative))\n if (!isMatch) continue\n\n // --- Check if the path matches the exclude pattern(s).\n const isExcluded = excludePatterns.some(pattern => pattern.test(pathRelative))\n if (isExcluded) continue\n\n // --- Return the result.\n let result: GlobEntry = pathAbsolute\n if (getStats) result = await stat(pathAbsolute)\n if (getRelative) result = `./${pathRelative}`\n yield result\n }\n }\n }\n\n // --- Instantiate the iterator.\n const iterator = createIterator()\n\n // --- Return the iterator or the result as an array.\n return awaitable(iterator) as GlobResult\n}\n"],"names":["pattern","createPattern","readdir","join","relative","stat","awaitable"],"mappings":";;AAoFO,SAAS,KAAK,SAA6B,UAAuB,IAAgB;AACvF,QAAM;AAAA,IACJ,MAAM,QAAQ,IAAA;AAAA,IACd,UAAU,CAAA;AAAA,IACV,cAAc;AAAA,IACd,WAAW;AAAA,IACX,kBAAkB;AAAA,IAClB,YAAY;AAAA,EAAA,IACV,SAIE,YADe,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO,GAClC,IAAI,CAAAA,aAAWC,cAAAA,cAAcD,QAAO,CAAC,GAE7D,mBADc,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO,GAC3B,IAAI,CAAAA,aAAWC,cAAAA,cAAcD,QAAO,CAAC,GAGnE,aAAuB,CAAC,GAAG;AACjC,kBAAiB,iBAAiB;AAChC,WAAO,WAAW,SAAS,KAAG;AAC5B,YAAM,YAAY,WAAW,IAAA,GACvB,WAAW,MAAME,SAAAA,QAAQ,WAAW,EAAE,eAAe,IAAM,EAAE,MAAM,MAAM,CAAA,CAAE;AAEjF,iBAAW,UAAU,UAAU;AAC7B,cAAM,eAAeC,UAAAA,KAAK,WAAW,OAAO,IAAI,GAC1C,eAAeC,UAAAA,SAAS,KAAK,YAAY,GACzC,SAAS,OAAO,UAChB,cAAc,OAAO,YAAA;AAe3B,YAZI,eAAa,WAAW,KAAK,YAAY,GAGzC,aAAa,CAAC,UACd,mBAAmB,CAAC,eAIpB,CADY,SAAS,KAAK,CAAAJ,aAAWA,SAAQ,KAAK,YAAY,CAAC,KAIhD,gBAAgB,KAAK,CAAAA,aAAWA,SAAQ,KAAK,YAAY,CAAC,EAC7D;AAGhB,YAAI,SAAoB;AACpB,qBAAU,SAAS,MAAMK,cAAK,YAAY,IAC1C,gBAAa,SAAS,KAAK,YAAY,KAC3C,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAGA,QAAM,WAAW,eAAA;AAGjB,SAAOC,UAAAA,UAAU,QAAQ;AAC3B;;"}
|
package/dist/glob.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"glob.js","sources":["../glob.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { MaybeArray } from '@unshared/types'\nimport type { Stats } from 'node:fs'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { createPattern } from '@unshared/string/createPattern'\nimport { readdir, stat } from 'node:fs/promises'\nimport { join, relative } from 'node:path'\n\n/**\n * An entry in the glob result iterator or array.\n */\nexport type GlobEntry = Stats | string\n\n/**\n * The result of a glob operation. If `Stat` is `true` the result will be an\n * array of file stats. Otherwise the result will be an array of file paths.\n */\nexport type GlobResult<T extends boolean = boolean> = T extends true\n ? Awaitable<AsyncIterable<Stats>, Stats[]>\n : Awaitable<AsyncIterable<string>, string[]>\n\nexport interface GlobOptions<Stat extends boolean = boolean> {\n\n /**\n * The current working directory. Used to determine the base path for the glob\n * pattern.\n *\n * @default process.cwd()\n */\n cwd?: string\n\n /**\n * A list of patterns to exclude from the result.\n *\n * @default []\n */\n exclude?: MaybeArray<string>\n\n /**\n * Return the paths relative to the current working directory. Will be ignored\n * if `stats` is `true`.\n *\n * @default false\n */\n getRelative?: boolean\n\n /**\n * Return the file stats instead of the file path. Allowing you to filter-out\n * files based on their stats.\n *\n * @default false\n */\n getStats?: Stat\n\n /**\n * If `true` and the glob pattern will only match directories.\n *\n * @default false\n * @example glob('src/**', { onlyDirectories: true }) // ['src/foo', 'src/foo/bar']\n */\n onlyDirectories?: boolean\n\n /**\n * Only return entries that matches the path of a file.\n *\n * @default false\n * @example glob('src/**', { onlyFiles: true }) // ['src/foo.ts', 'src/foo/bar.ts']\n */\n onlyFiles?: boolean\n}\n\n/**\n * Find files matching a glob pattern.\n *\n * @param pattern The glob pattern.\n * @param options The glob options.\n * @returns An awaitable asyncronous iterator of file paths.\n * @example\n * const files = glob('src/*.ts')\n * for await (const file of files) { ... }\n */\nexport function glob(pattern: MaybeArray<string>, options?: GlobOptions<false>): GlobResult<false>\nexport function glob(pattern: MaybeArray<string>, options?: GlobOptions<true>): GlobResult<true>\nexport function glob<T extends boolean>(pattern: MaybeArray<string>, options?: GlobOptions<T>): GlobResult<T>\nexport function glob(pattern: MaybeArray<string>, options: GlobOptions = {}): GlobResult {\n const {\n cwd = process.cwd(),\n exclude = [],\n getRelative = false,\n getStats = false,\n onlyDirectories = false,\n onlyFiles = false,\n } = options\n\n // --- Convert the pattern to an array of RegExp.\n const patternArray = Array.isArray(pattern) ? pattern : [pattern]\n const patterns = patternArray.map(pattern => createPattern(pattern))\n const exludeArray = Array.isArray(exclude) ? exclude : [exclude]\n const excludePatterns = exludeArray.map(pattern => createPattern(pattern))\n\n // --- Create an iterator that will yield the matching paths.\n const searchPool: string[] = [cwd]\n async function * createIterator() {\n while (searchPool.length > 0) {\n const directory = searchPool.pop()!\n const entities = await readdir(directory, { withFileTypes: true }).catch(() => [])\n\n for (const entity of entities) {\n const pathAbsolute = join(directory, entity.name)\n const pathRelative = relative(cwd, pathAbsolute)\n const isFile = entity.isFile()\n const isDirectory = entity.isDirectory()\n\n // --- Add the directory to the list of directories to check.\n if (isDirectory) searchPool.push(pathAbsolute)\n\n // --- Filter-out the non-matching entries.\n if (onlyFiles && !isFile) continue\n if (onlyDirectories && !isDirectory) continue\n\n // --- Check if the path matches the pattern(s).\n const isMatch = patterns.some(pattern => pattern.test(pathRelative))\n if (!isMatch) continue\n\n // --- Check if the path matches the exclude pattern(s).\n const isExcluded = excludePatterns.some(pattern => pattern.test(pathRelative))\n if (isExcluded) continue\n\n // --- Return the result.\n let result: GlobEntry = pathAbsolute\n if (getStats) result = await stat(pathAbsolute)\n if (getRelative) result = `./${pathRelative}`\n yield result\n }\n }\n }\n\n // --- Instantiate the iterator.\n const iterator = createIterator()\n\n // --- Return the iterator or the result as an array.\n return awaitable(iterator) as GlobResult\n}\n"],"names":["pattern"],"mappings":";;;;AAoFO,SAAS,KAAK,SAA6B,UAAuB,IAAgB;
|
1
|
+
{"version":3,"file":"glob.js","sources":["../glob.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { MaybeArray } from '@unshared/types'\nimport type { Stats } from 'node:fs'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { createPattern } from '@unshared/string/createPattern'\nimport { readdir, stat } from 'node:fs/promises'\nimport { join, relative } from 'node:path'\n\n/**\n * An entry in the glob result iterator or array.\n */\nexport type GlobEntry = Stats | string\n\n/**\n * The result of a glob operation. If `Stat` is `true` the result will be an\n * array of file stats. Otherwise the result will be an array of file paths.\n */\nexport type GlobResult<T extends boolean = boolean> = T extends true\n ? Awaitable<AsyncIterable<Stats>, Stats[]>\n : Awaitable<AsyncIterable<string>, string[]>\n\nexport interface GlobOptions<Stat extends boolean = boolean> {\n\n /**\n * The current working directory. Used to determine the base path for the glob\n * pattern.\n *\n * @default process.cwd()\n */\n cwd?: string\n\n /**\n * A list of patterns to exclude from the result.\n *\n * @default []\n */\n exclude?: MaybeArray<string>\n\n /**\n * Return the paths relative to the current working directory. Will be ignored\n * if `stats` is `true`.\n *\n * @default false\n */\n getRelative?: boolean\n\n /**\n * Return the file stats instead of the file path. Allowing you to filter-out\n * files based on their stats.\n *\n * @default false\n */\n getStats?: Stat\n\n /**\n * If `true` and the glob pattern will only match directories.\n *\n * @default false\n * @example glob('src/**', { onlyDirectories: true }) // ['src/foo', 'src/foo/bar']\n */\n onlyDirectories?: boolean\n\n /**\n * Only return entries that matches the path of a file.\n *\n * @default false\n * @example glob('src/**', { onlyFiles: true }) // ['src/foo.ts', 'src/foo/bar.ts']\n */\n onlyFiles?: boolean\n}\n\n/**\n * Find files matching a glob pattern.\n *\n * @param pattern The glob pattern.\n * @param options The glob options.\n * @returns An awaitable asyncronous iterator of file paths.\n * @example\n * const files = glob('src/*.ts')\n * for await (const file of files) { ... }\n */\nexport function glob(pattern: MaybeArray<string>, options?: GlobOptions<false>): GlobResult<false>\nexport function glob(pattern: MaybeArray<string>, options?: GlobOptions<true>): GlobResult<true>\nexport function glob<T extends boolean>(pattern: MaybeArray<string>, options?: GlobOptions<T>): GlobResult<T>\nexport function glob(pattern: MaybeArray<string>, options: GlobOptions = {}): GlobResult {\n const {\n cwd = process.cwd(),\n exclude = [],\n getRelative = false,\n getStats = false,\n onlyDirectories = false,\n onlyFiles = false,\n } = options\n\n // --- Convert the pattern to an array of RegExp.\n const patternArray = Array.isArray(pattern) ? pattern : [pattern]\n const patterns = patternArray.map(pattern => createPattern(pattern))\n const exludeArray = Array.isArray(exclude) ? exclude : [exclude]\n const excludePatterns = exludeArray.map(pattern => createPattern(pattern))\n\n // --- Create an iterator that will yield the matching paths.\n const searchPool: string[] = [cwd]\n async function * createIterator() {\n while (searchPool.length > 0) {\n const directory = searchPool.pop()!\n const entities = await readdir(directory, { withFileTypes: true }).catch(() => [])\n\n for (const entity of entities) {\n const pathAbsolute = join(directory, entity.name)\n const pathRelative = relative(cwd, pathAbsolute)\n const isFile = entity.isFile()\n const isDirectory = entity.isDirectory()\n\n // --- Add the directory to the list of directories to check.\n if (isDirectory) searchPool.push(pathAbsolute)\n\n // --- Filter-out the non-matching entries.\n if (onlyFiles && !isFile) continue\n if (onlyDirectories && !isDirectory) continue\n\n // --- Check if the path matches the pattern(s).\n const isMatch = patterns.some(pattern => pattern.test(pathRelative))\n if (!isMatch) continue\n\n // --- Check if the path matches the exclude pattern(s).\n const isExcluded = excludePatterns.some(pattern => pattern.test(pathRelative))\n if (isExcluded) continue\n\n // --- Return the result.\n let result: GlobEntry = pathAbsolute\n if (getStats) result = await stat(pathAbsolute)\n if (getRelative) result = `./${pathRelative}`\n yield result\n }\n }\n }\n\n // --- Instantiate the iterator.\n const iterator = createIterator()\n\n // --- Return the iterator or the result as an array.\n return awaitable(iterator) as GlobResult\n}\n"],"names":["pattern"],"mappings":";;;;AAoFO,SAAS,KAAK,SAA6B,UAAuB,IAAgB;AACvF,QAAM;AAAA,IACJ,MAAM,QAAQ,IAAA;AAAA,IACd,UAAU,CAAA;AAAA,IACV,cAAc;AAAA,IACd,WAAW;AAAA,IACX,kBAAkB;AAAA,IAClB,YAAY;AAAA,EAAA,IACV,SAIE,YADe,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO,GAClC,IAAI,CAAAA,aAAW,cAAcA,QAAO,CAAC,GAE7D,mBADc,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO,GAC3B,IAAI,CAAAA,aAAW,cAAcA,QAAO,CAAC,GAGnE,aAAuB,CAAC,GAAG;AACjC,kBAAiB,iBAAiB;AAChC,WAAO,WAAW,SAAS,KAAG;AAC5B,YAAM,YAAY,WAAW,IAAA,GACvB,WAAW,MAAM,QAAQ,WAAW,EAAE,eAAe,IAAM,EAAE,MAAM,MAAM,CAAA,CAAE;AAEjF,iBAAW,UAAU,UAAU;AAC7B,cAAM,eAAe,KAAK,WAAW,OAAO,IAAI,GAC1C,eAAe,SAAS,KAAK,YAAY,GACzC,SAAS,OAAO,UAChB,cAAc,OAAO,YAAA;AAe3B,YAZI,eAAa,WAAW,KAAK,YAAY,GAGzC,aAAa,CAAC,UACd,mBAAmB,CAAC,eAIpB,CADY,SAAS,KAAK,CAAAA,aAAWA,SAAQ,KAAK,YAAY,CAAC,KAIhD,gBAAgB,KAAK,CAAAA,aAAWA,SAAQ,KAAK,YAAY,CAAC,EAC7D;AAGhB,YAAI,SAAoB;AACpB,qBAAU,SAAS,MAAM,KAAK,YAAY,IAC1C,gBAAa,SAAS,KAAK,YAAY,KAC3C,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAGA,QAAM,WAAW,eAAA;AAGjB,SAAO,UAAU,QAAQ;AAC3B;"}
|
package/dist/loadObject.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"loadObject.cjs","sources":["../loadObject.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { Reactive, ReactiveOptions } from '@unshared/reactivity/reactive'\nimport type { FSWatcher, PathLike, Stats, WatchOptions } from 'node:fs'\nimport { overwrite } from '@unshared/collection/overwrite'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { reactive } from '@unshared/reactivity/reactive'\nimport { EventEmitter } from 'node:events'\nimport { constants, watch } from 'node:fs'\nimport { access, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface FSObjectOptions<T extends object> extends ReactiveOptions<T>, WatchOptions {\n\n /**\n * If set to `true` and the file does not exist, the file will be created\n * if it does not exist and the object will be initialized with an empty\n * object.\n *\n * @default false\n */\n createIfNotExists?: boolean\n\n /**\n * If set to `true`, the file will be deleted when the instance is destroyed.\n * Allowing you to create temporary files that will be deleted when the\n * instance is garbage collected.\n */\n deleteOnDestroy?: boolean\n\n /**\n * If set to `true`, changes on the file will not be reflected in the object.\n * You can use this to prevent the object from being updated when you are\n * making changes to the file.\n *\n * @default false\n */\n ignoreFileChanges?: boolean\n\n /**\n * If set to `true`, changes on the object will be reflected in the file.\n * You can set this to `false` if you want to make multiple changes to the\n * object without triggering multiple file updates.\n *\n * @default false\n */\n ignoreObjectChanges?: boolean\n\n /**\n * The initial value of the object. If the file does not exist, the object\n * will be initialized with this value.\n *\n * @default {}\n */\n initialValue?: T\n\n /**\n * The parser function to use when reading the file. If not set, the file\n * will be parsed as JSON using the native `JSON.parse` function.\n *\n * @default JSON.parse\n */\n parse?: (json: string) => T\n\n /**\n * The stringifier function to use when writing the file. If not set, the\n * object will be stringified as JSON using the native `JSON.stringify` function.\n *\n * @default JSON.stringify\n */\n serialize?: (object: T) => string\n}\n\nexport interface FSObjectEventMap<T extends object> {\n commit: [T]\n destroy: []\n load: [T]\n lock: []\n unlock: []\n}\n\n// eslint-disable-next-line unicorn/prefer-event-target\nexport class FSObject<T extends object> extends EventEmitter<FSObjectEventMap<T>> {\n\n /** Flag to signal the file is synchronized with the object. */\n public isCommitting = false\n\n /** Flag to signal the instance has been destroyed. */\n public isDestroyed = false\n\n /** Flag to signal the object is synchronized with the file. */\n public isLoading = false\n\n /** The current content of the file. */\n public object: Reactive<T>\n\n /** The current status of the file. */\n public stats: Stats | undefined\n\n /** A watcher that will update the object when the file changes. */\n public watcher: FSWatcher | undefined\n\n /**\n * Load a JSON file and keep it synchronized with it's source file.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options for the watcher.\n * @throws If the file is not a JSON object.\n */\n constructor(public path: PathLike, public options: FSObjectOptions<T> = {}) {\n super()\n\n // --- The callback that will be called when the object changes.\n // --- This callback is wrapped in a debounce function to prevent\n // --- multiple writes in a short period of time.\n const callback = async() => {\n if (this.isBusy) return\n if (this.options.ignoreObjectChanges) return\n await this.commit()\n }\n\n // --- Create the reactive object. Each time a nested property is\n // --- changed, the callback will be called with the new object.\n this.object = reactive(this.options.initialValue ?? {} as T, {\n callbacks: [callback],\n deep: true,\n hooks: ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'],\n ...this.options,\n })\n }\n\n /**\n * Close the file and stop watching the file and object for changes.\n * If the file has been created as a temporary file, it will be deleted.\n *\n * @returns A promise that resolves when the file has been destroyed.\n */\n async [Symbol.asyncDispose]() {\n return this.destroy()\n }\n\n /**\n * Create an awaitable instance of `FSObject` that resolves when the file\n * is synchronized with the object and the object is synchronized with the file.\n *\n * This function is a shorthand for creating a new `FSObject` instance and\n * calling the `access`, `load` and `watch` methods in sequence. This allows\n * fast and easy access to the file and object in a single call.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options to pass to the `FSObject` constructor.\n * @returns An awaitable instance of `FSObject`.\n * @example\n * const fsObject = FSObject.from('file.json')\n * const object = await fsObject\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n * await fsObject.untilLoaded\n * object // => { foo: 'bar' }\n *\n * // Change the object and check the file.\n * object.foo = 'baz'\n * await fsObject.untilCommitted\n * readFileSync('file.json', 'utf8') // => { \"foo\": \"baz\" }\n */\n static from<T extends object>(path: PathLike, options: FSObjectOptions<T> = {}): Awaitable<FSObject<T>, Reactive<T>> {\n const fsObject = new FSObject<T>(path, options)\n const createPromise = () => fsObject.load().then(() => fsObject.watch().object)\n return awaitable(fsObject, createPromise)\n }\n\n /**\n * Commit the current state of the object to the file. This function\n * **will** write the object to the file and emit a `commit` event.\n *\n * @param writeObject The object to write to the file.\n * @returns A promise that resolves when the file has been written.\n */\n public async commit(writeObject = this.object as T): Promise<void> {\n this.isCommitting = true\n\n // --- Stringify the object and write it to disk.\n const { serialize = (object: unknown) => JSON.stringify(object, undefined, 2) } = this.options\n const writeJson = serialize(writeObject)\n const pathString = this.path.toString()\n const pathDirectory = dirname(pathString)\n await mkdir(pathDirectory, { recursive: true })\n await writeFile(this.path, `${writeJson}\\n`, 'utf8')\n overwrite(this.object, writeObject)\n this.stats = await stat(this.path)\n\n this.emit('commit', writeObject)\n this.isCommitting = false\n }\n\n /**\n * Close the file and stop watching the file and object for changes.\n * If the file has been created as a temporary file, it will be deleted.\n */\n public async destroy(): Promise<void> {\n this.isLoading = false\n this.isCommitting = false\n if (this.watcher) this.watcher.close()\n if (this.options.deleteOnDestroy) await rm(this.path, { force: true })\n this.watcher = undefined\n this.isDestroyed = true\n this.emit('destroy')\n }\n\n /**\n * Load the file and update the object.\n *\n * @returns The loaded object.\n */\n public async load(): Promise<void> {\n this.isLoading = true\n this.isDestroyed = false\n\n // --- If the file does not exist, and the `createIfNotExists` option is\n // --- set to `true`, create the file and initialize the object with the\n // --- `initialValue` option.\n const accessError = await access(this.path, constants.F_OK | constants.R_OK).catch((error: Error) => error)\n if (accessError && this.options.createIfNotExists) {\n await this.commit()\n this.isLoading = false\n this.emit('load', this.object)\n return\n }\n\n // --- If the file does not exist, throw an error.\n if (accessError && !this.options.createIfNotExists) throw accessError\n\n // --- Assert the path points to a file.\n const newStats = await stat(this.path)\n const newIsFile = newStats.isFile()\n if (!newIsFile) throw new Error(`Expected ${this.path.toString()} to be a file`)\n\n // --- If the file has not changed, return the current object.\n if (this.object && this.stats && newStats.mtimeMs < this.stats.mtimeMs) return\n this.stats = newStats\n\n // --- Read and parse the file.\n const { parse = JSON.parse } = this.options\n const newJson = await readFile(this.path, 'utf8')\n const newObject = parse(newJson) as T\n\n // --- Assert JSON is an object.\n if (typeof newObject !== 'object' || newObject === null)\n throw new Error(`Expected ${this.path.toString()} to be a JSON object`)\n\n // --- Update the object by overwriting it's properties.\n overwrite(this.object, newObject)\n this.isLoading = false\n this.emit('load', newObject)\n }\n\n /**\n * Start watching the file for changes and update the object if the content\n * of the file changes.\n *\n * @returns The current instance for chaining.\n * @example\n * const object = new FSObject('file.json').watch()\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n *\n * // Wait until the object is updated.\n * await object.untilLoaded\n *\n * // Check the object.\n * expect(object.object).toStrictEqual({ foo: 'bar' })\n */\n public watch(): this {\n if (this.watcher) return this\n\n // --- Try to watch the file for changes. If an error occurs, the file\n // --- is likely not accessible. In this case, just set the `isWatching`\n // --- flag to `true` and retry watching the file when it becomes accessible.\n this.watcher = watch(this.path, { persistent: false, ...this.options }, (event) => {\n if (this.isBusy) return\n if (this.options.ignoreFileChanges) return\n if (event === 'change') void this.load()\n })\n\n // --- Return the instance for chaining.\n return this\n }\n\n /**\n * Flag to signal the instance is busy doing a commit or a load operation.\n *\n * @returns `true` if the instance is busy, `false` otherwise.\n */\n get isBusy() {\n return this.isLoading || this.isCommitting || this.isDestroyed\n }\n\n /**\n * A promise that resolves when the file is synchronized with the object.\n *\n * @returns A promise that resolves when the file is synchronized.\n * @example\n * const object = new FSObject('file.json')\n * object.commit()\n *\n * // Wait until the file is synchronized.\n * await object.untilCommitted\n */\n get untilCommitted(): Promise<void> {\n if (!this.isCommitting) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('commit', () => resolve()))\n }\n\n /**\n * A promise that resolves when the object is destroyed.\n *\n * @returns A promise that resolves when the object is destroyed.\n * @example\n * const object = new FSObject('file.json')\n * object.destroy()\n *\n * // Wait until the object is destroyed.\n * await object.untilDestroyed\n */\n get untilDestroyed(): Promise<void> {\n if (this.isDestroyed) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('destroy', resolve))\n }\n\n /**\n * A promise that resolves when the object is synchronized with the file.\n *\n * @returns A promise that resolves when the file is synchronized.\n * @example\n * const object = new FSObject('file.json')\n * object.load()\n *\n * // Wait until the object is synchronized.\n * await object.untilLoaded\n */\n get untilLoaded(): Promise<void> {\n if (!this.isLoading) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('load', () => resolve()))\n }\n}\n\n/**\n * Create an awaitable instance of `FSObject` that resolves when the file\n * is synchronized with the object and the object is synchronized with the file.\n *\n * This function is a shorthand for creating a new `FSObject` instance and\n * calling the `access`, `load` and `watch` methods in sequence. This allows\n * fast and easy access to the file and object in a single call.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options to pass to the `FSObject` constructor.\n * @returns An awaitable instance of `FSObject`.\n * @example\n * const fsObject = loadObject('file.json')\n * const object = await fsObject\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n * await fsObject.untilLoaded\n * object // => { foo: 'bar' }\n *\n * // Change the object and check the file.\n * object.foo = 'baz'\n * await fsObject.untilCommitted\n * readFileSync('file.json', 'utf8') // => { \"foo\": \"baz\" }\n */\nexport function loadObject<T extends object>(path: PathLike, options: FSObjectOptions<T> = {}): Awaitable<FSObject<T>, Reactive<T>> {\n return FSObject.from(path, options)\n}\n"],"names":["EventEmitter","reactive","awaitable","dirname","mkdir","writeFile","overwrite","stat","rm","access","constants","readFile","watch"],"mappings":";;AAiFO,MAAM,iBAAmCA,YAAAA,aAAkC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2BhF,YAAmB,MAAuB,UAA8B,IAAI;AACpE,UAAA,GADW,KAAA,OAAA,MAAuB,KAAA,UAAA;AAMxC,UAAM,WAAW,YAAW;AACtB,WAAK,UACL,KAAK,QAAQ,uBACjB,MAAM,KAAK,OAAO;AAAA,IACpB;AAIA,SAAK,SAASC,SAAS,SAAA,KAAK,QAAQ,gBAAgB,IAAS;AAAA,MAC3D,WAAW,CAAC,QAAQ;AAAA,MACpB,MAAM;AAAA,MACN,OAAO,CAAC,QAAQ,OAAO,SAAS,WAAW,UAAU,QAAQ,SAAS;AAAA,MACtE,GAAG,KAAK;AAAA,IAAA,CACT;AAAA,EAAA;AAAA;AAAA,EA3CI,eAAe;AAAA;AAAA,EAGf,cAAc;AAAA;AAAA,EAGd,YAAY;AAAA;AAAA,EAGZ;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqCP,OAAO,OA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,UAAU,YAAe,KAAK,KAAK;AAAA,IACxC,CAAA,GAGM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQT,IAAI,SAAS;AACX,WAAO,KAAK,aAAa,KAAK,gBAAgB,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcrD,IAAI,iBAAgC;AAClC,WAAK,KAAK,eACH,IAAI,QAAc,aAAW,KAAK,oBAAoB,UAAU,MAAM,QAAQ,CAAC,CAAC,IADxD,QAAQ,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAejD,IAAI,iBAAgC;AAClC,WAAI,KAAK,cAAoB,QAAQ,QAC9B,IAAA,IAAI,QAAc,CAAA,YAAW,KAAK,oBAAoB,WAAW,OAAO,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAclF,IAAI,cAA6B;AAC/B,WAAK,KAAK,YACH,IAAI,QAAc,aAAW,KAAK,oBAAoB,QAAQ,MAAM,QAAQ,CAAC,CAAC,IADzD,QAAQ,QAAQ;AAAA,EAAA;AAGhD;AA2BO,SAAS,WAA6B,MAAgB,UAA8B,IAAyC;AAC3H,SAAA,SAAS,KAAK,MAAM,OAAO;AACpC;;;"}
|
1
|
+
{"version":3,"file":"loadObject.cjs","sources":["../loadObject.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { Reactive, ReactiveOptions } from '@unshared/reactivity/reactive'\nimport type { FSWatcher, PathLike, Stats, WatchOptions } from 'node:fs'\nimport { overwrite } from '@unshared/collection/overwrite'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { reactive } from '@unshared/reactivity/reactive'\nimport { EventEmitter } from 'node:events'\nimport { constants, watch } from 'node:fs'\nimport { access, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface FSObjectOptions<T extends object> extends ReactiveOptions<T>, WatchOptions {\n\n /**\n * If set to `true` and the file does not exist, the file will be created\n * if it does not exist and the object will be initialized with an empty\n * object.\n *\n * @default false\n */\n createIfNotExists?: boolean\n\n /**\n * If set to `true`, the file will be deleted when the instance is destroyed.\n * Allowing you to create temporary files that will be deleted when the\n * instance is garbage collected.\n */\n deleteOnDestroy?: boolean\n\n /**\n * If set to `true`, changes on the file will not be reflected in the object.\n * You can use this to prevent the object from being updated when you are\n * making changes to the file.\n *\n * @default false\n */\n ignoreFileChanges?: boolean\n\n /**\n * If set to `true`, changes on the object will be reflected in the file.\n * You can set this to `false` if you want to make multiple changes to the\n * object without triggering multiple file updates.\n *\n * @default false\n */\n ignoreObjectChanges?: boolean\n\n /**\n * The initial value of the object. If the file does not exist, the object\n * will be initialized with this value.\n *\n * @default {}\n */\n initialValue?: T\n\n /**\n * The parser function to use when reading the file. If not set, the file\n * will be parsed as JSON using the native `JSON.parse` function.\n *\n * @default JSON.parse\n */\n parse?: (json: string) => T\n\n /**\n * The stringifier function to use when writing the file. If not set, the\n * object will be stringified as JSON using the native `JSON.stringify` function.\n *\n * @default JSON.stringify\n */\n serialize?: (object: T) => string\n}\n\nexport interface FSObjectEventMap<T extends object> {\n commit: [T]\n destroy: []\n load: [T]\n lock: []\n unlock: []\n}\n\n// eslint-disable-next-line unicorn/prefer-event-target\nexport class FSObject<T extends object> extends EventEmitter<FSObjectEventMap<T>> {\n\n /** Flag to signal the file is synchronized with the object. */\n public isCommitting = false\n\n /** Flag to signal the instance has been destroyed. */\n public isDestroyed = false\n\n /** Flag to signal the object is synchronized with the file. */\n public isLoading = false\n\n /** The current content of the file. */\n public object: Reactive<T>\n\n /** The current status of the file. */\n public stats: Stats | undefined\n\n /** A watcher that will update the object when the file changes. */\n public watcher: FSWatcher | undefined\n\n /**\n * Load a JSON file and keep it synchronized with it's source file.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options for the watcher.\n * @throws If the file is not a JSON object.\n */\n constructor(public path: PathLike, public options: FSObjectOptions<T> = {}) {\n super()\n\n // --- The callback that will be called when the object changes.\n // --- This callback is wrapped in a debounce function to prevent\n // --- multiple writes in a short period of time.\n const callback = async() => {\n if (this.isBusy) return\n if (this.options.ignoreObjectChanges) return\n await this.commit()\n }\n\n // --- Create the reactive object. Each time a nested property is\n // --- changed, the callback will be called with the new object.\n this.object = reactive(this.options.initialValue ?? {} as T, {\n callbacks: [callback],\n deep: true,\n hooks: ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'],\n ...this.options,\n })\n }\n\n /**\n * Close the file and stop watching the file and object for changes.\n * If the file has been created as a temporary file, it will be deleted.\n *\n * @returns A promise that resolves when the file has been destroyed.\n */\n async [Symbol.asyncDispose]() {\n return this.destroy()\n }\n\n /**\n * Create an awaitable instance of `FSObject` that resolves when the file\n * is synchronized with the object and the object is synchronized with the file.\n *\n * This function is a shorthand for creating a new `FSObject` instance and\n * calling the `access`, `load` and `watch` methods in sequence. This allows\n * fast and easy access to the file and object in a single call.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options to pass to the `FSObject` constructor.\n * @returns An awaitable instance of `FSObject`.\n * @example\n * const fsObject = FSObject.from('file.json')\n * const object = await fsObject\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n * await fsObject.untilLoaded\n * object // => { foo: 'bar' }\n *\n * // Change the object and check the file.\n * object.foo = 'baz'\n * await fsObject.untilCommitted\n * readFileSync('file.json', 'utf8') // => { \"foo\": \"baz\" }\n */\n static from<T extends object>(path: PathLike, options: FSObjectOptions<T> = {}): Awaitable<FSObject<T>, Reactive<T>> {\n const fsObject = new FSObject<T>(path, options)\n const createPromise = () => fsObject.load().then(() => fsObject.watch().object)\n return awaitable(fsObject, createPromise)\n }\n\n /**\n * Commit the current state of the object to the file. This function\n * **will** write the object to the file and emit a `commit` event.\n *\n * @param writeObject The object to write to the file.\n * @returns A promise that resolves when the file has been written.\n */\n public async commit(writeObject = this.object as T): Promise<void> {\n this.isCommitting = true\n\n // --- Stringify the object and write it to disk.\n const { serialize = (object: unknown) => JSON.stringify(object, undefined, 2) } = this.options\n const writeJson = serialize(writeObject)\n const pathString = this.path.toString()\n const pathDirectory = dirname(pathString)\n await mkdir(pathDirectory, { recursive: true })\n await writeFile(this.path, `${writeJson}\\n`, 'utf8')\n overwrite(this.object, writeObject)\n this.stats = await stat(this.path)\n\n this.emit('commit', writeObject)\n this.isCommitting = false\n }\n\n /**\n * Close the file and stop watching the file and object for changes.\n * If the file has been created as a temporary file, it will be deleted.\n */\n public async destroy(): Promise<void> {\n this.isLoading = false\n this.isCommitting = false\n if (this.watcher) this.watcher.close()\n if (this.options.deleteOnDestroy) await rm(this.path, { force: true })\n this.watcher = undefined\n this.isDestroyed = true\n this.emit('destroy')\n }\n\n /**\n * Load the file and update the object.\n *\n * @returns The loaded object.\n */\n public async load(): Promise<void> {\n this.isLoading = true\n this.isDestroyed = false\n\n // --- If the file does not exist, and the `createIfNotExists` option is\n // --- set to `true`, create the file and initialize the object with the\n // --- `initialValue` option.\n const accessError = await access(this.path, constants.F_OK | constants.R_OK).catch((error: Error) => error)\n if (accessError && this.options.createIfNotExists) {\n await this.commit()\n this.isLoading = false\n this.emit('load', this.object)\n return\n }\n\n // --- If the file does not exist, throw an error.\n if (accessError && !this.options.createIfNotExists) throw accessError\n\n // --- Assert the path points to a file.\n const newStats = await stat(this.path)\n const newIsFile = newStats.isFile()\n if (!newIsFile) throw new Error(`Expected ${this.path.toString()} to be a file`)\n\n // --- If the file has not changed, return the current object.\n if (this.object && this.stats && newStats.mtimeMs < this.stats.mtimeMs) return\n this.stats = newStats\n\n // --- Read and parse the file.\n const { parse = JSON.parse } = this.options\n const newJson = await readFile(this.path, 'utf8')\n const newObject = parse(newJson) as T\n\n // --- Assert JSON is an object.\n if (typeof newObject !== 'object' || newObject === null)\n throw new Error(`Expected ${this.path.toString()} to be a JSON object`)\n\n // --- Update the object by overwriting it's properties.\n overwrite(this.object, newObject)\n this.isLoading = false\n this.emit('load', newObject)\n }\n\n /**\n * Start watching the file for changes and update the object if the content\n * of the file changes.\n *\n * @returns The current instance for chaining.\n * @example\n * const object = new FSObject('file.json').watch()\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n *\n * // Wait until the object is updated.\n * await object.untilLoaded\n *\n * // Check the object.\n * expect(object.object).toStrictEqual({ foo: 'bar' })\n */\n public watch(): this {\n if (this.watcher) return this\n\n // --- Try to watch the file for changes. If an error occurs, the file\n // --- is likely not accessible. In this case, just set the `isWatching`\n // --- flag to `true` and retry watching the file when it becomes accessible.\n this.watcher = watch(this.path, { persistent: false, ...this.options }, (event) => {\n if (this.isBusy) return\n if (this.options.ignoreFileChanges) return\n if (event === 'change') void this.load()\n })\n\n // --- Return the instance for chaining.\n return this\n }\n\n /**\n * Flag to signal the instance is busy doing a commit or a load operation.\n *\n * @returns `true` if the instance is busy, `false` otherwise.\n */\n get isBusy() {\n return this.isLoading || this.isCommitting || this.isDestroyed\n }\n\n /**\n * A promise that resolves when the file is synchronized with the object.\n *\n * @returns A promise that resolves when the file is synchronized.\n * @example\n * const object = new FSObject('file.json')\n * object.commit()\n *\n * // Wait until the file is synchronized.\n * await object.untilCommitted\n */\n get untilCommitted(): Promise<void> {\n if (!this.isCommitting) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('commit', () => resolve()))\n }\n\n /**\n * A promise that resolves when the object is destroyed.\n *\n * @returns A promise that resolves when the object is destroyed.\n * @example\n * const object = new FSObject('file.json')\n * object.destroy()\n *\n * // Wait until the object is destroyed.\n * await object.untilDestroyed\n */\n get untilDestroyed(): Promise<void> {\n if (this.isDestroyed) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('destroy', resolve))\n }\n\n /**\n * A promise that resolves when the object is synchronized with the file.\n *\n * @returns A promise that resolves when the file is synchronized.\n * @example\n * const object = new FSObject('file.json')\n * object.load()\n *\n * // Wait until the object is synchronized.\n * await object.untilLoaded\n */\n get untilLoaded(): Promise<void> {\n if (!this.isLoading) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('load', () => resolve()))\n }\n}\n\n/**\n * Create an awaitable instance of `FSObject` that resolves when the file\n * is synchronized with the object and the object is synchronized with the file.\n *\n * This function is a shorthand for creating a new `FSObject` instance and\n * calling the `access`, `load` and `watch` methods in sequence. This allows\n * fast and easy access to the file and object in a single call.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options to pass to the `FSObject` constructor.\n * @returns An awaitable instance of `FSObject`.\n * @example\n * const fsObject = loadObject('file.json')\n * const object = await fsObject\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n * await fsObject.untilLoaded\n * object // => { foo: 'bar' }\n *\n * // Change the object and check the file.\n * object.foo = 'baz'\n * await fsObject.untilCommitted\n * readFileSync('file.json', 'utf8') // => { \"foo\": \"baz\" }\n */\nexport function loadObject<T extends object>(path: PathLike, options: FSObjectOptions<T> = {}): Awaitable<FSObject<T>, Reactive<T>> {\n return FSObject.from(path, options)\n}\n"],"names":["EventEmitter","reactive","awaitable","dirname","mkdir","writeFile","overwrite","stat","rm","access","constants","readFile","watch"],"mappings":";;AAiFO,MAAM,iBAAmCA,YAAAA,aAAkC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2BhF,YAAmB,MAAuB,UAA8B,IAAI;AAC1E,UAAA,GADiB,KAAA,OAAA,MAAuB,KAAA,UAAA;AAMxC,UAAM,WAAW,YAAW;AACtB,WAAK,UACL,KAAK,QAAQ,uBACjB,MAAM,KAAK,OAAA;AAAA,IACb;AAIA,SAAK,SAASC,SAAAA,SAAS,KAAK,QAAQ,gBAAgB,IAAS;AAAA,MAC3D,WAAW,CAAC,QAAQ;AAAA,MACpB,MAAM;AAAA,MACN,OAAO,CAAC,QAAQ,OAAO,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["../loadObject.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { Reactive, ReactiveOptions } from '@unshared/reactivity/reactive'\nimport type { FSWatcher, PathLike, Stats, WatchOptions } from 'node:fs'\nimport { overwrite } from '@unshared/collection/overwrite'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { reactive } from '@unshared/reactivity/reactive'\nimport { EventEmitter } from 'node:events'\nimport { constants, watch } from 'node:fs'\nimport { access, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface FSObjectOptions<T extends object> extends ReactiveOptions<T>, WatchOptions {\n\n /**\n * If set to `true` and the file does not exist, the file will be created\n * if it does not exist and the object will be initialized with an empty\n * object.\n *\n * @default false\n */\n createIfNotExists?: boolean\n\n /**\n * If set to `true`, the file will be deleted when the instance is destroyed.\n * Allowing you to create temporary files that will be deleted when the\n * instance is garbage collected.\n */\n deleteOnDestroy?: boolean\n\n /**\n * If set to `true`, changes on the file will not be reflected in the object.\n * You can use this to prevent the object from being updated when you are\n * making changes to the file.\n *\n * @default false\n */\n ignoreFileChanges?: boolean\n\n /**\n * If set to `true`, changes on the object will be reflected in the file.\n * You can set this to `false` if you want to make multiple changes to the\n * object without triggering multiple file updates.\n *\n * @default false\n */\n ignoreObjectChanges?: boolean\n\n /**\n * The initial value of the object. If the file does not exist, the object\n * will be initialized with this value.\n *\n * @default {}\n */\n initialValue?: T\n\n /**\n * The parser function to use when reading the file. If not set, the file\n * will be parsed as JSON using the native `JSON.parse` function.\n *\n * @default JSON.parse\n */\n parse?: (json: string) => T\n\n /**\n * The stringifier function to use when writing the file. If not set, the\n * object will be stringified as JSON using the native `JSON.stringify` function.\n *\n * @default JSON.stringify\n */\n serialize?: (object: T) => string\n}\n\nexport interface FSObjectEventMap<T extends object> {\n commit: [T]\n destroy: []\n load: [T]\n lock: []\n unlock: []\n}\n\n// eslint-disable-next-line unicorn/prefer-event-target\nexport class FSObject<T extends object> extends EventEmitter<FSObjectEventMap<T>> {\n\n /** Flag to signal the file is synchronized with the object. */\n public isCommitting = false\n\n /** Flag to signal the instance has been destroyed. */\n public isDestroyed = false\n\n /** Flag to signal the object is synchronized with the file. */\n public isLoading = false\n\n /** The current content of the file. */\n public object: Reactive<T>\n\n /** The current status of the file. */\n public stats: Stats | undefined\n\n /** A watcher that will update the object when the file changes. */\n public watcher: FSWatcher | undefined\n\n /**\n * Load a JSON file and keep it synchronized with it's source file.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options for the watcher.\n * @throws If the file is not a JSON object.\n */\n constructor(public path: PathLike, public options: FSObjectOptions<T> = {}) {\n super()\n\n // --- The callback that will be called when the object changes.\n // --- This callback is wrapped in a debounce function to prevent\n // --- multiple writes in a short period of time.\n const callback = async() => {\n if (this.isBusy) return\n if (this.options.ignoreObjectChanges) return\n await this.commit()\n }\n\n // --- Create the reactive object. Each time a nested property is\n // --- changed, the callback will be called with the new object.\n this.object = reactive(this.options.initialValue ?? {} as T, {\n callbacks: [callback],\n deep: true,\n hooks: ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'],\n ...this.options,\n })\n }\n\n /**\n * Close the file and stop watching the file and object for changes.\n * If the file has been created as a temporary file, it will be deleted.\n *\n * @returns A promise that resolves when the file has been destroyed.\n */\n async [Symbol.asyncDispose]() {\n return this.destroy()\n }\n\n /**\n * Create an awaitable instance of `FSObject` that resolves when the file\n * is synchronized with the object and the object is synchronized with the file.\n *\n * This function is a shorthand for creating a new `FSObject` instance and\n * calling the `access`, `load` and `watch` methods in sequence. This allows\n * fast and easy access to the file and object in a single call.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options to pass to the `FSObject` constructor.\n * @returns An awaitable instance of `FSObject`.\n * @example\n * const fsObject = FSObject.from('file.json')\n * const object = await fsObject\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n * await fsObject.untilLoaded\n * object // => { foo: 'bar' }\n *\n * // Change the object and check the file.\n * object.foo = 'baz'\n * await fsObject.untilCommitted\n * readFileSync('file.json', 'utf8') // => { \"foo\": \"baz\" }\n */\n static from<T extends object>(path: PathLike, options: FSObjectOptions<T> = {}): Awaitable<FSObject<T>, Reactive<T>> {\n const fsObject = new FSObject<T>(path, options)\n const createPromise = () => fsObject.load().then(() => fsObject.watch().object)\n return awaitable(fsObject, createPromise)\n }\n\n /**\n * Commit the current state of the object to the file. This function\n * **will** write the object to the file and emit a `commit` event.\n *\n * @param writeObject The object to write to the file.\n * @returns A promise that resolves when the file has been written.\n */\n public async commit(writeObject = this.object as T): Promise<void> {\n this.isCommitting = true\n\n // --- Stringify the object and write it to disk.\n const { serialize = (object: unknown) => JSON.stringify(object, undefined, 2) } = this.options\n const writeJson = serialize(writeObject)\n const pathString = this.path.toString()\n const pathDirectory = dirname(pathString)\n await mkdir(pathDirectory, { recursive: true })\n await writeFile(this.path, `${writeJson}\\n`, 'utf8')\n overwrite(this.object, writeObject)\n this.stats = await stat(this.path)\n\n this.emit('commit', writeObject)\n this.isCommitting = false\n }\n\n /**\n * Close the file and stop watching the file and object for changes.\n * If the file has been created as a temporary file, it will be deleted.\n */\n public async destroy(): Promise<void> {\n this.isLoading = false\n this.isCommitting = false\n if (this.watcher) this.watcher.close()\n if (this.options.deleteOnDestroy) await rm(this.path, { force: true })\n this.watcher = undefined\n this.isDestroyed = true\n this.emit('destroy')\n }\n\n /**\n * Load the file and update the object.\n *\n * @returns The loaded object.\n */\n public async load(): Promise<void> {\n this.isLoading = true\n this.isDestroyed = false\n\n // --- If the file does not exist, and the `createIfNotExists` option is\n // --- set to `true`, create the file and initialize the object with the\n // --- `initialValue` option.\n const accessError = await access(this.path, constants.F_OK | constants.R_OK).catch((error: Error) => error)\n if (accessError && this.options.createIfNotExists) {\n await this.commit()\n this.isLoading = false\n this.emit('load', this.object)\n return\n }\n\n // --- If the file does not exist, throw an error.\n if (accessError && !this.options.createIfNotExists) throw accessError\n\n // --- Assert the path points to a file.\n const newStats = await stat(this.path)\n const newIsFile = newStats.isFile()\n if (!newIsFile) throw new Error(`Expected ${this.path.toString()} to be a file`)\n\n // --- If the file has not changed, return the current object.\n if (this.object && this.stats && newStats.mtimeMs < this.stats.mtimeMs) return\n this.stats = newStats\n\n // --- Read and parse the file.\n const { parse = JSON.parse } = this.options\n const newJson = await readFile(this.path, 'utf8')\n const newObject = parse(newJson) as T\n\n // --- Assert JSON is an object.\n if (typeof newObject !== 'object' || newObject === null)\n throw new Error(`Expected ${this.path.toString()} to be a JSON object`)\n\n // --- Update the object by overwriting it's properties.\n overwrite(this.object, newObject)\n this.isLoading = false\n this.emit('load', newObject)\n }\n\n /**\n * Start watching the file for changes and update the object if the content\n * of the file changes.\n *\n * @returns The current instance for chaining.\n * @example\n * const object = new FSObject('file.json').watch()\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n *\n * // Wait until the object is updated.\n * await object.untilLoaded\n *\n * // Check the object.\n * expect(object.object).toStrictEqual({ foo: 'bar' })\n */\n public watch(): this {\n if (this.watcher) return this\n\n // --- Try to watch the file for changes. If an error occurs, the file\n // --- is likely not accessible. In this case, just set the `isWatching`\n // --- flag to `true` and retry watching the file when it becomes accessible.\n this.watcher = watch(this.path, { persistent: false, ...this.options }, (event) => {\n if (this.isBusy) return\n if (this.options.ignoreFileChanges) return\n if (event === 'change') void this.load()\n })\n\n // --- Return the instance for chaining.\n return this\n }\n\n /**\n * Flag to signal the instance is busy doing a commit or a load operation.\n *\n * @returns `true` if the instance is busy, `false` otherwise.\n */\n get isBusy() {\n return this.isLoading || this.isCommitting || this.isDestroyed\n }\n\n /**\n * A promise that resolves when the file is synchronized with the object.\n *\n * @returns A promise that resolves when the file is synchronized.\n * @example\n * const object = new FSObject('file.json')\n * object.commit()\n *\n * // Wait until the file is synchronized.\n * await object.untilCommitted\n */\n get untilCommitted(): Promise<void> {\n if (!this.isCommitting) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('commit', () => resolve()))\n }\n\n /**\n * A promise that resolves when the object is destroyed.\n *\n * @returns A promise that resolves when the object is destroyed.\n * @example\n * const object = new FSObject('file.json')\n * object.destroy()\n *\n * // Wait until the object is destroyed.\n * await object.untilDestroyed\n */\n get untilDestroyed(): Promise<void> {\n if (this.isDestroyed) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('destroy', resolve))\n }\n\n /**\n * A promise that resolves when the object is synchronized with the file.\n *\n * @returns A promise that resolves when the file is synchronized.\n * @example\n * const object = new FSObject('file.json')\n * object.load()\n *\n * // Wait until the object is synchronized.\n * await object.untilLoaded\n */\n get untilLoaded(): Promise<void> {\n if (!this.isLoading) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('load', () => resolve()))\n }\n}\n\n/**\n * Create an awaitable instance of `FSObject` that resolves when the file\n * is synchronized with the object and the object is synchronized with the file.\n *\n * This function is a shorthand for creating a new `FSObject` instance and\n * calling the `access`, `load` and `watch` methods in sequence. This allows\n * fast and easy access to the file and object in a single call.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options to pass to the `FSObject` constructor.\n * @returns An awaitable instance of `FSObject`.\n * @example\n * const fsObject = loadObject('file.json')\n * const object = await fsObject\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n * await fsObject.untilLoaded\n * object // => { foo: 'bar' }\n *\n * // Change the object and check the file.\n * object.foo = 'baz'\n * await fsObject.untilCommitted\n * readFileSync('file.json', 'utf8') // => { \"foo\": \"baz\" }\n */\nexport function loadObject<T extends object>(path: PathLike, options: FSObjectOptions<T> = {}): Awaitable<FSObject<T>, Reactive<T>> {\n return FSObject.from(path, options)\n}\n"],"names":[],"mappings":";;;;;;;AAiFO,MAAM,iBAAmC,aAAkC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2BhF,YAAmB,MAAuB,UAA8B,IAAI;AACpE,UAAA,GADW,KAAA,OAAA,MAAuB,KAAA,UAAA;AAMxC,UAAM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MAAgB,UAA8B,IAAyC;AAC3H,SAAA,SAAS,KAAK,MAAM,OAAO;AACpC;"}
|
1
|
+
{"version":3,"file":"loadObject.js","sources":["../loadObject.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { Reactive, ReactiveOptions } from '@unshared/reactivity/reactive'\nimport type { FSWatcher, PathLike, Stats, WatchOptions } from 'node:fs'\nimport { overwrite } from '@unshared/collection/overwrite'\nimport { awaitable } from '@unshared/functions/awaitable'\nimport { reactive } from '@unshared/reactivity/reactive'\nimport { EventEmitter } from 'node:events'\nimport { constants, watch } from 'node:fs'\nimport { access, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface FSObjectOptions<T extends object> extends ReactiveOptions<T>, WatchOptions {\n\n /**\n * If set to `true` and the file does not exist, the file will be created\n * if it does not exist and the object will be initialized with an empty\n * object.\n *\n * @default false\n */\n createIfNotExists?: boolean\n\n /**\n * If set to `true`, the file will be deleted when the instance is destroyed.\n * Allowing you to create temporary files that will be deleted when the\n * instance is garbage collected.\n */\n deleteOnDestroy?: boolean\n\n /**\n * If set to `true`, changes on the file will not be reflected in the object.\n * You can use this to prevent the object from being updated when you are\n * making changes to the file.\n *\n * @default false\n */\n ignoreFileChanges?: boolean\n\n /**\n * If set to `true`, changes on the object will be reflected in the file.\n * You can set this to `false` if you want to make multiple changes to the\n * object without triggering multiple file updates.\n *\n * @default false\n */\n ignoreObjectChanges?: boolean\n\n /**\n * The initial value of the object. If the file does not exist, the object\n * will be initialized with this value.\n *\n * @default {}\n */\n initialValue?: T\n\n /**\n * The parser function to use when reading the file. If not set, the file\n * will be parsed as JSON using the native `JSON.parse` function.\n *\n * @default JSON.parse\n */\n parse?: (json: string) => T\n\n /**\n * The stringifier function to use when writing the file. If not set, the\n * object will be stringified as JSON using the native `JSON.stringify` function.\n *\n * @default JSON.stringify\n */\n serialize?: (object: T) => string\n}\n\nexport interface FSObjectEventMap<T extends object> {\n commit: [T]\n destroy: []\n load: [T]\n lock: []\n unlock: []\n}\n\n// eslint-disable-next-line unicorn/prefer-event-target\nexport class FSObject<T extends object> extends EventEmitter<FSObjectEventMap<T>> {\n\n /** Flag to signal the file is synchronized with the object. */\n public isCommitting = false\n\n /** Flag to signal the instance has been destroyed. */\n public isDestroyed = false\n\n /** Flag to signal the object is synchronized with the file. */\n public isLoading = false\n\n /** The current content of the file. */\n public object: Reactive<T>\n\n /** The current status of the file. */\n public stats: Stats | undefined\n\n /** A watcher that will update the object when the file changes. */\n public watcher: FSWatcher | undefined\n\n /**\n * Load a JSON file and keep it synchronized with it's source file.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options for the watcher.\n * @throws If the file is not a JSON object.\n */\n constructor(public path: PathLike, public options: FSObjectOptions<T> = {}) {\n super()\n\n // --- The callback that will be called when the object changes.\n // --- This callback is wrapped in a debounce function to prevent\n // --- multiple writes in a short period of time.\n const callback = async() => {\n if (this.isBusy) return\n if (this.options.ignoreObjectChanges) return\n await this.commit()\n }\n\n // --- Create the reactive object. Each time a nested property is\n // --- changed, the callback will be called with the new object.\n this.object = reactive(this.options.initialValue ?? {} as T, {\n callbacks: [callback],\n deep: true,\n hooks: ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'],\n ...this.options,\n })\n }\n\n /**\n * Close the file and stop watching the file and object for changes.\n * If the file has been created as a temporary file, it will be deleted.\n *\n * @returns A promise that resolves when the file has been destroyed.\n */\n async [Symbol.asyncDispose]() {\n return this.destroy()\n }\n\n /**\n * Create an awaitable instance of `FSObject` that resolves when the file\n * is synchronized with the object and the object is synchronized with the file.\n *\n * This function is a shorthand for creating a new `FSObject` instance and\n * calling the `access`, `load` and `watch` methods in sequence. This allows\n * fast and easy access to the file and object in a single call.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options to pass to the `FSObject` constructor.\n * @returns An awaitable instance of `FSObject`.\n * @example\n * const fsObject = FSObject.from('file.json')\n * const object = await fsObject\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n * await fsObject.untilLoaded\n * object // => { foo: 'bar' }\n *\n * // Change the object and check the file.\n * object.foo = 'baz'\n * await fsObject.untilCommitted\n * readFileSync('file.json', 'utf8') // => { \"foo\": \"baz\" }\n */\n static from<T extends object>(path: PathLike, options: FSObjectOptions<T> = {}): Awaitable<FSObject<T>, Reactive<T>> {\n const fsObject = new FSObject<T>(path, options)\n const createPromise = () => fsObject.load().then(() => fsObject.watch().object)\n return awaitable(fsObject, createPromise)\n }\n\n /**\n * Commit the current state of the object to the file. This function\n * **will** write the object to the file and emit a `commit` event.\n *\n * @param writeObject The object to write to the file.\n * @returns A promise that resolves when the file has been written.\n */\n public async commit(writeObject = this.object as T): Promise<void> {\n this.isCommitting = true\n\n // --- Stringify the object and write it to disk.\n const { serialize = (object: unknown) => JSON.stringify(object, undefined, 2) } = this.options\n const writeJson = serialize(writeObject)\n const pathString = this.path.toString()\n const pathDirectory = dirname(pathString)\n await mkdir(pathDirectory, { recursive: true })\n await writeFile(this.path, `${writeJson}\\n`, 'utf8')\n overwrite(this.object, writeObject)\n this.stats = await stat(this.path)\n\n this.emit('commit', writeObject)\n this.isCommitting = false\n }\n\n /**\n * Close the file and stop watching the file and object for changes.\n * If the file has been created as a temporary file, it will be deleted.\n */\n public async destroy(): Promise<void> {\n this.isLoading = false\n this.isCommitting = false\n if (this.watcher) this.watcher.close()\n if (this.options.deleteOnDestroy) await rm(this.path, { force: true })\n this.watcher = undefined\n this.isDestroyed = true\n this.emit('destroy')\n }\n\n /**\n * Load the file and update the object.\n *\n * @returns The loaded object.\n */\n public async load(): Promise<void> {\n this.isLoading = true\n this.isDestroyed = false\n\n // --- If the file does not exist, and the `createIfNotExists` option is\n // --- set to `true`, create the file and initialize the object with the\n // --- `initialValue` option.\n const accessError = await access(this.path, constants.F_OK | constants.R_OK).catch((error: Error) => error)\n if (accessError && this.options.createIfNotExists) {\n await this.commit()\n this.isLoading = false\n this.emit('load', this.object)\n return\n }\n\n // --- If the file does not exist, throw an error.\n if (accessError && !this.options.createIfNotExists) throw accessError\n\n // --- Assert the path points to a file.\n const newStats = await stat(this.path)\n const newIsFile = newStats.isFile()\n if (!newIsFile) throw new Error(`Expected ${this.path.toString()} to be a file`)\n\n // --- If the file has not changed, return the current object.\n if (this.object && this.stats && newStats.mtimeMs < this.stats.mtimeMs) return\n this.stats = newStats\n\n // --- Read and parse the file.\n const { parse = JSON.parse } = this.options\n const newJson = await readFile(this.path, 'utf8')\n const newObject = parse(newJson) as T\n\n // --- Assert JSON is an object.\n if (typeof newObject !== 'object' || newObject === null)\n throw new Error(`Expected ${this.path.toString()} to be a JSON object`)\n\n // --- Update the object by overwriting it's properties.\n overwrite(this.object, newObject)\n this.isLoading = false\n this.emit('load', newObject)\n }\n\n /**\n * Start watching the file for changes and update the object if the content\n * of the file changes.\n *\n * @returns The current instance for chaining.\n * @example\n * const object = new FSObject('file.json').watch()\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n *\n * // Wait until the object is updated.\n * await object.untilLoaded\n *\n * // Check the object.\n * expect(object.object).toStrictEqual({ foo: 'bar' })\n */\n public watch(): this {\n if (this.watcher) return this\n\n // --- Try to watch the file for changes. If an error occurs, the file\n // --- is likely not accessible. In this case, just set the `isWatching`\n // --- flag to `true` and retry watching the file when it becomes accessible.\n this.watcher = watch(this.path, { persistent: false, ...this.options }, (event) => {\n if (this.isBusy) return\n if (this.options.ignoreFileChanges) return\n if (event === 'change') void this.load()\n })\n\n // --- Return the instance for chaining.\n return this\n }\n\n /**\n * Flag to signal the instance is busy doing a commit or a load operation.\n *\n * @returns `true` if the instance is busy, `false` otherwise.\n */\n get isBusy() {\n return this.isLoading || this.isCommitting || this.isDestroyed\n }\n\n /**\n * A promise that resolves when the file is synchronized with the object.\n *\n * @returns A promise that resolves when the file is synchronized.\n * @example\n * const object = new FSObject('file.json')\n * object.commit()\n *\n * // Wait until the file is synchronized.\n * await object.untilCommitted\n */\n get untilCommitted(): Promise<void> {\n if (!this.isCommitting) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('commit', () => resolve()))\n }\n\n /**\n * A promise that resolves when the object is destroyed.\n *\n * @returns A promise that resolves when the object is destroyed.\n * @example\n * const object = new FSObject('file.json')\n * object.destroy()\n *\n * // Wait until the object is destroyed.\n * await object.untilDestroyed\n */\n get untilDestroyed(): Promise<void> {\n if (this.isDestroyed) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('destroy', resolve))\n }\n\n /**\n * A promise that resolves when the object is synchronized with the file.\n *\n * @returns A promise that resolves when the file is synchronized.\n * @example\n * const object = new FSObject('file.json')\n * object.load()\n *\n * // Wait until the object is synchronized.\n * await object.untilLoaded\n */\n get untilLoaded(): Promise<void> {\n if (!this.isLoading) return Promise.resolve()\n return new Promise<void>(resolve => this.prependOnceListener('load', () => resolve()))\n }\n}\n\n/**\n * Create an awaitable instance of `FSObject` that resolves when the file\n * is synchronized with the object and the object is synchronized with the file.\n *\n * This function is a shorthand for creating a new `FSObject` instance and\n * calling the `access`, `load` and `watch` methods in sequence. This allows\n * fast and easy access to the file and object in a single call.\n *\n * @param path The path or file descriptor of the file to load.\n * @param options Options to pass to the `FSObject` constructor.\n * @returns An awaitable instance of `FSObject`.\n * @example\n * const fsObject = loadObject('file.json')\n * const object = await fsObject\n *\n * // Change the file and check the object.\n * writeFileSync('file.json', '{\"foo\":\"bar\"}')\n * await fsObject.untilLoaded\n * object // => { foo: 'bar' }\n *\n * // Change the object and check the file.\n * object.foo = 'baz'\n * await fsObject.untilCommitted\n * readFileSync('file.json', 'utf8') // => { \"foo\": \"baz\" }\n */\nexport function loadObject<T extends object>(path: PathLike, options: FSObjectOptions<T> = {}): Awaitable<FSObject<T>, Reactive<T>> {\n return FSObject.from(path, options)\n}\n"],"names":[],"mappings":";;;;;;;AAiFO,MAAM,iBAAmC,aAAkC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,MAAM,QAAA,CAAS,CAAC,IADzD,QAAQ,QAAA;AAAA,EAEtC;AACF;AA2BO,SAAS,WAA6B,MAAgB,UAA8B,IAAyC;AAClI,SAAO,SAAS,KAAK,MAAM,OAAO;AACpC;"}
|
package/dist/touch.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"touch.cjs","sources":["../touch.ts"],"sourcesContent":["import type { TimeLike } from 'node:fs'\nimport { mkdir, stat, utimes, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface TouchOptions {\n\n /**\n * The time to set as the file's last access time.\n *\n * @default Date.now()\n */\n accessTime?: TimeLike\n\n /**\n * The time to set as the file's last modified time.\n *\n * @default Date.now()\n */\n modifiedTime?: TimeLike\n}\n\n/**\n * Touch a file at the given path. You can optionally specify the access and modified times\n * to set on the file. If the file does not exists, an empty file and any missing parent\n * folders will be created.\n *\n * @param path The path to the file to touch.\n * @param options The access and modified times to set on the file.\n * @returns A promise that resolves when the file has been touched.\n * @example\n * // Touch a file with a specific access and modified time.\n * await touch('/foo/bar.txt', { accessTime: 1000, modifiedTime: 2000 })\n *\n * // Check the file's access and modified times.\n * const stats = await stat('/foo/bar.txt')\n * expect(stats.atimeMs).toStrictEqual(1000)\n * expect(stats.mtimeMs).toStrictEqual(2000)\n */\nexport async function touch(path: string, options: TouchOptions = {}): Promise<void> {\n const {\n accessTime = Date.now(),\n modifiedTime = Date.now(),\n } = options\n\n // --- If the path does not exist, then create it.\n const fileExists = await stat(path)\n .then(() => true)\n .catch(() => false)\n\n if (!fileExists) {\n const fileDirectory = dirname(path)\n await mkdir(fileDirectory, { recursive: true })\n await writeFile(path, [])\n }\n\n // --- Update the file's access and modified times.\n await utimes(path, accessTime, modifiedTime)\n}\n"],"names":["stat","dirname","mkdir","writeFile","utimes"],"mappings":";;AAsCA,eAAsB,MAAM,MAAc,UAAwB,IAAmB;
|
1
|
+
{"version":3,"file":"touch.cjs","sources":["../touch.ts"],"sourcesContent":["import type { TimeLike } from 'node:fs'\nimport { mkdir, stat, utimes, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface TouchOptions {\n\n /**\n * The time to set as the file's last access time.\n *\n * @default Date.now()\n */\n accessTime?: TimeLike\n\n /**\n * The time to set as the file's last modified time.\n *\n * @default Date.now()\n */\n modifiedTime?: TimeLike\n}\n\n/**\n * Touch a file at the given path. You can optionally specify the access and modified times\n * to set on the file. If the file does not exists, an empty file and any missing parent\n * folders will be created.\n *\n * @param path The path to the file to touch.\n * @param options The access and modified times to set on the file.\n * @returns A promise that resolves when the file has been touched.\n * @example\n * // Touch a file with a specific access and modified time.\n * await touch('/foo/bar.txt', { accessTime: 1000, modifiedTime: 2000 })\n *\n * // Check the file's access and modified times.\n * const stats = await stat('/foo/bar.txt')\n * expect(stats.atimeMs).toStrictEqual(1000)\n * expect(stats.mtimeMs).toStrictEqual(2000)\n */\nexport async function touch(path: string, options: TouchOptions = {}): Promise<void> {\n const {\n accessTime = Date.now(),\n modifiedTime = Date.now(),\n } = options\n\n // --- If the path does not exist, then create it.\n const fileExists = await stat(path)\n .then(() => true)\n .catch(() => false)\n\n if (!fileExists) {\n const fileDirectory = dirname(path)\n await mkdir(fileDirectory, { recursive: true })\n await writeFile(path, [])\n }\n\n // --- Update the file's access and modified times.\n await utimes(path, accessTime, modifiedTime)\n}\n"],"names":["stat","dirname","mkdir","writeFile","utimes"],"mappings":";;AAsCA,eAAsB,MAAM,MAAc,UAAwB,IAAmB;AACnF,QAAM;AAAA,IACJ,aAAa,KAAK,IAAA;AAAA,IAClB,eAAe,KAAK,IAAA;AAAA,EAAI,IACtB;AAOJ,MAAI,CAJe,MAAMA,SAAAA,KAAK,IAAI,EAC/B,KAAK,MAAM,EAAI,EACf,MAAM,MAAM,EAAK,GAEH;AACf,UAAM,gBAAgBC,UAAAA,QAAQ,IAAI;AAClC,UAAMC,SAAAA,MAAM,eAAe,EAAE,WAAW,GAAA,CAAM,GAC9C,MAAMC,SAAAA,UAAU,MAAM,EAAE;AAAA,EAC1B;AAGA,QAAMC,gBAAO,MAAM,YAAY,YAAY;AAC7C;;"}
|
package/dist/touch.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"touch.js","sources":["../touch.ts"],"sourcesContent":["import type { TimeLike } from 'node:fs'\nimport { mkdir, stat, utimes, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface TouchOptions {\n\n /**\n * The time to set as the file's last access time.\n *\n * @default Date.now()\n */\n accessTime?: TimeLike\n\n /**\n * The time to set as the file's last modified time.\n *\n * @default Date.now()\n */\n modifiedTime?: TimeLike\n}\n\n/**\n * Touch a file at the given path. You can optionally specify the access and modified times\n * to set on the file. If the file does not exists, an empty file and any missing parent\n * folders will be created.\n *\n * @param path The path to the file to touch.\n * @param options The access and modified times to set on the file.\n * @returns A promise that resolves when the file has been touched.\n * @example\n * // Touch a file with a specific access and modified time.\n * await touch('/foo/bar.txt', { accessTime: 1000, modifiedTime: 2000 })\n *\n * // Check the file's access and modified times.\n * const stats = await stat('/foo/bar.txt')\n * expect(stats.atimeMs).toStrictEqual(1000)\n * expect(stats.mtimeMs).toStrictEqual(2000)\n */\nexport async function touch(path: string, options: TouchOptions = {}): Promise<void> {\n const {\n accessTime = Date.now(),\n modifiedTime = Date.now(),\n } = options\n\n // --- If the path does not exist, then create it.\n const fileExists = await stat(path)\n .then(() => true)\n .catch(() => false)\n\n if (!fileExists) {\n const fileDirectory = dirname(path)\n await mkdir(fileDirectory, { recursive: true })\n await writeFile(path, [])\n }\n\n // --- Update the file's access and modified times.\n await utimes(path, accessTime, modifiedTime)\n}\n"],"names":[],"mappings":";;AAsCA,eAAsB,MAAM,MAAc,UAAwB,IAAmB;
|
1
|
+
{"version":3,"file":"touch.js","sources":["../touch.ts"],"sourcesContent":["import type { TimeLike } from 'node:fs'\nimport { mkdir, stat, utimes, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport interface TouchOptions {\n\n /**\n * The time to set as the file's last access time.\n *\n * @default Date.now()\n */\n accessTime?: TimeLike\n\n /**\n * The time to set as the file's last modified time.\n *\n * @default Date.now()\n */\n modifiedTime?: TimeLike\n}\n\n/**\n * Touch a file at the given path. You can optionally specify the access and modified times\n * to set on the file. If the file does not exists, an empty file and any missing parent\n * folders will be created.\n *\n * @param path The path to the file to touch.\n * @param options The access and modified times to set on the file.\n * @returns A promise that resolves when the file has been touched.\n * @example\n * // Touch a file with a specific access and modified time.\n * await touch('/foo/bar.txt', { accessTime: 1000, modifiedTime: 2000 })\n *\n * // Check the file's access and modified times.\n * const stats = await stat('/foo/bar.txt')\n * expect(stats.atimeMs).toStrictEqual(1000)\n * expect(stats.mtimeMs).toStrictEqual(2000)\n */\nexport async function touch(path: string, options: TouchOptions = {}): Promise<void> {\n const {\n accessTime = Date.now(),\n modifiedTime = Date.now(),\n } = options\n\n // --- If the path does not exist, then create it.\n const fileExists = await stat(path)\n .then(() => true)\n .catch(() => false)\n\n if (!fileExists) {\n const fileDirectory = dirname(path)\n await mkdir(fileDirectory, { recursive: true })\n await writeFile(path, [])\n }\n\n // --- Update the file's access and modified times.\n await utimes(path, accessTime, modifiedTime)\n}\n"],"names":[],"mappings":";;AAsCA,eAAsB,MAAM,MAAc,UAAwB,IAAmB;AACnF,QAAM;AAAA,IACJ,aAAa,KAAK,IAAA;AAAA,IAClB,eAAe,KAAK,IAAA;AAAA,EAAI,IACtB;AAOJ,MAAI,CAJe,MAAM,KAAK,IAAI,EAC/B,KAAK,MAAM,EAAI,EACf,MAAM,MAAM,EAAK,GAEH;AACf,UAAM,gBAAgB,QAAQ,IAAI;AAClC,UAAM,MAAM,eAAe,EAAE,WAAW,GAAA,CAAM,GAC9C,MAAM,UAAU,MAAM,EAAE;AAAA,EAC1B;AAGA,QAAM,OAAO,MAAM,YAAY,YAAY;AAC7C;"}
|
package/dist/updateFile.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"updateFile.cjs","sources":["../updateFile.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\nimport type { MaybePromise } from '@unshared/types'\nimport type { PathLike } from 'node:fs'\nimport { open, readFile, writeFile } from 'node:fs/promises'\n\n/**\n * A callback that updates a file's contents.\n *\n * @template T The type of the file's contents.\n * @example UpdateFileCallback<string> // (content: string) => Promise<string> | string\n */\nexport type UpdateFileCallback<T extends Buffer | string> = (content: T) => MaybePromise<Buffer | string>\n\n/**\n * Open a file, update its contents using the provided callback, and close it. The file\n * must exist before calling this function or an error will be thrown.\n *\n * @param path The path to the file to update.\n * @param callback A callback that updates the file's contents.\n * @param encoding The encoding to use when reading the file.\n * @returns A promise that resolves when the file is updated.\n * @example\n * // Create a file.\n * await writeFile('/path/to/file.txt', 'foo')\n *\n * // Update a file's contents using a transform function.\n * await updateFile('/path/to/file.txt', toUpperCase, 'utf8')\n *\n * // Check the file's contents.\n * await readFile('/path/to/file.txt', 'utf8') // 'FOO'\n */\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<Buffer>): Promise<void>\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<string>, encoding: BufferEncoding): Promise<void>\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<any>, encoding?: BufferEncoding): Promise<void> {\n const fileHandle = await open(path, 'r+')\n const fileContents = await readFile(fileHandle, encoding)\n const newFileContents = await callback(fileContents)\n await writeFile(fileHandle, newFileContents)\n await fileHandle.close()\n}\n"],"names":["open","readFile","writeFile"],"mappings":";;
|
1
|
+
{"version":3,"file":"updateFile.cjs","sources":["../updateFile.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\nimport type { MaybePromise } from '@unshared/types'\nimport type { PathLike } from 'node:fs'\nimport { open, readFile, writeFile } from 'node:fs/promises'\n\n/**\n * A callback that updates a file's contents.\n *\n * @template T The type of the file's contents.\n * @example UpdateFileCallback<string> // (content: string) => Promise<string> | string\n */\nexport type UpdateFileCallback<T extends Buffer | string> = (content: T) => MaybePromise<Buffer | string>\n\n/**\n * Open a file, update its contents using the provided callback, and close it. The file\n * must exist before calling this function or an error will be thrown.\n *\n * @param path The path to the file to update.\n * @param callback A callback that updates the file's contents.\n * @param encoding The encoding to use when reading the file.\n * @returns A promise that resolves when the file is updated.\n * @example\n * // Create a file.\n * await writeFile('/path/to/file.txt', 'foo')\n *\n * // Update a file's contents using a transform function.\n * await updateFile('/path/to/file.txt', toUpperCase, 'utf8')\n *\n * // Check the file's contents.\n * await readFile('/path/to/file.txt', 'utf8') // 'FOO'\n */\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<Buffer>): Promise<void>\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<string>, encoding: BufferEncoding): Promise<void>\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<any>, encoding?: BufferEncoding): Promise<void> {\n const fileHandle = await open(path, 'r+')\n const fileContents = await readFile(fileHandle, encoding)\n const newFileContents = await callback(fileContents)\n await writeFile(fileHandle, newFileContents)\n await fileHandle.close()\n}\n"],"names":["open","readFile","writeFile"],"mappings":";;AAiCA,eAAsB,WAAW,MAAgB,UAAmC,UAA0C;AAC5H,QAAM,aAAa,MAAMA,SAAAA,KAAK,MAAM,IAAI,GAClC,eAAe,MAAMC,SAAAA,SAAS,YAAY,QAAQ,GAClD,kBAAkB,MAAM,SAAS,YAAY;AACnD,QAAMC,SAAAA,UAAU,YAAY,eAAe,GAC3C,MAAM,WAAW,MAAA;AACnB;;"}
|
package/dist/updateFile.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"updateFile.js","sources":["../updateFile.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\nimport type { MaybePromise } from '@unshared/types'\nimport type { PathLike } from 'node:fs'\nimport { open, readFile, writeFile } from 'node:fs/promises'\n\n/**\n * A callback that updates a file's contents.\n *\n * @template T The type of the file's contents.\n * @example UpdateFileCallback<string> // (content: string) => Promise<string> | string\n */\nexport type UpdateFileCallback<T extends Buffer | string> = (content: T) => MaybePromise<Buffer | string>\n\n/**\n * Open a file, update its contents using the provided callback, and close it. The file\n * must exist before calling this function or an error will be thrown.\n *\n * @param path The path to the file to update.\n * @param callback A callback that updates the file's contents.\n * @param encoding The encoding to use when reading the file.\n * @returns A promise that resolves when the file is updated.\n * @example\n * // Create a file.\n * await writeFile('/path/to/file.txt', 'foo')\n *\n * // Update a file's contents using a transform function.\n * await updateFile('/path/to/file.txt', toUpperCase, 'utf8')\n *\n * // Check the file's contents.\n * await readFile('/path/to/file.txt', 'utf8') // 'FOO'\n */\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<Buffer>): Promise<void>\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<string>, encoding: BufferEncoding): Promise<void>\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<any>, encoding?: BufferEncoding): Promise<void> {\n const fileHandle = await open(path, 'r+')\n const fileContents = await readFile(fileHandle, encoding)\n const newFileContents = await callback(fileContents)\n await writeFile(fileHandle, newFileContents)\n await fileHandle.close()\n}\n"],"names":[],"mappings":";
|
1
|
+
{"version":3,"file":"updateFile.js","sources":["../updateFile.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\nimport type { MaybePromise } from '@unshared/types'\nimport type { PathLike } from 'node:fs'\nimport { open, readFile, writeFile } from 'node:fs/promises'\n\n/**\n * A callback that updates a file's contents.\n *\n * @template T The type of the file's contents.\n * @example UpdateFileCallback<string> // (content: string) => Promise<string> | string\n */\nexport type UpdateFileCallback<T extends Buffer | string> = (content: T) => MaybePromise<Buffer | string>\n\n/**\n * Open a file, update its contents using the provided callback, and close it. The file\n * must exist before calling this function or an error will be thrown.\n *\n * @param path The path to the file to update.\n * @param callback A callback that updates the file's contents.\n * @param encoding The encoding to use when reading the file.\n * @returns A promise that resolves when the file is updated.\n * @example\n * // Create a file.\n * await writeFile('/path/to/file.txt', 'foo')\n *\n * // Update a file's contents using a transform function.\n * await updateFile('/path/to/file.txt', toUpperCase, 'utf8')\n *\n * // Check the file's contents.\n * await readFile('/path/to/file.txt', 'utf8') // 'FOO'\n */\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<Buffer>): Promise<void>\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<string>, encoding: BufferEncoding): Promise<void>\nexport async function updateFile(path: PathLike, callback: UpdateFileCallback<any>, encoding?: BufferEncoding): Promise<void> {\n const fileHandle = await open(path, 'r+')\n const fileContents = await readFile(fileHandle, encoding)\n const newFileContents = await callback(fileContents)\n await writeFile(fileHandle, newFileContents)\n await fileHandle.close()\n}\n"],"names":[],"mappings":";AAiCA,eAAsB,WAAW,MAAgB,UAAmC,UAA0C;AAC5H,QAAM,aAAa,MAAM,KAAK,MAAM,IAAI,GAClC,eAAe,MAAM,SAAS,YAAY,QAAQ,GAClD,kBAAkB,MAAM,SAAS,YAAY;AACnD,QAAM,UAAU,YAAY,eAAe,GAC3C,MAAM,WAAW,MAAA;AACnB;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"withTemporaryDirectories.cjs","sources":["../withTemporaryDirectories.ts"],"sourcesContent":["import type { Function, MaybeArray, Tuple, TupleLength } from '@unshared/types'\nimport type { CreateTemporaryDirectoryOptions } from './createTemporaryDirectory'\nimport { createTemporaryDirectory } from './createTemporaryDirectory'\n\ntype Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U> | U\n\n/**\n * Wrap a function that will create a temporary directory and\n * recursively remove it after the function has been executed,\n * regardless of whether the function throws an error or not.\n *\n * @param count The number of temporary directories to create.\n * @param fn The function to wrap that takes the temporary directory path(s) as arguments.\n * @returns A promise that resolves to the result of the function.\n */\nexport async function withTemporaryDirectories<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>\nexport async function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>\nexport async function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions>(option: T, fn: Callback<U, 1>): Promise<U>\nexport async function withTemporaryDirectories(options: MaybeArray<CreateTemporaryDirectoryOptions> | number, fn: Function<unknown>): Promise<unknown> {\n\n // --- Normalize the arguments.\n if (typeof options === 'number') options = Array.from({ length: options }, () => ({}))\n if (!Array.isArray(options)) options = [options]\n\n // --- Create temporary files.\n const pathsPromises = options.map(option => createTemporaryDirectory(option))\n const pathsInstances = await Promise.all(pathsPromises)\n const paths = pathsInstances.map(x => x[0])\n\n try {\n return await fn(...paths)\n }\n finally {\n const promises = pathsInstances.map(x => x[1]())\n await Promise.all(promises)\n }\n}\n"],"names":["createTemporaryDirectory"],"mappings":";;;;;;
|
1
|
+
{"version":3,"file":"withTemporaryDirectories.cjs","sources":["../withTemporaryDirectories.ts"],"sourcesContent":["import type { Function, MaybeArray, Tuple, TupleLength } from '@unshared/types'\nimport type { CreateTemporaryDirectoryOptions } from './createTemporaryDirectory'\nimport { createTemporaryDirectory } from './createTemporaryDirectory'\n\ntype Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U> | U\n\n/**\n * Wrap a function that will create a temporary directory and\n * recursively remove it after the function has been executed,\n * regardless of whether the function throws an error or not.\n *\n * @param count The number of temporary directories to create.\n * @param fn The function to wrap that takes the temporary directory path(s) as arguments.\n * @returns A promise that resolves to the result of the function.\n */\nexport async function withTemporaryDirectories<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>\n\n/**\n * Executes a function with temporary directories that are automatically cleaned up.\n *\n * This function creates one or more temporary directories, passes their paths to the\n * provided function, and ensures cleanup occurs even if the function throws an error.\n *\n * @param options Configuration for temporary directory creation. Can be:\n * - A number indicating how many directories to create with default options\n * - A single CreateTemporaryDirectoryOptions object\n * - An array of CreateTemporaryDirectoryOptions objects\n * @param fn The function to execute with the temporary directory paths as arguments\n * @returns A promise that resolves to the return value of the provided function\n *\n * @example\n * // Create a single temporary directory\n * await withTemporaryDirectories({}, (tempDir) => {\n * // Use tempDir...\n * });\n *\n * // Create multiple temporary directories\n * await withTemporaryDirectories([{}, { prefix: 'test-' }], (dir1, dir2) => {\n * // Use dir1 and dir2...\n * });\n *\n * // Create 3 directories with default options\n * await withTemporaryDirectories(3, (dir1, dir2, dir3) => {\n * // Use all three directories...\n * });\n */\nexport async function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>\nexport async function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions>(option: T, fn: Callback<U, 1>): Promise<U>\nexport async function withTemporaryDirectories(options: MaybeArray<CreateTemporaryDirectoryOptions> | number, fn: Function<unknown>): Promise<unknown> {\n\n // --- Normalize the arguments.\n if (typeof options === 'number') options = Array.from({ length: options }, () => ({}))\n if (!Array.isArray(options)) options = [options]\n\n // --- Create temporary files.\n const pathsPromises = options.map(option => createTemporaryDirectory(option))\n const pathsInstances = await Promise.all(pathsPromises)\n const paths = pathsInstances.map(x => x[0])\n\n try {\n return await fn(...paths)\n }\n finally {\n const promises = pathsInstances.map(x => x[1]())\n await Promise.all(promises)\n }\n}\n"],"names":["createTemporaryDirectory"],"mappings":";;;;;;AAgDA,eAAsB,yBAAyB,SAA+D,IAAyC;AAGjJ,SAAO,WAAY,aAAU,UAAU,MAAM,KAAK,EAAE,QAAQ,QAAA,GAAW,OAAO,CAAA,EAAG,IAChF,MAAM,QAAQ,OAAO,MAAG,UAAU,CAAC,OAAO;AAG/C,QAAM,gBAAgB,QAAQ,IAAI,CAAA,WAAUA,kDAAyB,MAAM,CAAC,GACtE,iBAAiB,MAAM,QAAQ,IAAI,aAAa,GAChD,QAAQ,eAAe,IAAI,CAAA,MAAK,EAAE,CAAC,CAAC;AAE1C,MAAI;AACF,WAAO,MAAM,GAAG,GAAG,KAAK;AAAA,EAC1B,UAAA;AAEE,UAAM,WAAW,eAAe,IAAI,OAAK,EAAE,CAAC,GAAG;AAC/C,UAAM,QAAQ,IAAI,QAAQ;AAAA,EAC5B;AACF;;"}
|
@@ -12,6 +12,35 @@ type Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U>
|
|
12
12
|
* @returns A promise that resolves to the result of the function.
|
13
13
|
*/
|
14
14
|
declare function withTemporaryDirectories<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>;
|
15
|
+
/**
|
16
|
+
* Executes a function with temporary directories that are automatically cleaned up.
|
17
|
+
*
|
18
|
+
* This function creates one or more temporary directories, passes their paths to the
|
19
|
+
* provided function, and ensures cleanup occurs even if the function throws an error.
|
20
|
+
*
|
21
|
+
* @param options Configuration for temporary directory creation. Can be:
|
22
|
+
* - A number indicating how many directories to create with default options
|
23
|
+
* - A single CreateTemporaryDirectoryOptions object
|
24
|
+
* - An array of CreateTemporaryDirectoryOptions objects
|
25
|
+
* @param fn The function to execute with the temporary directory paths as arguments
|
26
|
+
* @returns A promise that resolves to the return value of the provided function
|
27
|
+
*
|
28
|
+
* @example
|
29
|
+
* // Create a single temporary directory
|
30
|
+
* await withTemporaryDirectories({}, (tempDir) => {
|
31
|
+
* // Use tempDir...
|
32
|
+
* });
|
33
|
+
*
|
34
|
+
* // Create multiple temporary directories
|
35
|
+
* await withTemporaryDirectories([{}, { prefix: 'test-' }], (dir1, dir2) => {
|
36
|
+
* // Use dir1 and dir2...
|
37
|
+
* });
|
38
|
+
*
|
39
|
+
* // Create 3 directories with default options
|
40
|
+
* await withTemporaryDirectories(3, (dir1, dir2, dir3) => {
|
41
|
+
* // Use all three directories...
|
42
|
+
* });
|
43
|
+
*/
|
15
44
|
declare function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>;
|
16
45
|
declare function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions>(option: T, fn: Callback<U, 1>): Promise<U>;
|
17
46
|
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"withTemporaryDirectories.js","sources":["../withTemporaryDirectories.ts"],"sourcesContent":["import type { Function, MaybeArray, Tuple, TupleLength } from '@unshared/types'\nimport type { CreateTemporaryDirectoryOptions } from './createTemporaryDirectory'\nimport { createTemporaryDirectory } from './createTemporaryDirectory'\n\ntype Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U> | U\n\n/**\n * Wrap a function that will create a temporary directory and\n * recursively remove it after the function has been executed,\n * regardless of whether the function throws an error or not.\n *\n * @param count The number of temporary directories to create.\n * @param fn The function to wrap that takes the temporary directory path(s) as arguments.\n * @returns A promise that resolves to the result of the function.\n */\nexport async function withTemporaryDirectories<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>\nexport async function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>\nexport async function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions>(option: T, fn: Callback<U, 1>): Promise<U>\nexport async function withTemporaryDirectories(options: MaybeArray<CreateTemporaryDirectoryOptions> | number, fn: Function<unknown>): Promise<unknown> {\n\n // --- Normalize the arguments.\n if (typeof options === 'number') options = Array.from({ length: options }, () => ({}))\n if (!Array.isArray(options)) options = [options]\n\n // --- Create temporary files.\n const pathsPromises = options.map(option => createTemporaryDirectory(option))\n const pathsInstances = await Promise.all(pathsPromises)\n const paths = pathsInstances.map(x => x[0])\n\n try {\n return await fn(...paths)\n }\n finally {\n const promises = pathsInstances.map(x => x[1]())\n await Promise.all(promises)\n }\n}\n"],"names":[],"mappings":";;;;;
|
1
|
+
{"version":3,"file":"withTemporaryDirectories.js","sources":["../withTemporaryDirectories.ts"],"sourcesContent":["import type { Function, MaybeArray, Tuple, TupleLength } from '@unshared/types'\nimport type { CreateTemporaryDirectoryOptions } from './createTemporaryDirectory'\nimport { createTemporaryDirectory } from './createTemporaryDirectory'\n\ntype Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U> | U\n\n/**\n * Wrap a function that will create a temporary directory and\n * recursively remove it after the function has been executed,\n * regardless of whether the function throws an error or not.\n *\n * @param count The number of temporary directories to create.\n * @param fn The function to wrap that takes the temporary directory path(s) as arguments.\n * @returns A promise that resolves to the result of the function.\n */\nexport async function withTemporaryDirectories<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>\n\n/**\n * Executes a function with temporary directories that are automatically cleaned up.\n *\n * This function creates one or more temporary directories, passes their paths to the\n * provided function, and ensures cleanup occurs even if the function throws an error.\n *\n * @param options Configuration for temporary directory creation. Can be:\n * - A number indicating how many directories to create with default options\n * - A single CreateTemporaryDirectoryOptions object\n * - An array of CreateTemporaryDirectoryOptions objects\n * @param fn The function to execute with the temporary directory paths as arguments\n * @returns A promise that resolves to the return value of the provided function\n *\n * @example\n * // Create a single temporary directory\n * await withTemporaryDirectories({}, (tempDir) => {\n * // Use tempDir...\n * });\n *\n * // Create multiple temporary directories\n * await withTemporaryDirectories([{}, { prefix: 'test-' }], (dir1, dir2) => {\n * // Use dir1 and dir2...\n * });\n *\n * // Create 3 directories with default options\n * await withTemporaryDirectories(3, (dir1, dir2, dir3) => {\n * // Use all three directories...\n * });\n */\nexport async function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>\nexport async function withTemporaryDirectories<U, T extends CreateTemporaryDirectoryOptions>(option: T, fn: Callback<U, 1>): Promise<U>\nexport async function withTemporaryDirectories(options: MaybeArray<CreateTemporaryDirectoryOptions> | number, fn: Function<unknown>): Promise<unknown> {\n\n // --- Normalize the arguments.\n if (typeof options === 'number') options = Array.from({ length: options }, () => ({}))\n if (!Array.isArray(options)) options = [options]\n\n // --- Create temporary files.\n const pathsPromises = options.map(option => createTemporaryDirectory(option))\n const pathsInstances = await Promise.all(pathsPromises)\n const paths = pathsInstances.map(x => x[0])\n\n try {\n return await fn(...paths)\n }\n finally {\n const promises = pathsInstances.map(x => x[1]())\n await Promise.all(promises)\n }\n}\n"],"names":[],"mappings":";;;;;AAgDA,eAAsB,yBAAyB,SAA+D,IAAyC;AAGjJ,SAAO,WAAY,aAAU,UAAU,MAAM,KAAK,EAAE,QAAQ,QAAA,GAAW,OAAO,CAAA,EAAG,IAChF,MAAM,QAAQ,OAAO,MAAG,UAAU,CAAC,OAAO;AAG/C,QAAM,gBAAgB,QAAQ,IAAI,CAAA,WAAU,yBAAyB,MAAM,CAAC,GACtE,iBAAiB,MAAM,QAAQ,IAAI,aAAa,GAChD,QAAQ,eAAe,IAAI,CAAA,MAAK,EAAE,CAAC,CAAC;AAE1C,MAAI;AACF,WAAO,MAAM,GAAG,GAAG,KAAK;AAAA,EAC1B,UAAA;AAEE,UAAM,WAAW,eAAe,IAAI,OAAK,EAAE,CAAC,GAAG;AAC/C,UAAM,QAAQ,IAAI,QAAQ;AAAA,EAC5B;AACF;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"withTemporaryFiles.cjs","sources":["../withTemporaryFiles.ts"],"sourcesContent":["import type { Function, MaybeArray, Tuple, TupleLength } from '@unshared/types'\nimport type { CreateTemporaryFileOptions } from './createTemporaryFile'\nimport { createTemporaryFile } from './createTemporaryFile'\n\ntype Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U> | U\n\n/**\n * Wrap a function that will create one or more temporary files and\n * remove them after the function has been executed, regardless of\n * whether the function throws an error or not.\n *\n * @param count The number of temporary files to create.\n * @param fn The function to wrap that takes the temporary directory path(s) as arguments.\n * @returns A promise that resolves to the result of the function.\n */\nexport async function withTemporaryFiles<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>\nexport async function withTemporaryFiles<U, T extends CreateTemporaryFileOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>\nexport async function withTemporaryFiles<U, T extends CreateTemporaryFileOptions>(option: T, fn: Callback<U, 1>): Promise<U>\nexport async function withTemporaryFiles(options: MaybeArray<CreateTemporaryFileOptions> | number, fn: Function<unknown>): Promise<unknown> {\n\n // --- Normalize the arguments.\n if (typeof options === 'number') options = Array.from({ length: options }, () => ({}))\n if (!Array.isArray(options)) options = [options]\n\n // --- Create temporary files.\n const pathsPromises = options.map(option => createTemporaryFile(undefined, option))\n const pathsInstances = await Promise.all(pathsPromises)\n const paths = pathsInstances.map(x => x[0])\n\n // --- Execute the function with the temporary files.\n try {\n return await fn(...paths)\n }\n\n // --- On completion, remove the temporary files.\n finally {\n const promises = pathsInstances.map(x => x[1]())\n await Promise.all(promises)\n }\n}\n"],"names":["createTemporaryFile"],"mappings":";;;;;;
|
1
|
+
{"version":3,"file":"withTemporaryFiles.cjs","sources":["../withTemporaryFiles.ts"],"sourcesContent":["import type { Function, MaybeArray, Tuple, TupleLength } from '@unshared/types'\nimport type { CreateTemporaryFileOptions } from './createTemporaryFile'\nimport { createTemporaryFile } from './createTemporaryFile'\n\ntype Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U> | U\n\n/**\n * Wrap a function that will create one or more temporary files and\n * remove them after the function has been executed, regardless of\n * whether the function throws an error or not.\n *\n * @param count The number of temporary files to create.\n * @param fn The function to wrap that takes the temporary directory path(s) as arguments.\n * @returns A promise that resolves to the result of the function.\n */\nexport async function withTemporaryFiles<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>\n\n/**\n * Executes a function with temporary files and automatically cleans them up afterwards.\n *\n * This function creates one or more temporary files, passes their paths to the provided\n * function, and ensures the temporary files are removed after the function completes,\n * regardless of whether it succeeds or throws an error.\n *\n * @param options Configuration for creating temporary files. Can be:\n * - A number indicating how many temporary files to create with default options\n * - A single CreateTemporaryFileOptions object for one temporary file\n * - An array of CreateTemporaryFileOptions objects for multiple temporary files\n * @param fn The function to execute with the temporary file paths as arguments\n * @returns A promise that resolves to the return value of the provided function\n *\n * @example\n * // Create 2 temporary files with default options\n * const result = await withTemporaryFiles(2, (path1, path2) => {\n * // Use the temporary files\n * return someOperation(path1, path2);\n * });\n *\n * // Create temporary files with specific options\n * const result = await withTemporaryFiles([\n * { extension: '.txt' },\n * { prefix: 'temp-', extension: '.json' }\n * ], (txtFile, jsonFile) => {\n * // Use the temporary files\n * return processFiles(txtFile, jsonFile);\n * });\n */\nexport async function withTemporaryFiles<U, T extends CreateTemporaryFileOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>\nexport async function withTemporaryFiles<U, T extends CreateTemporaryFileOptions>(option: T, fn: Callback<U, 1>): Promise<U>\nexport async function withTemporaryFiles(options: MaybeArray<CreateTemporaryFileOptions> | number, fn: Function<unknown>): Promise<unknown> {\n\n // --- Normalize the arguments.\n if (typeof options === 'number') options = Array.from({ length: options }, () => ({}))\n if (!Array.isArray(options)) options = [options]\n\n // --- Create temporary files.\n const pathsPromises = options.map(option => createTemporaryFile(undefined, option))\n const pathsInstances = await Promise.all(pathsPromises)\n const paths = pathsInstances.map(x => x[0])\n\n // --- Execute the function with the temporary files.\n try {\n return await fn(...paths)\n }\n\n // --- On completion, remove the temporary files.\n finally {\n const promises = pathsInstances.map(x => x[1]())\n await Promise.all(promises)\n }\n}\n"],"names":["createTemporaryFile"],"mappings":";;;;;;AAiDA,eAAsB,mBAAmB,SAA0D,IAAyC;AAGtI,SAAO,WAAY,aAAU,UAAU,MAAM,KAAK,EAAE,QAAQ,QAAA,GAAW,OAAO,CAAA,EAAG,IAChF,MAAM,QAAQ,OAAO,MAAG,UAAU,CAAC,OAAO;AAG/C,QAAM,gBAAgB,QAAQ,IAAI,CAAA,WAAUA,oBAAAA,oBAAoB,QAAW,MAAM,CAAC,GAC5E,iBAAiB,MAAM,QAAQ,IAAI,aAAa,GAChD,QAAQ,eAAe,IAAI,CAAA,MAAK,EAAE,CAAC,CAAC;AAG1C,MAAI;AACF,WAAO,MAAM,GAAG,GAAG,KAAK;AAAA,EAC1B,UAAA;AAIE,UAAM,WAAW,eAAe,IAAI,OAAK,EAAE,CAAC,GAAG;AAC/C,UAAM,QAAQ,IAAI,QAAQ;AAAA,EAC5B;AACF;;"}
|
@@ -13,6 +13,36 @@ type Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U>
|
|
13
13
|
* @returns A promise that resolves to the result of the function.
|
14
14
|
*/
|
15
15
|
declare function withTemporaryFiles<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>;
|
16
|
+
/**
|
17
|
+
* Executes a function with temporary files and automatically cleans them up afterwards.
|
18
|
+
*
|
19
|
+
* This function creates one or more temporary files, passes their paths to the provided
|
20
|
+
* function, and ensures the temporary files are removed after the function completes,
|
21
|
+
* regardless of whether it succeeds or throws an error.
|
22
|
+
*
|
23
|
+
* @param options Configuration for creating temporary files. Can be:
|
24
|
+
* - A number indicating how many temporary files to create with default options
|
25
|
+
* - A single CreateTemporaryFileOptions object for one temporary file
|
26
|
+
* - An array of CreateTemporaryFileOptions objects for multiple temporary files
|
27
|
+
* @param fn The function to execute with the temporary file paths as arguments
|
28
|
+
* @returns A promise that resolves to the return value of the provided function
|
29
|
+
*
|
30
|
+
* @example
|
31
|
+
* // Create 2 temporary files with default options
|
32
|
+
* const result = await withTemporaryFiles(2, (path1, path2) => {
|
33
|
+
* // Use the temporary files
|
34
|
+
* return someOperation(path1, path2);
|
35
|
+
* });
|
36
|
+
*
|
37
|
+
* // Create temporary files with specific options
|
38
|
+
* const result = await withTemporaryFiles([
|
39
|
+
* { extension: '.txt' },
|
40
|
+
* { prefix: 'temp-', extension: '.json' }
|
41
|
+
* ], (txtFile, jsonFile) => {
|
42
|
+
* // Use the temporary files
|
43
|
+
* return processFiles(txtFile, jsonFile);
|
44
|
+
* });
|
45
|
+
*/
|
16
46
|
declare function withTemporaryFiles<U, T extends CreateTemporaryFileOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>;
|
17
47
|
declare function withTemporaryFiles<U, T extends CreateTemporaryFileOptions>(option: T, fn: Callback<U, 1>): Promise<U>;
|
18
48
|
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"withTemporaryFiles.js","sources":["../withTemporaryFiles.ts"],"sourcesContent":["import type { Function, MaybeArray, Tuple, TupleLength } from '@unshared/types'\nimport type { CreateTemporaryFileOptions } from './createTemporaryFile'\nimport { createTemporaryFile } from './createTemporaryFile'\n\ntype Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U> | U\n\n/**\n * Wrap a function that will create one or more temporary files and\n * remove them after the function has been executed, regardless of\n * whether the function throws an error or not.\n *\n * @param count The number of temporary files to create.\n * @param fn The function to wrap that takes the temporary directory path(s) as arguments.\n * @returns A promise that resolves to the result of the function.\n */\nexport async function withTemporaryFiles<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>\nexport async function withTemporaryFiles<U, T extends CreateTemporaryFileOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>\nexport async function withTemporaryFiles<U, T extends CreateTemporaryFileOptions>(option: T, fn: Callback<U, 1>): Promise<U>\nexport async function withTemporaryFiles(options: MaybeArray<CreateTemporaryFileOptions> | number, fn: Function<unknown>): Promise<unknown> {\n\n // --- Normalize the arguments.\n if (typeof options === 'number') options = Array.from({ length: options }, () => ({}))\n if (!Array.isArray(options)) options = [options]\n\n // --- Create temporary files.\n const pathsPromises = options.map(option => createTemporaryFile(undefined, option))\n const pathsInstances = await Promise.all(pathsPromises)\n const paths = pathsInstances.map(x => x[0])\n\n // --- Execute the function with the temporary files.\n try {\n return await fn(...paths)\n }\n\n // --- On completion, remove the temporary files.\n finally {\n const promises = pathsInstances.map(x => x[1]())\n await Promise.all(promises)\n }\n}\n"],"names":[],"mappings":";;;;;
|
1
|
+
{"version":3,"file":"withTemporaryFiles.js","sources":["../withTemporaryFiles.ts"],"sourcesContent":["import type { Function, MaybeArray, Tuple, TupleLength } from '@unshared/types'\nimport type { CreateTemporaryFileOptions } from './createTemporaryFile'\nimport { createTemporaryFile } from './createTemporaryFile'\n\ntype Callback<U, N extends number> = (...paths: Tuple<N, string>) => Promise<U> | U\n\n/**\n * Wrap a function that will create one or more temporary files and\n * remove them after the function has been executed, regardless of\n * whether the function throws an error or not.\n *\n * @param count The number of temporary files to create.\n * @param fn The function to wrap that takes the temporary directory path(s) as arguments.\n * @returns A promise that resolves to the result of the function.\n */\nexport async function withTemporaryFiles<U, N extends number>(count: N, fn: Callback<U, N>): Promise<U>\n\n/**\n * Executes a function with temporary files and automatically cleans them up afterwards.\n *\n * This function creates one or more temporary files, passes their paths to the provided\n * function, and ensures the temporary files are removed after the function completes,\n * regardless of whether it succeeds or throws an error.\n *\n * @param options Configuration for creating temporary files. Can be:\n * - A number indicating how many temporary files to create with default options\n * - A single CreateTemporaryFileOptions object for one temporary file\n * - An array of CreateTemporaryFileOptions objects for multiple temporary files\n * @param fn The function to execute with the temporary file paths as arguments\n * @returns A promise that resolves to the return value of the provided function\n *\n * @example\n * // Create 2 temporary files with default options\n * const result = await withTemporaryFiles(2, (path1, path2) => {\n * // Use the temporary files\n * return someOperation(path1, path2);\n * });\n *\n * // Create temporary files with specific options\n * const result = await withTemporaryFiles([\n * { extension: '.txt' },\n * { prefix: 'temp-', extension: '.json' }\n * ], (txtFile, jsonFile) => {\n * // Use the temporary files\n * return processFiles(txtFile, jsonFile);\n * });\n */\nexport async function withTemporaryFiles<U, T extends CreateTemporaryFileOptions[]>(options: T, fn: Callback<U, TupleLength<T>>): Promise<U>\nexport async function withTemporaryFiles<U, T extends CreateTemporaryFileOptions>(option: T, fn: Callback<U, 1>): Promise<U>\nexport async function withTemporaryFiles(options: MaybeArray<CreateTemporaryFileOptions> | number, fn: Function<unknown>): Promise<unknown> {\n\n // --- Normalize the arguments.\n if (typeof options === 'number') options = Array.from({ length: options }, () => ({}))\n if (!Array.isArray(options)) options = [options]\n\n // --- Create temporary files.\n const pathsPromises = options.map(option => createTemporaryFile(undefined, option))\n const pathsInstances = await Promise.all(pathsPromises)\n const paths = pathsInstances.map(x => x[0])\n\n // --- Execute the function with the temporary files.\n try {\n return await fn(...paths)\n }\n\n // --- On completion, remove the temporary files.\n finally {\n const promises = pathsInstances.map(x => x[1]())\n await Promise.all(promises)\n }\n}\n"],"names":[],"mappings":";;;;;AAiDA,eAAsB,mBAAmB,SAA0D,IAAyC;AAGtI,SAAO,WAAY,aAAU,UAAU,MAAM,KAAK,EAAE,QAAQ,QAAA,GAAW,OAAO,CAAA,EAAG,IAChF,MAAM,QAAQ,OAAO,MAAG,UAAU,CAAC,OAAO;AAG/C,QAAM,gBAAgB,QAAQ,IAAI,CAAA,WAAU,oBAAoB,QAAW,MAAM,CAAC,GAC5E,iBAAiB,MAAM,QAAQ,IAAI,aAAa,GAChD,QAAQ,eAAe,IAAI,CAAA,MAAK,EAAE,CAAC,CAAC;AAG1C,MAAI;AACF,WAAO,MAAM,GAAG,GAAG,KAAK;AAAA,EAC1B,UAAA;AAIE,UAAM,WAAW,eAAe,IAAI,OAAK,EAAE,CAAC,GAAG;AAC/C,UAAM,QAAQ,IAAI,QAAQ;AAAA,EAC5B;AACF;"}
|
package/package.json
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"name": "@unshared/fs",
|
3
3
|
"type": "module",
|
4
|
-
"version": "0.
|
4
|
+
"version": "0.7.0",
|
5
5
|
"license": "MIT",
|
6
6
|
"sideEffects": false,
|
7
7
|
"author": "Stanley Horwood <stanley@hsjm.io>",
|
@@ -78,13 +78,13 @@
|
|
78
78
|
"LICENSE.md"
|
79
79
|
],
|
80
80
|
"dependencies": {
|
81
|
-
"@unshared/collection": "0.
|
82
|
-
"@unshared/functions": "0.
|
83
|
-
"@unshared/reactivity": "0.
|
84
|
-
"@unshared/string": "0.
|
85
|
-
"@unshared/types": "0.
|
81
|
+
"@unshared/collection": "0.7.0",
|
82
|
+
"@unshared/functions": "0.7.0",
|
83
|
+
"@unshared/reactivity": "0.7.0",
|
84
|
+
"@unshared/string": "0.7.0",
|
85
|
+
"@unshared/types": "0.7.0"
|
86
86
|
},
|
87
87
|
"devDependencies": {
|
88
|
-
"memfs": "4.
|
88
|
+
"memfs": "4.36.3"
|
89
89
|
}
|
90
90
|
}
|