{"id":13500818,"url":"https://github.com/Yaffle/EventSource","last_synced_at":"2025-03-29T07:31:51.842Z","repository":{"id":40655413,"uuid":"1475331","full_name":"Yaffle/EventSource","owner":"Yaffle","description":"a polyfill for http://www.w3.org/TR/eventsource/","archived":false,"fork":false,"pushed_at":"2024-05-18T19:20:29.000Z","size":620,"stargazers_count":2151,"open_issues_count":42,"forks_count":338,"subscribers_count":44,"default_branch":"master","last_synced_at":"2025-03-25T23:16:18.359Z","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":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Yaffle.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-03-13T18:48:26.000Z","updated_at":"2025-03-21T21:08:16.000Z","dependencies_parsed_at":"2022-07-14T04:50:33.702Z","dependency_job_id":"4fc3763e-5f14-4efb-ae6f-1edbd8bd76cb","html_url":"https://github.com/Yaffle/EventSource","commit_stats":{"total_commits":336,"total_committers":41,"mean_commits":8.195121951219512,"dds":0.1607142857142857,"last_synced_commit":"03e44c8ea3d83012c3f27da2a2052061b4b4cdd8"},"previous_names":[],"tags_count":33,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yaffle%2FEventSource","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yaffle%2FEventSource/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yaffle%2FEventSource/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yaffle%2FEventSource/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Yaffle","download_url":"https://codeload.github.com/Yaffle/EventSource/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246155998,"owners_count":20732355,"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","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-07-31T22:01:15.328Z","updated_at":"2025-03-29T07:31:51.552Z","avatar_url":"https://github.com/Yaffle.png","language":"JavaScript","readme":"EventSource polyfill - https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events\n========================================================\n\nПожалуйста не используйте эту обосранную библиотеку!\n\nInstalling:\n-----------\n\nYou can get the code from npm or bower:\n\n```\nnpm install event-source-polyfill\n```\n\n```\nbower install event-source-polyfill\n```\n\nJust include `src/eventsource.js` or `src/eventsource.min.js` in your page to use the polyfill.\n\n\nIonic2/Angular2 Installation:\n-----------------------------\n\nUnless a typescript definition file is created for this polyfill, this is how you would use it in an Ionic2 project.  It should (in theory) be very similar in an Angular2 project.\n\n```\nnpm install event-source-polyfill\n```\n\nAdd to (or create) src/app/polyfills.ts (path is relative to where polyfills.ts is) :\n```\nimport 'path/to/event-source-polyfill/src/eventsource.min.js'\n```\n\nAdd anywhere you need access to EventSourcePolyfill class : \n\n```\ndeclare var EventSourcePolyfill: any;\n```\n\nUsage with webpack/browserify:\n------------------------------\n\n```javascript\nimport { NativeEventSource, EventSourcePolyfill } from 'event-source-polyfill';\n\nconst EventSource = NativeEventSource || EventSourcePolyfill;\n// OR: may also need to set as global property\nglobal.EventSource =  NativeEventSource || EventSourcePolyfill;\n```\n\nBrowser support:\n----------------\n\n* IE 10+, Firefox 3.5+, Chrome 3+, Safari 4+, Opera 12+\n* IE 8 - IE 9: XDomainRequest is used internally, which has some limitations (2KB padding in the beginning is required, no way to send cookies, no way to use client certificates)\n* It works on Mobile Safari, Opera Mobile, Chrome for Android, Firefox for Android\n* It does not work on: Android Browser(requires 4 KB padding after every chunk), Opera Mini\n\nAdvantages:\n-----------\n\n* Simple server-side code\n* Cross-domain requests support\n\nServer-side requirements:\n-------------------------\n\n* \"Last-Event-ID\" is sent in a query string (CORS + \"Last-Event-ID\" header is not supported by all browsers)\n* It is required to send 2 KB padding for IE \u003c 10 and Chrome \u003c 13 at the top of the response stream (the polyfill sends `padding=true` query argument)\n* You need to send \"comment\" messages each 15-30 seconds, these messages will be used as heartbeat to detect disconnects - see https://bugzilla.mozilla.org/show_bug.cgi?id=444328\n\nSpecification:\n--------------\n\n* http://www.w3.org/TR/eventsource/\n\nBuild:\n------\n\n* To build EventSource, just install npm modules (`npm install`) and then run the build (`npm run build`). It should generate a new version of `src/eventsource.min.js`.\n\nNotes:\n-----\n * If you are using HTTP Basic Authentication, you can embed credentials into the URL - `http://username:password@github.com`.\n\nCustom Headers:\n---------------\n```\nvar es = new EventSourcePolyfill('/events', {\n  headers: {\n    'X-Custom-Header': 'value'\n  }\n});\n```\n\nCustom query parameter name for the last event id:\n---------------\n * Some server require a special query parameter name for last-event-id, you can change that via option\n * The default is `lastEventId`\n * Example for mercure-hub (https://mercure.rocks/)\n  \n```\nvar es = new EventSourcePolyfill(hubUrl, {\n  lastEventIdQueryParameterName: 'Last-Event-Id'\n});\n```\n\nOther EventSource polyfills:\n----------------------------\n\n* https://github.com/remy/polyfills/blob/master/EventSource.js by Remy Sharp\n* https://github.com/rwldrn/jquery.eventsource by Rick Waldron\n* https://github.com/amvtek/EventSource by AmvTek\n\nEXAMPLE\n-------\n\n\n\nserver-side (node.js)\n---------------------\n\n```javascript\nvar PORT = 8081;\n\nvar http = require(\"http\");\nvar fs = require(\"fs\");\nvar url = require(\"url\");\n\nhttp.createServer(function (request, response) {\n  var parsedURL = url.parse(request.url, true);\n  var pathname = parsedURL.pathname;\n  if (pathname === \"/events.php\") {\n\n    response.writeHead(200, {\n      \"Content-Type\": \"text/event-stream\",\n      \"Cache-Control\": \"no-store\",\n      \"Access-Control-Allow-Origin\": \"*\"\n    });\n\n    var padding = new Array(2049);\n    response.write(\":\" + padding.join(\" \") + \"\\n\"); // 2kB padding for IE\n    response.write(\"retry: 2000\\n\");\n\n    var lastEventId = Number(request.headers[\"last-event-id\"]) || Number(parsedURL.query.lastEventId) || 0;\n\n    var timeoutId = 0;\n    var i = lastEventId;\n    var c = i + 100;\n    var f = function () {\n      if (++i \u003c c) {\n        response.write(\"id: \" + i + \"\\n\");\n        response.write(\"data: \" + i + \"\\n\\n\");\n        timeoutId = setTimeout(f, 1000);\n      } else {\n        response.end();\n      }\n    };\n\n    f();\n\n    response.on(\"close\", function () {\n      clearTimeout(timeoutId);\n    });\n\n  } else {\n    if (pathname === \"/\") {\n      pathname = \"/index.html\";\n    }\n    if (pathname === \"/index.html\" || pathname === \"../src/eventsource.js\") {\n      response.writeHead(200, {\n        \"Content-Type\": pathname === \"/index.html\" ? \"text/html\" : \"text/javascript\"\n      });\n      response.write(fs.readFileSync(__dirname + pathname));\n    }\n    response.end();\n  }\n}).listen(PORT);\n```\n\nor use PHP (see php/events.php)\n-------------------------------\n```php\n\u003c?php\n\n  header(\"Content-Type: text/event-stream\");\n  header(\"Cache-Control: no-store\");\n  header(\"Access-Control-Allow-Origin: *\");\n\n  $lastEventId = floatval(isset($_SERVER[\"HTTP_LAST_EVENT_ID\"]) ? $_SERVER[\"HTTP_LAST_EVENT_ID\"] : 0);\n  if ($lastEventId == 0) {\n    $lastEventId = floatval(isset($_GET[\"lastEventId\"]) ? $_GET[\"lastEventId\"] : 0);\n  }\n\n  echo \":\" . str_repeat(\" \", 2048) . \"\\n\"; // 2 kB padding for IE\n  echo \"retry: 2000\\n\";\n\n  // event-stream\n  $i = $lastEventId;\n  $c = $i + 100;\n  while (++$i \u003c $c) {\n    echo \"id: \" . $i . \"\\n\";\n    echo \"data: \" . $i . \";\\n\\n\";\n    ob_flush();\n    flush();\n    sleep(1);\n  }\n\n?\u003e\n```\n\nindex.html (php/index.html):\n----------------------------\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"utf-8\" /\u003e\n    \u003ctitle\u003eEventSource example\u003c/title\u003e\n    \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"\u003e\n    \u003cscript src=\"../src/eventsource.js\"\u003e\u003c/script\u003e\n    \u003cscript\u003e\n      var es = new EventSource(\"events.php\");\n      var listener = function (event) {\n        var div = document.createElement(\"div\");\n        var type = event.type;\n        div.appendChild(document.createTextNode(type + \": \" + (type === \"message\" ? event.data : es.url)));\n        document.body.appendChild(div);\n      };\n      es.addEventListener(\"open\", listener);\n      es.addEventListener(\"message\", listener);\n      es.addEventListener(\"error\", listener);\n    \u003c/script\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\nUsage in node.js:\n=================\nWith some dynamic imports it may work in node.js:\n\nInstall the library and the dependency:\n`npm install @titelmedia/node-fetch`\n`npm install event-source-polyfill`\n\nx.js:\n```javascript\n// The @titelmedia/node-fetch is used instead of node-fetch as it supports ReadableStream Web API\nimport('@titelmedia/node-fetch').then(function (fetch) {\n  globalThis.fetch = fetch.default;\n  globalThis.Response = fetch.default.Response;\n  import('event-source-polyfill').then(function (x) {\n    var es = new x.default.EventSourcePolyfill('http://localhost:8004/events');\n    es.onerror = es.onopen = es.onmessage = function (event) {\n      console.log(event.type + ': ' + event.data);\n    };\n  });\n});\n```\n\n`node --experimental-modules ./x.js`\n\nLicense\n-------\nThe MIT License (MIT)\n\nCopyright (c) 2012 vic99999@yandex.ru\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","funding_links":[],"categories":["JavaScript","24. 前后端交互"],"sub_categories":["24.2 SSE (Server-Sent Events)"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FYaffle%2FEventSource","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FYaffle%2FEventSource","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FYaffle%2FEventSource/lists"}