{"id":13602111,"url":"https://github.com/rosiejs/rosie","last_synced_at":"2025-12-12T03:12:04.211Z","repository":{"id":38272139,"uuid":"1619724","full_name":"rosiejs/rosie","owner":"rosiejs","description":"factory for building JavaScript objects, mostly useful for setting up test data. Inspired by factory_girl","archived":false,"fork":false,"pushed_at":"2024-03-25T21:12:54.000Z","size":731,"stargazers_count":1059,"open_issues_count":14,"forks_count":92,"subscribers_count":10,"default_branch":"main","last_synced_at":"2025-08-10T12:30:10.006Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rosiejs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2011-04-15T16:08:10.000Z","updated_at":"2025-07-12T12:20:27.000Z","dependencies_parsed_at":"2024-06-18T12:18:53.163Z","dependency_job_id":"f0ec38d1-47ab-4432-a762-0ed0a3be25e8","html_url":"https://github.com/rosiejs/rosie","commit_stats":{"total_commits":139,"total_committers":29,"mean_commits":4.793103448275862,"dds":0.7410071942446044,"last_synced_commit":"3fec83d8f7a4e70c42bc29a800bcc9e15488ba82"},"previous_names":["bkeepers/rosie"],"tags_count":16,"template":false,"template_full_name":null,"purl":"pkg:github/rosiejs/rosie","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rosiejs%2Frosie","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rosiejs%2Frosie/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rosiejs%2Frosie/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rosiejs%2Frosie/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rosiejs","download_url":"https://codeload.github.com/rosiejs/rosie/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rosiejs%2Frosie/sbom","scorecard":{"id":241591,"data":{"date":"2025-08-11","repo":{"name":"github.com/rosiejs/rosie","commit":"3fec83d8f7a4e70c42bc29a800bcc9e15488ba82"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":3.1,"checks":[{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Pinned-Dependencies","score":3,"reason":"dependency not pinned by hash detected -- score normalized to 3","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/rosiejs/rosie/node.js.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/rosiejs/rosie/node.js.yml/main?enable=pin","Info:   0 out of   2 GitHub-owned GitHubAction dependencies pinned","Info:   1 out of   1 npmCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Code-Review","score":1,"reason":"Found 2/17 approved changesets -- score normalized to 1","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/node.js.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":9,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Warn: project license file does not contain an FSF or OSI license."],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 30 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":1,"reason":"9 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-968p-4wvh-cqc8","Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92","Warn: Project is vulnerable to: GHSA-v6h2-p8h4-qcjw","Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg","Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275","Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h","Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv","Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw","Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-17T06:46:06.625Z","repository_id":38272139,"created_at":"2025-08-17T06:46:06.625Z","updated_at":"2025-08-17T06:46:06.625Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27675323,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-12T02:00:06.775Z","response_time":129,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T18:01:14.406Z","updated_at":"2025-12-12T03:12:04.173Z","avatar_url":"https://github.com/rosiejs.png","language":"JavaScript","funding_links":[],"categories":["Web 后端","JavaScript"],"sub_categories":[],"readme":"# Rosie\n\n![Rosie the Riveter](https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/We_Can_Do_It%21.jpg/220px-We_Can_Do_It%21.jpg)\n\nRosie is a factory for building JavaScript objects, mostly useful for setting up test data. It is inspired by [factory_bot](https://github.com/thoughtbot/factory_bot).\n\nTo use Rosie you first define a _factory_. The _factory_ is defined in terms of _attributes_, _sequences_, _options_, _callbacks_, and can inherit from other factories. Once the factory is defined you use it to build _objects_.\n\n## Usage\n\nThere are two phases of use:\n\n1.  Factory definition\n2.  Object building\n\n**Factory Definition:** Define your factory, giving it a name and optionally a constructor function (`game` in this example):\n\n```js\nFactory.define('game')\n  .sequence('id')\n  .attr('is_over', false)\n  .attr('created_at', () =\u003e new Date())\n  .attr('random_seed', () =\u003e Math.random())\n\n  // Default to two players. If players were given, fill in\n  // whatever attributes might be missing.\n  .attr('players', ['players'], (players) =\u003e {\n    if (!players) {\n      players = [{}, {}];\n    }\n    return players.map((data) =\u003e Factory.attributes('player', data));\n  });\n\nFactory.define('player')\n  .sequence('id')\n  .sequence('name', (i) =\u003e {\n    return 'player' + i;\n  })\n\n  // Define `position` to depend on `id`.\n  .attr('position', ['id'], (id) =\u003e {\n    const positions = ['pitcher', '1st base', '2nd base', '3rd base'];\n    return positions[id % positions.length];\n  });\n\nFactory.define('disabled-player').extend('player').attr('state', 'disabled');\n```\n\n**Object Building:** Build an object, passing in attributes that you want to override:\n\n```js\nconst game = Factory.build('game', { is_over: true });\n// Built object (note scores are random):\n//{\n//    id:           1,\n//    is_over:      true,   // overriden when building\n//    created_at:   Fri Apr 15 2011 12:02:25 GMT-0400 (EDT),\n//    random_seed:  0.8999513240996748,\n//    players: [\n//                {id: 1, name:'Player 1'},\n//                {id: 2, name:'Player 2'}\n//    ]\n//}\n```\n\nFor a factory with a constructor, if you want just the attributes:\n\n```js\nFactory.attributes('game'); // return just the attributes\n```\n\n### Programmatic Generation of Attributes\n\nYou can specify options that are used to programmatically generate the attributes:\n\n```js\nconst moment = require('moment');\n\nFactory.define('matches')\n  .attr('seasonStart', '2016-01-01')\n  .option('numMatches', 2)\n  .attr('matches', ['numMatches', 'seasonStart'], (numMatches, seasonStart) =\u003e {\n    const matches = [];\n    for (const i = 1; i \u003c= numMatches; i++) {\n      matches.push({\n        matchDate: moment(seasonStart).add(i, 'week').format('YYYY-MM-DD'),\n        homeScore: Math.floor(Math.random() * 5),\n        awayScore: Math.floor(Math.random() * 5),\n      });\n    }\n    return matches;\n  });\n\nFactory.build('matches', { seasonStart: '2016-03-12' }, { numMatches: 3 });\n// Built object (note scores are random):\n//{\n//  seasonStart: '2016-03-12',\n//  matches: [\n//    { matchDate: '2016-03-19', homeScore: 3, awayScore: 1 },\n//    { matchDate: '2016-03-26', homeScore: 0, awayScore: 4 },\n//    { matchDate: '2016-04-02', homeScore: 1, awayScore: 0 }\n//  ]\n//}\n```\n\nIn the example `numMatches` is defined as an `option`, not as an `attribute`. Therefore `numMatches` is not part of the output, it is only used to generate the `matches` array.\n\nIn the same example `seasonStart` is defined as an `attribute`, therefore it appears in the output, and can also be used in the generator function that creates the `matches` array.\n\n### Batch Specification of Attributes\n\nThe convenience function `attrs` simplifies the common case of specifying multiple attributes in a batch. Rewriting the `game` example from above:\n\n```js\nFactory.define('game')\n  .sequence('id')\n  .attrs({\n    is_over: false,\n    created_at: () =\u003e new Date(),\n    random_seed: () =\u003e Math.random(),\n  })\n  .attr('players', ['players'], (players) =\u003e {\n    /* etc. */\n  });\n```\n\n### Post Build Callback\n\nYou can also define a callback function to be run after building an object:\n\n```js\nFactory.define('coach')\n  .option('buildPlayer', false)\n  .sequence('id')\n  .attr('players', ['id', 'buildPlayer'], (id, buildPlayer) =\u003e {\n    if (buildPlayer) {\n      return [Factory.build('player', { coach_id: id })];\n    }\n  })\n  .after((coach, options) =\u003e {\n    if (options.buildPlayer) {\n      console.log('built player:', coach.players[0]);\n    }\n  });\n\nFactory.build('coach', {}, { buildPlayer: true });\n```\n\nMultiple callbacks can be registered, and they will be executed in the order they are registered. The callbacks can manipulate the built object before it is returned to the callee.\n\nIf the callback doesn't return anything, rosie will return build object as final result. If the callback returns a value, rosie will use that as final result instead.\n\n### Associate a Factory with an existing Class\n\nThis is an advanced use case that you can probably happily ignore, but store this away in case you need it.\n\nWhen you define a factory you can optionally provide a class definition, and anything built by the factory will be passed through the constructor of the provided class.\n\nSpecifically, the output of `.build` is used as the input to the constructor function, so the returned object is an instance of the specified class:\n\n```js\nclass SimpleClass {\n  constructor(args) {\n    this.moops = 'correct';\n    this.args = args;\n  }\n\n  isMoopsCorrect() {\n    return this.moops;\n  }\n}\n\ntestFactory = Factory.define('test', SimpleClass).attr('some_var', 4);\n\ntestInstance = testFactory.build({ stuff: 2 });\nconsole.log(JSON.stringify(testInstance, {}, 2));\n// Output:\n// {\n//   \"moops\": \"correct\",\n//   \"args\": {\n//     \"stuff\": 2,\n//     \"some_var\": 4\n//   }\n// }\n\nconsole.log(testInstance.isMoopsCorrect());\n// Output:\n// correct\n```\n\nMind. Blown.\n\n## Usage in Node.js\n\nTo use Rosie in node, you'll need to import it first:\n\n```js\nimport { Factory } from 'rosie';\n// or with `require`\nconst Factory = require('rosie').Factory;\n```\n\nYou might also choose to use unregistered factories, as it fits better with node's module pattern:\n\n```js\n// factories/game.js\nimport { Factory } from 'rosie';\n\nexport default new Factory().sequence('id').attr('is_over', false);\n// etc\n```\n\nTo use the unregistered `Game` factory defined above:\n\n```js\nimport Game from './factories/game';\n\nconst game = Game.build({ is_over: true });\n```\n\nA tool like [babel](https://babeljs.io) is currently required to use this syntax.\n\nYou can also extend an existing unregistered factory:\n\n```js\n// factories/scored-game.js\nimport { Factory } from 'rosie';\nimport Game from './game';\n\nexport default new Factory().extend(Game).attrs({\n  score: 10,\n});\n```\n\n## Rosie API\n\nAs stated above the rosie factory signatures can be broken into factory definition and object creation.\n\nAdditionally factories can be defined and accessed via the Factory singleton, or they can be created and maintained by the callee.\n\n### Factory declaration functions\n\nOnce you have an instance returned from a `Factory.define` or a `new Factory()` call, you do the actual of work of defining the objects. This is done using the methods below (note these are typically chained together as in the examples above):\n\n#### Factory.define\n\n- **Factory.define(`factory_name`)** - Defines a factory by name. Return an instance of a Factory that you call `.attr`, `.option`, `.sequence`, and `.after` on the result to define the properties of this factory.\n- **Factory.define(`factory_name`, `constructor`)** - Optionally pass a constuctor function, and the objects produced by `.build` will be passed through the `constructor` function.\n\n#### instance.attr:\n\nUse this to define attributes of your objects\n\n- **instance.attr(`attribute_name`, `default_value`)** - `attribute_name` is required and is a string, `default_value` is the value to use by default for the attribute\n- **instance.attr(`attribute_name`, `generator_function`)** - `generator_function` is called to generate the value of the attribute\n- **instance.attr(`attribute_name`, `dependencies`, `generator_function`)** - `dependencies` is an array of strings, each string is the name of an attribute or option that is required by the `generator_function` to generate the value of the attribute. This list of `dependencies` will match the parameters that are passed to the `generator_function`\n\n#### instance.attrs:\n\nUse this as a convenience function instead of calling `instance.attr` multiple times\n\n- **instance.attrs(`{attribute_1: value_1, attribute_2: value_2, ...}`)** - `attribute_i` is a string, `value_i` is either an object or generator function.\n\nSee `instance.attr` above for details. Note: there is no way to specify dependencies using this method, so if you need that, you should use `instance.attr` instead.\n\n#### instance.option:\n\nUse this to define options. Options do not appear in the generated object, but they can be used in a `generator_function` that is used to configure an attribute or sequence that appears in the generated object. See the [Programmatic Generation Of Attributes](#programmatic-generation-of-attributes) section for examples.\n\n- **instance.option(`option_name`, `default_value`)** - `option_name` is required and is a string, `default_value` is the value to use by default for the option\n- **instance.option(`option_name`, `generator_function`)** - `generator_function` is called to generate the value of the option\n- **instance.option(`option_name`, `dependencies`, `generator_function`)** - `dependencies` is an array of strings, each string is the name of an option that is required by the `generator_function` to generate the value of the option. This list of `dependencies` will match the parameters that are passed to the `generator_function`\n\n#### instance.sequence:\n\nUse this to define an auto incrementing sequence field in your object\n\n- **instance.sequence(`sequence_name`)** - define a sequence called `sequence_name`, set the start value to 1\n- **instance.sequence(`sequence_name`, `generator_function`)** - `generator_function` is called to generate the value of the sequence. When the `generator_function` is called the pre-incremented sequence number will be passed as the first parameter, followed by any dependencies that have been specified.\n- **instance.sequence(`sequence_name`, `dependencies`, `generator_function`)** - `dependencies` is an array of strings, each string is the name of an attribute or option that is required by the `generator_function` to generate the value of the option. The value of each specified dependency will be passed as parameters 2..N to the `generator_function`, noting again that the pre-incremented sequence number is passed as the first parameter.\n\n#### instance.after:\n\n- **instance.after(`callback`)** - register a `callback` function that will be called at the end of the object build process. The `callback` is invoked with two params: (`build_object`, `object_options`). See the [Post Build Callback](#post-build-callback) section for examples.\n\n### Object building functions\n\n#### build\n\nReturns an object that is generated by the named factory. `attributes` and `options` are optional parameters. The `factory_name` is required when calling against the rosie Factory singleton.\n\n- **Factory.build(`factory_name`, `attributes`, `options`)** - when build is called against the rosie Factory singleton, the first param is the name of the factory to use to build the object. The second is an object containing attribute override key value pairs, and the third is a object containing option key value pairs\n- **instance.build(`attributes`, `options`)** - when build is called on a factory instance only the `attributes` and `options` objects are necessary\n\n#### buildList\n\nIdentical to `.build` except it returns an array of built objects. `size` is required, `attributes` and `options` are optional\n\n- **Factory.buildList(`factory_name`, size, `attributes`, `options`)** - when buildList is called against the rosie Factory singleton, the first param is the name of the factory to use to build the object. The `attributes` and `options` behave the same as the call to `.build`.\n- **instance.buildList(size, `attributes`, `options`)** - when buildList is called on a factory instance only the size, `attributes` and `options` objects are necessary (strictly speaking only the size is necessary)\n\n### Testing\n\nYou may find `resetAll` useful when working with testing frameworks such as Jest. It resets any build state, such as sequences, to their original values:\n\n```js\nimport Factory from 'rosie';\n\nbeforeEach(() =\u003e {\n  Factory.resetAll();\n});\n```\n\nOr call `reset` on a specific factory:\n\n```js\nimport Game from './game';\n\nbeforeEach(() =\u003e {\n  Game.reset();\n});\n```\n\n## Contributing\n\n1.  Fork it\n1.  Create your feature branch (`git checkout -b my-new-feature`)\n1.  Install the test dependencies (`npm install` - requires NodeJS)\n1.  Make your changes and make sure the tests pass (`npm test`)\n1.  Commit your changes (`git commit -am 'Added some feature'`)\n1.  Push to the branch (`git push origin my-new-feature`)\n1.  Create new Pull Request\n\n## Credits\n\nThanks to [Daniel Morrison](http://twitter.com/danielmorrison/status/58883772040486912) for the name and [Jon Hoyt](http://twitter.com/jonmagic) for inspiration and brainstorming the idea.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frosiejs%2Frosie","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frosiejs%2Frosie","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frosiejs%2Frosie/lists"}