{"name":"try","version":"1.0.1","keywords":["try","operator","result","safe","error","proposal"],"author":{"url":"https://arthur.place","name":"Arthur Fiorette"},"license":"MIT","_id":"try@1.0.1","maintainers":[{"name":"szymon.wygnanski","email":"s@finalclass.net"},{"name":"hazork","email":"arthur.fiorette@gmail.com"}],"contributors":[{"url":"https://finalclass.net","name":"Szymon Wygnański"}],"homepage":"https://github.com/arthurfiorette/try#readme","bugs":{"url":"https://github.com/arthurfiorette/try/issues"},"dist":{"shasum":"ab63d9d2449f20d4a6de73a84dbd118b1b18e831","tarball":"http://registry-npm.ywwl.com/try/download/try-1.0.1.tgz","fileCount":5,"integrity":"sha512-3S6RIoraErJFhkNmlNyojU9YmaEs6M2qvAyy7lSb6PgSbiX5hOgyeLVsgwJ74lCSMLxjCggtgiaOJ4BtCV7LNA==","signatures":[{"sig":"MEQCIAr+FX3mPoM4MpYD3O0IxkPTlS8eUA7+thf+Ep5s0H+fAiBfImhA+EQs4DOrn1gT1e+IvbBKNUAYei+2e/Qy2Flm3A==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/try@1.0.1","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":18632,"size":6797,"noattachment":false,"key":"/try/-/try-1.0.1.tgz"},"main":"lib/index.js","type":"module","_from":"file:try-1.0.1.tgz","types":"lib/index.d.ts","funding":"https://github.com/arthurfiorette/try?sponsor=1","scripts":{"lint":"biome check .","test":"c8 --reporter lcov node --test test/**/*.js","format":"biome format --write .","lint-ci":"biome ci .","lint-fix":"biome check --write --unsafe .","test-types":"tsd --show-diff -f test","test-watch":"node --watch --test test/**/*.js"},"_npmUser":{"name":"szymon.wygnanski","email":"s@finalclass.net"},"_resolved":"/tmp/1f8c19339c9b7345b38af0bb77bfca66/try-1.0.1.tgz","_integrity":"sha512-3S6RIoraErJFhkNmlNyojU9YmaEs6M2qvAyy7lSb6PgSbiX5hOgyeLVsgwJ74lCSMLxjCggtgiaOJ4BtCV7LNA==","repository":{"url":"git+https://github.com/arthurfiorette/try.git","type":"git"},"_npmVersion":"11.6.3","description":"A 373-byte Spec-Compliant Runtime-Only Implementation of the ECMAScript Try Operator Proposal Result class","directories":{},"sideEffects":false,"_nodeVersion":"24.11.1","publishConfig":{"tag":"latest","access":"public","provenance":true},"_hasShrinkwrap":false,"devDependencies":{"c8":"^10.1.3","tsd":"^0.33.0","husky":"^9.1.7","typescript":"^5.9.3","@types/node":"^24.10.1","@biomejs/biome":"^2.3.7","@arthurfiorette/biomejs-config":"^2.0.1"},"_npmOperationalInternal":{"tmp":"tmp/try_1.0.1_1763866763319_0.03406158573121831","host":"s3://npm-registry-packages-npm-production"},"readme":"<p align=\"center\">\n   <b>Using this package?</b> Please consider <a href=\"https://github.com/arthurfiorette/try?sponsor=1\" target=\"_blank\">donating</a> to support the proposal ❤️\n  <br />\n  <sup>\n   Help <code>try</code> grow! Star and share this amazing repository with your friends and co-workers!\n  </sup>\n</p>\n\n<p align=\"center\">\n  <a title=\"MIT license\" target=\"_blank\" href=\"https://github.com/arthurfiorette/try/blob/main/LICENSE\"><img alt=\"License\" src=\"https://img.shields.io/github/license/arthurfiorette/try\"></a>\n  <a title=\"NPM Package\" target=\"_blank\" href=\"https://www.npmjs.com/package/try\"><img alt=\"Downloads\" src=\"https://img.shields.io/npm/dw/try?style=flat\"></a>\n  <a title=\"Bundle size\" target=\"_blank\" href=\"https://bundlephobia.com/package/try\"><img alt=\"Bundlephobia\" src=\"https://img.shields.io/bundlephobia/minzip/try/latest?style=flat\"></a>\n  <a title=\"Last Commit\" target=\"_blank\" href=\"https://github.com/arthurfiorette/try/commits/main\"><img alt=\"Last commit\" src=\"https://img.shields.io/github/last-commit/arthurfiorette/try\"></a>\n  <a title=\"Codecov\" target=\"_blank\" href=\"https://app.codecov.io/gh/arthurfiorette/try\"><img alt=\"Codecov\" src=\"https://codecov.io/gh/arthurfiorette/try/graph/badge.svg?token=ky185JbytA\"></a>\n  \n</p>\n\n<br />\n\n<h1>TRY</h1>\n\n> A [373-byte](https://bundlephobia.com/package/try) spec-compliant runtime-only implementation of the [`Result` class from the ECMAScript Try Operator proposal](https://github.com/arthurfiorette/proposal-try-operator).\n\n```ts\nimport { t } from 'try';\n\nconst [ok, error, value] = t(() => JSON.parse('{\"foo\": \"bar\"}'));\nconst [ok, error, value] = await t(axios.get('https://arthur.place'));\n```\n\n<br />\n\nThis package is a minimal and precise reference implementation of the [`Result` class](https://github.com/arthurfiorette/proposal-try-operator#result-class) as described in the [Try Operator](https://github.com/arthurfiorette/proposal-try-operator) proposal for JavaScript.\n\nIt aims to provide a lightweight and fast runtime utility that reflects exactly how the proposed `try` operator would behave, and **will not evolve independently of the proposal**.\n\nIf you'd like to suggest changes or improvements to the behavior or API, please [open an issue on the proposal repository](https://github.com/arthurfiorette/proposal-try-operator/issues/new/choose). Once discussed and approved there, changes will be reflected in this package.\n\n<br />\n\n- [Why This Exists](#why-this-exists)\n- [Usage](#usage)\n  - [Wrapping a Function Call](#wrapping-a-function-call)\n  - [`t()` alias](#t-alias)\n  - [Prefer Using the Result Object in Multi-Try Scenarios](#prefer-using-the-result-object-in-multi-try-scenarios)\n- [Works With Promises Too!](#works-with-promises-too)\n- [No `Result.bind`](#no-resultbind)\n- [Creating Results Manually](#creating-results-manually)\n- [Learn More](#learn-more)\n- [Acknowledgements](#acknowledgements)\n- [License](#license)\n\n<br />\n\n```ts\nimport { Result, ok, error, t } from 'try';\n\n// Synchronous function call\nconst [ok1, err1, val1] = t(JSON.parse, '{\"foo\":\"bar\"}');\n\n// Arrow function context\nconst [ok2, err2, val2] = t(() => decoder.decode(buffer));\n\n// Promise call\nconst [ok3, err3, val3] = await t(fetch, 'https://api.example.com');\n\n// Promise-safe call (safely catches both sync and async errors)\nconst [ok4, err4, val4] = await t(() => readFile('./config.json'));\n\n// Argument passthrough\nconst [ok5, err5, val5] = t((a, b) => a + b, 2, 3);\n\n// Keep full result object for readability\nconst result = await t(fetch, 'https://arthur.place');\nif (result.ok) console.log(await result.value.text());\n\n// Manual success and error results\nconst success = ok(42);\nconst failure = error(new Error('nope'));\n\n// Manual Result creation via class\nconst successObj = Result.ok('done');\nconst failureObj = Result.error('fail');\n```\n\n<br />\n\n## Why This Exists\n\nJavaScript error handling can be verbose and inconsistent. The [Try Operator proposal](https://github.com/arthurfiorette/proposal-try-operator) introduces a new pattern that returns structured `Result` objects instead of throwing exceptions, simplifying async and sync error flows alike.\n\nWhile the proposal is still in the works, this package provides a way to experiment with the new pattern in a standardized way.\n\nThis package provides a drop-in utility: `Result.try()` (or the shorter `t()`) to wrap expressions and handle errors in a clean, tuple-like form.\n\n```ts\nconst [ok, error, value] = t(JSON.parse, '{\"foo\":\"bar\"}');\n\nif (ok) {\n  console.log(value.foo);\n} else {\n  console.error('Invalid JSON', error);\n}\n```\n\n> You can destructure the result into `[ok, error, value]`, or access `.ok`, `.error`, and `.value` directly depending on your use case.\n\n<br />\n\n## Usage\n\nAll methods are documented via TSDoc, so your editor will guide you with full type support and autocomplete.\n\n### Wrapping a Function Call\n\nUse `Result.try()` or `t()` to wrap a potentially failing operation:\n\n```ts\nconst [ok, error, value] = Result.try(() => JSON.parse(request.body));\n\nif (ok) {\n  console.log(`Hello ${value.name}`);\n} else {\n  console.error(`Invalid JSON!`);\n}\n```\n\n> [!NOTE]  \n>  `Result.try(() => fn())` is verbose compared to the proposal's future `try fn()` syntax. Always prefer to use the `t()` alias for cleaner code.\n\n<br />\n\n### `t()` alias\n\nTo make code cleaner and more ergonomic while we wait for language-level syntax sugar, this package also exports `t`, a shortcut for `Result.try`.\n\n```ts\nimport { readFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\n\n// Example (this is void)\nconst [ok, error, value] = t(readFileSync, './config.json');\n// If `this` matters in your context\nconst [ok, error, value] = t(() => decoder.decode(request.body));\n// Promises don't need wrapping\nconst [ok, error, value] = await t(axios.get('http://example.com'));\n// Safer way even for promises (catches sync errors before returning a promise)\nconst [ok, error, value] = await t(readFile, path);\n```\n\nThe `t(fn, ...args)` form is ideal: it automatically passes arguments to your function, preserves full TypeScript inference, and keeps code short and readable.\n\n```ts\nfunction divide(a: number, b: number) {\n  return a / b;\n}\n\nconst [ok, error, value] = t(divide, 10, 2);\n// ok: true, value: 5\n```\n\n<br />\n\n### Prefer Using the Result Object in Multi-Try Scenarios\n\nWhile destructuring works well for simple use cases, it can lead to awkward variable naming and clutter when handling multiple `try` results. In these cases, **it's recommended to keep the full result object and access `.ok`, `.error`, and `.value` directly** for better clarity and readability.\n\n❌ Bad (managing variable names becomes cumbersome):\n\n```ts\n// error handling omitted for brevity\nconst [ok1, error1, value1] = Result.try(() => axios.get(...));\nconst [ok2, error2, value2] = Result.try(() => value1.data.property);\n```\n\n✅ Better (clearer structure and easier to follow):\n\n```ts\n// error handling omitted for brevity\nconst response = await Result.try(fetch('https://arthur.place'));\nconst data = await Result.try(() => response.value.text()));\n```\n\nUsing the result object directly avoids unnecessary boilerplate and naming inconsistencies, especially in nested or sequential operations. It's a cleaner, more scalable pattern that mirrors real-world error handling flows.\n\n<br />\n\n## Works With Promises Too!\n\nYou can pass a `Promise` directly and get a `Result`-wrapped version:\n\n```ts\nconst [ok, error, value] = await t(\n  fs.promises.readFile('./config.json')\n);\n\nif (ok) {\n  const config = JSON.parse(value.toString());\n} else {\n  console.error('Failed to read file', error);\n}\n```\n\nThe return value of `t()` is automatically `await`-able if the function returns a promise, no extra handling required.\n\n<br />\n\n## No `Result.bind`\n\nThis implementation **will never provide a `Result.bind()`** (like `util.promisify`) because the Try Operator follows the [Caller’s Approach](https://github.com/arthurfiorette/proposal-try-operator/tree/main#callers-approach) model.\n\nThat means **error handling belongs to the calling context**, not the function itself. Wrapping a function with `bind()` would push error encapsulation into the callee, breaking that principle.\n\n**In short:** the caller chooses to wrap a function call in `Result.try`, not the function author.\n\n<br />\n\n## Creating Results Manually\n\nYou can also create `Result` objects directly:\n\n```ts\nimport { Result, ok, error } from 'try';\n\n// With full Result class\nconst res1 = Result.ok('done');\nconst res2 = Result.error('fail');\n\n// Shorthand\nconst okRes = ok(42);\nconst errRes = error('oops');\n```\n\nThis is useful when bridging non-try-based code or mocking results.\n\n<br />\n\n## Learn More\n\nTo learn about the underlying proposal, including syntax goals and motivation, visit:\n\n🔗 https://github.com/arthurfiorette/proposal-try-operator\n\n<br />\n\n## Acknowledgements\n\nMany thanks to [Szymon Wygnański](https://finalclass.net) for transferring the `try` package name on NPM to this project. Versions below `1.0.0` served a different purpose, but with his permission, the project was repurposed to host an implementation of the proposal’s `Result` class.\n\n<br />\n\n## License\n\nBoth the project and the proposal are licensed under the [MIT](./LICENSE) license.\n\n<br />\n","publish_time":1763866763505,"_cnpm_publish_time":1763866763505,"dist-tags":{"latest":"1.0.3"}}